/*
Chatting script
*/
var windowFocus = true;
var username;
var chatHeartbeatCount = 0;
var minChatHeartbeat = 5000;
var maxChatHeartbeat = 7000;
var chatHeartbeatTime = minChatHeartbeat;
var originalTitle;
var blinkOrder = 0;
var chatboxFocus = new Array();
var newMessages = new Array();
var newMessagesWin = new Array();
var chatBoxes = new Array();

//$(document).ready(function(){
function startChatFunction()
{  		
	originalTitle = document.title;
	$([window, document]).blur(function(){
		windowFocus = false;
	}).focus(function(){
		windowFocus = true;
		document.title = originalTitle;
	});
	var from_user = $('#username').val(); 
	$('#chatbox_MSCHAT').show('slow');
	$("#chatingName").val(''); 
	
	$.get("chat.php?action=checkMyName", { } , function(data){								
		if(data)
			$("#chatingName").val("customer_"+data); 
			
		$.get("chat.php?action=showminimize", { } , function(data){
			if(data != '')													 
				$("#openchatbox").html(data);
				$.get("chat.php?action=showopenchatbox", { } , function(data){											 
					var res = new Array();
					res = data.split("#$#");
					for( var x=0; x+1<res.length; x++ )
						if(res[x] != '')
							openChat(res[x]);
							
					chatHeartbeatCount=1;
					chatHeartbeat();
				});
		});
	});
	draggableBox();
	flasher();
	
}


function connectwithadmin()
{
	if( $('.chatmainbox').length <= 0)
	{	
		if($("#openchatbox").html())
		{
			$("#openchatbox").toggle();
		}
		else
		{
			$('#sendRequest').css({left:'40%',top:'25%',width:'325px',height:'325px'});
			$('#sendRequest').html('<div class="chatmainbox" id="chatmainbox"><div class="chatheaderbox" id="chatbox" flasherchatbox=0><div class="chatboxtitle">Chat with us</div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:closeChatBox2()">X</a></div><br clear="all"/></div><div class="chatboxcontent" id="chatboxcontent" style="font-weight:bold;text-align:center">Please click below on who you want to chat with : <br><br><a href="javascript:void(0)" onclick="javascript:connectwithadmin2(5)"><img src="includes/languages/english/images/buttons/button_sales_rep.gif" style="border:0"></a><br><br><a href="javascript:void(0)" onclick="javascript:connectwithadmin2(8)"><img src="includes/languages/english/images/buttons/button_technical.gif" style="border:0"></a></div></div>');
			$('#sendRequest').slideDown(2000);
		}
	}
}
function connectwithadmin2(chattingtype)
{
	$('#sendRequest').slideUp(2000,function(){
		$('#sendRequest').html('<div class="chatmainbox" id="chatmainbox"><div class="chatheaderbox" id="chatbox" flasherchatbox=0><div class="chatboxtitle">Chat with us</div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:closeChatBox2()">X</a></div><br clear="all"/></div><div class="chatboxcontent" id="chatboxcontent" style="font-weight:bold;text-align:center"><br /><br /> Please wait ...<br /><br /> <img src="images/loading3.gif" /></div></div>');
		$('#sendRequest').slideDown(2000,function(){					  
			startchatwithavailableadmins(chattingtype);
		});
	});
}


function startchatwithavailableadmins(chattingtype)
{
	if($("#customerName").val() == '')
	{
		$.get("chat.php?action=createName", {} , function(data){
			$("#chatingName").val("customer_"+data); 
			$.get("chat.php?action=chooseAdmin", {chattingtype:chattingtype} , function(data1){
				if(data1 != 0)
				{
					$.get("chat.php?action=sendchat", {to:data1, message:'Live Chat Customer - Auto Msg', from: $("#chatingName").val()} , function(data2){
						if(data2 == "1")
						{
							$("#sendRequest").slideUp(2000,function(){
								$("#chatmainbox").remove();																		
								openChat(data1);
								if(chatHeartbeatCount == 0)
								{
									chatHeartbeatCount=1;
									chatHeartbeat();
								}
							});
						}
					});
				}else
				{
					$("#chatingName").val('');
					$("#chatboxcontent").html("<br>All our representatives are currently busy assisting other customer please Leave your name number and our representatives will call you Click Here which will link to <br><a href='http://www.2mcctv.com/contact_us.html' style='color:#0000ff' target='_blank'> Contact Us </a> ");
				}
			});
		});
	}else
	{
		$("#chatingName").val($("#customerName").val()); 
		$.get("chat.php?action=chooseAdmin", {chattingtype:chattingtype} , function(data1){									   
				if(data1 != 0)
				{
					$.get("chat.php?action=sendchat", {to:data1, message: 'Live Chat Customer - Auto Msg', from: $("#chatingName").val()} , function(data2){
						if(data2 == "1")
						{
							$("#sendRequest").slideUp(2000,function(){
								$("#chatmainbox").remove();																		
								openChat(data1);
								if(chatHeartbeatCount == 0)
								{
									chatHeartbeatCount=1;
									chatHeartbeat();
								}
							});
						}
					});
				}else
				{
					$("#chatingName").val('');
					$("#chatboxcontent").html("<br /><br /> Sorry ... <br /> There is no available supporters now ... <br /> Chat in other time");
				}
			});
	}
}
//});
/* --------------------------- Ahmad ---------------------------- */
function flasher()
{
	//alert("asdasdasdasd");  
	$("div > [flasher='1']").toggleClass('headerminimizeboxflasher');
	$("div > [flasherchatbox='1']").toggleClass('chatheaderboxflasher');
//	$("#whosonline [flasherminimize='1']").toggleClass('minimizechatflasher');
	if($("#whosonline").attr('flasherminimize')==1)
	{
		$("#whosonline").toggleClass('minimizechatflasher22');	
	}
	setTimeout("flasher();",1000);
}
function chatHeartbeat()
{
	return; // stop chat
	
	if($("#customerName").val() != '')
		$("#chatingName").val($("#customerName").val());
		
	if($("#chatingName").val() == '' )	
	{
		chatHeartbeatCount=0;
		return ;
	}

	var chatingName=$("#chatingName").val();
	$.get("chat.php?action=chatHeartbeat", { chatingName: chatingName} , function(data){					 					   
		if(data != '')
		{
			var res = new Array();
			res = data.split("#$#"); 
			for(var x=0;x+1 < res.length ;x++)
			{
				if(res[x] != '')
				{
					if($("#minimizebox"+res[x]).length > 0)
					{
						$("#minimizebox"+res[x]).attr('flasher',1);
						$("#whosonline").attr('flasherminimize',1);
					}else
					{
						if($("#chatmainbox_"+res[x]).length > 0)
						{
							fetchHistory(res[x]);
							$("#chatbox_"+res[x]).attr("flasherchatbox","1");
							showontop("#chatmainbox_"+res[x]);
						}else
						{
							minimizebox2();
							openChat(res[x]);
							$("#chatbox_"+res[x]).attr("flasherchatbox","1");
						}
					}
				}
			}
		}
		setTimeout("chatHeartbeat();",5000);
	});
}

function minimizebox(boxName)
{
	$("#chatmainbox_"+boxName).slideUp(2000,function(){
		$(this).remove();
		if($("#minimizebox"+boxName).length <= 0)
		{
			$("#openchatbox").append("<div id='minimizebox"+boxName+"' class='headerminimizebox' flasher='0' ><div class='chatboxtitle' onclick=javascript:chatWith(\'"+boxName+"\') >"+boxName+"</div><div class='chatboxoptions'><a href='javascript:void(0)' class='minimizelink' onclick=javascript:closeMinimizeChatBox(\'"+boxName+"\')>X</a></div><br clear='all'/></div>");					 
			$.get("chat.php?action=minimizeChatBox", { chatuser: boxName} , function(data){});
		}
	});
}

function minimizebox2()
{
	$('#sendRequest').slideUp(2000,function(){
		$("#sendRequest").html(' ');
	});
}

function chatWith(chatuser) {
	openChat(chatuser);
	if( $("div > [flasher='1']").length <= 0 )
	{
		$("#whosonline").attr('flasherminimize','0');	
		$("#whosonline").removeClass('minimizechatflasher22');
	}
	$("#chatmainbox_"+chatuser+" .chatboxtextarea").focus();
	
}

function closeMinimizeChatBox(boxName){
	var from = $('#chatingName').val();
	$('#minimizebox'+boxName).remove();
	$.get("chat.php?action=sendchat", {to: boxName, message: 'This Customer Left - Auto Msg', from: from} , function(data){
		$.get("chat.php?action=closechat", { chatbox: boxName} , function(data){
	   		$("#chatingName").val('');
		});
	});
	$.get("chat.php?action=logoff", {} , function(data){
	});
}
/* --------------------------- Ahmad ---------------------------- */
  function draggableBox()
  {
	  /*
	  	$(".chatheaderbox").mouseover(function () {
		    $(this).css("cursor","pointer");
			$(this).parent().draggable();
		});
		$(".chatheaderbox").mousedown(function () {
			$(this).css("cursor","move");
		});
		$(".chatheaderbox").mouseup(function () {
			$(this).css("cursor","pointer");
		});*/
		$(".chatmainbox").mousedown(function () {
			showontop(this);	
		});
		$(".chatboxtextarea").keydown(function(){
			var id=$(this).parent().attr("id");								   
			var id2=$("#"+id).parent().attr("id");								   
			var id3=$("#"+id2+" div:first").attr("id");
			$("#"+id3).attr('flasherchatbox','0');
			$("#"+id3).removeClass('chatheaderboxflasher');
			$("#"+id3).addClass('chatheaderbox');
		});
		$(".chatmainbox").click(function(){
			var id=$(this).attr("id");
		 	var id2=$("#"+id+" div:first").attr("id");
			var id3=$("#"+id+" div:last textarea").attr("id");

			$("#"+id2).attr('flasherchatbox','0');
			$("#"+id2).removeClass('chatheaderboxflasher');
			$("#"+id2).addClass('chatheaderbox');
			$("#"+id3).focus();
		});

  }
  function showontop(box)
  {
		$(".chatmainbox").css("z-index",10);							
		$(box).css("z-index",15);
  }
  
  function openChat(chatuser)
  {
	openChatBox(chatuser);
	// check if already exist
	if ($("#chatmainbox_"+chatuser).length > 0) 
	{
		if ($("#chatmainbox_"+chatuser).css('display') == 'none')
		{
			$("#chatmainbox_"+chatuser).css('display','block');
		}
		showontop("#chatmainbox_"+chatuser);
		$("#chatmainbox_"+chatuser+" .chatboxtextarea").focus();
		return;
	}
		
	  $("#chatingDiv").html('<div class="chatmainbox" id="chatmainbox_'+chatuser+'" style="left:45%;top:40%;width:225px;height:300px;z-index:12;display:none"><div class="chatheaderbox" id="chatbox_'+chatuser+'" flasherchatbox=0><div class="chatboxtitle">'+chatuser+'</div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:minimizebox(\''+chatuser+'\')" id="minimizeboxchat_'+chatuser+'">-</a> <a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+chatuser+'\')">X</a></div><br clear="all"/></div><div class="chatboxcontent" id="chatboxcontent_'+chatuser+'" style="height:183px"></div><div class="chatboxinput" id="chatboxinput_'+chatuser+'" style="text-align:center" ><textarea id="chatboxtextarea_'+chatuser+'" style="display:none" class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+chatuser+'\');"></textarea></div></div>');
	  $("#chatmainbox_"+chatuser).slideDown(2000,function(){
			$("#chatboxtextarea_"+chatuser).slideDown(800);											  
	  });
	  
	  draggableBox();
	  showontop("#chatmainbox_"+chatuser);
	  $("#chatmainbox_"+chatuser+" .chatboxtextarea").focus();
	   
	   // check Minimized or Not
	   if ($("#minimizebox"+chatuser).length > 0) 
	   {
			$("#minimizebox"+chatuser).remove();
			countminimizechatbox();
	   }
	   fetchHistory(chatuser);
  }
function countminimizechatbox()
{
	var numChatMinimized=$("#openchatbox > div").length; // count minimize chat box
	//$("#countchatminimized").html(numChatMinimized);
	if(numChatMinimized == 0)
	{
		$("#openchatbox").hide();		
		//$("#minimizechat").hide();
	}
}

function fetchHistory(chatuser)
{
	$.get("chat.php?action=fetchHistory", { chatuser: chatuser} , function(data){
		$("#chatboxcontent_"+chatuser).html(data);
		nDiv = document.getElementById("chatboxcontent_"+chatuser);
		setTimeout("nDiv.scrollTop = nDiv.scrollHeight",1);
	});
}
 
function openChatBox(chatboxtitle){
	$.get("chat.php?action=openchat", { chatbox: chatboxtitle} , function(data){
	});
}

function mschatWith(chatuser) {
	$('#chatbox_MSCHAT').show('slow');
}

function restructureChatBoxes() {
	align = 0;
	for (x in chatBoxes) {
		chatboxtitle = chatBoxes[x];

		if ($("#chatbox_"+chatboxtitle).css('display') != 'none') {
			if (align == 0) {
				$("#chatbox_"+chatboxtitle).css('right', '20px');
			} else {
				width = (align)*(225+7)+20;
				$("#chatbox_"+chatboxtitle).css('right', width+'px');
			}
			align++;
		}
	}
}

function closeChatBox2(){
	var chatboxtitle = $("#chatingName").val();
	$('#chatmainbox').remove();
	$.get("chat.php?action=closechat", { chatbox: chatboxtitle} , function(data){
	    $('#sendRequest').slideUp(2000,function(){
			$("#chatingName").val('');
		});
	});	
}

function closeChatBox(chatboxtitle){
	var from = $('#chatingName').val();
	$("#chatmainbox_"+chatboxtitle).remove();
	$.get("chat.php?action=sendchat", {to: chatboxtitle, message: 'This Customer Left - Auto Msg', from: from} , function(data){
		$.get("chat.php?action=closechat", { chatbox: chatboxtitle} , function(data){
	   		$("#chatingName").val('');
		});
	});
}


function toggleChatBoxGrowth(chatboxtitle) {
	if ($('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') == 'none') {  
		
		var minimizedChatBoxes = new Array();
		
		if ($.cookie('chatbox_minimized')) {
			minimizedChatBoxes = $.cookie('chatbox_minimized').split(/\|/);
		}

		var newCookie = '';

		for (i=0;i<minimizedChatBoxes.length;i++) {
			if (minimizedChatBoxes[i] != chatboxtitle) {
				newCookie += chatboxtitle+'|';
			}
		}

		newCookie = newCookie.slice(0, -1)


		$.cookie('chatbox_minimized', newCookie);
		$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','block');
		$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','block');
		$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
	} else {
		
		var newCookie = chatboxtitle;

		if ($.cookie('chatbox_minimized')) {
			newCookie += '|'+$.cookie('chatbox_minimized');
		}

		$.cookie('chatbox_minimized',newCookie);
		$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
		$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
	}
	
}


function toggleChatBox(chatboxtitle)
{
	$("#chatboxcontent_"+chatboxtitle).slideUp("slow");
	$("#chatboxinput_"+chatboxtitle).slideUp("slow");
}


function checkChatBoxInputKey(event,chatboxtextarea,chatboxtitle) {
	 var from = $('#chatingName').val();
	if(event.keyCode == 13 && event.shiftKey == 0)  
	{
		message = $(chatboxtextarea).val();
		message = message.replace(/^\s+|\s+$/g,"");
		$(chatboxtextarea).val('');
		$(chatboxtextarea).focus();
		$(chatboxtextarea).css('height','44px');
		if(message != '') {
			$("#chatboxinput_"+chatboxtitle).html('<img src="images/loading3.gif" >');
			$.get("chat.php?action=sendchat", {to: chatboxtitle, message: message, from: from} , function(data){
				message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
				$("#chatboxcontent_"+chatboxtitle).append('<div class="chatboxmessage"><b>Me</b>:&nbsp;<span class="chatboxmessagecontent">'+message+'</span></div>');
				$("#chatboxcontent_"+chatboxtitle).scrollTop($("#chatboxcontent_"+chatboxtitle)[0].scrollHeight);
				$("#chatboxinput_"+chatboxtitle).html('<textarea id=chatboxtextarea_'+chatboxtitle+' class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxtitle+'\');"></textarea>');
				$("#chatboxtextarea_"+chatboxtitle).focus();
				nDiv = document.getElementById("chatboxcontent_"+chatboxtitle);
				setTimeout("nDiv.scrollTop = nDiv.scrollHeight",1);
			});
		}
		chatHeartbeatTime = minChatHeartbeat;
		//chatHeartbeatCount = 1;
		return false;
	}

	var adjustedHeight = chatboxtextarea.clientHeight;
	var maxHeight = 94;

	if (maxHeight > adjustedHeight) {
		adjustedHeight = Math.max(chatboxtextarea.scrollHeight, adjustedHeight);
		if (maxHeight)
			adjustedHeight = Math.min(maxHeight, adjustedHeight);
		if (adjustedHeight > chatboxtextarea.clientHeight)
			$(chatboxtextarea).css('height',adjustedHeight+8 +'px');
	} else {
		$(chatboxtextarea).css('overflow','auto');
	}
	 
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
