var windowFocus = true;
var username;
var chatHeartbeatCount = 0;
var minChatHeartbeat = 3000;
var maxChatHeartbeat = 33000;
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(){
	originalTitle = document.title;
	startChatSession();
	$([window, document]).blur(function(){
		windowFocus = false;
	}).focus(function(){
		windowFocus = true;
		document.title = originalTitle;
	});
});

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 chatWith(chatuser,chatusername) {
//	alert("chatuser"+chatuser+"-chatusername-"+chatusername)
	createChatBox(chatuser,'',chatusername);
	$("#chatbox_"+chatuser+" .chatboxtextarea").focus();
}

function createChatBox(chatboxtitle,minimizeChatBox,titlename) {

	if ($("#chatbox_"+chatboxtitle).length > 0) {

		if ($("#chatbox_"+chatboxtitle).css('display') == 'none') {
			$("#chatbox_"+chatboxtitle).css('display','block');
			restructureChatBoxes();
		}
		$("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
		return;
	}
	$(" <div />" ).attr("id","chatbox_"+chatboxtitle).addClass("chatbox").html('<div class="chatboxhead"><div class="chatboxtitle">'+titlename+'</div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\')">_</a> <a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+chatboxtitle+'\')">X</a></div><br clear="all"/></div><div class="chatboxcontent"></div><div class="chatboxinput"><textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxtitle+'\',\''+titlename+'\');"></textarea></div>').appendTo($( "body" ));
	$("#chatbox_"+chatboxtitle).css('bottom', '0px');
	$("#chatbox_"+chatboxtitle).css('z-index', '1000');
	chatBoxeslength = 0;
	for (x in chatBoxes){	
		if ($("#chatbox_"+chatBoxes[x]).css('display') != 'none') {
      	              chatBoxeslength++;
		}
	}
	if (chatBoxeslength == 0) {
		$("#chatbox_"+chatboxtitle).css('right', '20px');
	} else {
		width = (chatBoxeslength)*(225+7)+20;
		$("#chatbox_"+chatboxtitle).css('right', width+'px');
	}

	chatBoxes.push(chatboxtitle);
	if (minimizeChatBox == 1) {
		minimizedChatBoxes = new Array();
		//alert(chatbox_minimized);
		if ($.cookie('chatbox_minimized')) {
      	                 minimizedChatBoxes = $.cookie('chatbox_minimized').split(/\|/);
		}
		minimize = 0;
		for (j=0;j<minimizedChatBoxes.length;j++) {
			if (minimizedChatBoxes[j] == chatboxtitle) {
				minimize = 1;
			}
		}
		if (minimize == 1) {
			$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
			$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
		}
	}
	chatboxFocus[chatboxtitle] = false;
	$("#chatbox_"+chatboxtitle+" .chatboxtextarea").blur(function(){
		chatboxFocus[chatboxtitle] = false;
		$("#chatbox_"+chatboxtitle+" .chatboxtextarea").removeClass('chatboxtextareaselected');
	}).focus(function(){
		chatboxFocus[chatboxtitle] = true;
		newMessages[chatboxtitle] = false;
		$('#chatbox_'+chatboxtitle+' .chatboxhead').removeClass('chatboxblink');
		$("#chatbox_"+chatboxtitle+" .chatboxtextarea").addClass('chatboxtextareaselected');
	});
	$("#chatbox_"+chatboxtitle).click(function() {
		if ($('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') != 'none') {
			$("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
		}
	});
	$("#chatbox_"+chatboxtitle).show();
}

function chatHeartbeat(){
       // alert("hi");
	var itemsfound = 0;
	if (windowFocus == false) {
		var blinkNumber = 0;
		var titleChanged = 0;
		for (x in newMessagesWin) {
			if (newMessagesWin[x] == true) {
				++blinkNumber;
				if (blinkNumber >= blinkOrder) {
					document.title = x+' says...';
					titleChanged = 1;
					break;
				}
			}
		}
		if (titleChanged == 0) {
			document.title = originalTitle;
			blinkOrder = 0;
		} else {
			++blinkOrder;
		}
	} else {
		for (x in newMessagesWin) {
			newMessagesWin[x] = false;
		}
	}

	for (x in newMessages) {
		if (newMessages[x] == true) {
			if (chatboxFocus[x] == false) {
                                    //FIXME: add toggle all or none policy, otherwise it looks funny
                                    $('#chatbox_'+x+' .chatboxhead').toggleClass('chatboxblink');
			}
		}
	}
	$.ajax({
	  url: SITEROOT+"/modules/chat/chat.php?action=chatheartbeat",
	  cache: false,
	  dataType: "json",
	  success: function(data) {
			$.each(data.items, function(i,item){
				if (item)	{ // fix strange ie bug
					chatboxtitle = item.f;
					titlename = item.n;

					if ($("#chatbox_"+chatboxtitle).length <= 0) {


						createChatBox(chatboxtitle,'',titlename);
					}
					if ($("#chatbox_"+chatboxtitle).css('display') == 'none') {
						$("#chatbox_"+chatboxtitle).css('display','block');
						restructureChatBoxes();
					}
					if (item.s == 1) {
						item.n = username;
					}
					
					// alert(item.a+">>"+item.n+">>>"+item.s+">>"+item.m);
					
					if (item.s == 2) {
						$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
					}
					else if (item.s != 1)
					{
// 					   if(item.a == "1" )
// 					   {
                                                        newMessages[chatboxtitle] = true;
                                                        newMessagesWin[titlename] = true;
                                                        $("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.n+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
//					   }	
					}
					
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
					itemsfound += 1;
					/*
					if(item.a == "0" && item.s== 0)
					{									
                                                        $("#chatbox_"+chatboxtitle+" .chatboxinput").append('<div class="chatboxallow"><p>are you want to chat with '+titlename+'? </p><input type="button" name="yes" onclick="javascript:allowchat(\''+chatboxtitle+'\')" value="yes"><input type="button" name="no" value="no" onclick="javascript:closeChatBox(\''+chatboxtitle+'\')"></div>');
                                                      
                                                        $("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.n+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
                                                        
                                                         $('.chatboxcontent').css('display','none');
                                                         $('.chatboxtextarea').css('display','none');
					}*/				
				}
			});
			chatHeartbeatCount++;
			if (itemsfound > 0) {
				chatHeartbeatTime = minChatHeartbeat;
				chatHeartbeatCount = 1;
			} else if (chatHeartbeatCount >= 10) {
				chatHeartbeatTime *= 2;
				chatHeartbeatCount = 1;
				if (chatHeartbeatTime > maxChatHeartbeat) {
					chatHeartbeatTime = maxChatHeartbeat;
				}
			}
			setTimeout('chatHeartbeat();',chatHeartbeatTime);
		}
	});
}



function closeChatBox(chatboxtitle) {
        //alert('hi');
	$('#chatbox_'+chatboxtitle).css('display','none');
	restructureChatBoxes();
	$.post(SITEROOT+"/modules/chat/chat.php?action=closechat", { chatbox: chatboxtitle} , function(data){
	});
}



function toggleChatBoxGrowth(chatboxtitle) {	//alert(chatboxtitle+"Me");
	if ($('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display') == 'none') {
		//alert(chatboxtitle);
		var minimizedChatBoxes = new Array();
		if ($.cookie('chatbox_minimized')) {
		//alert($.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 checkChatBoxInputKey(event,chatboxtextarea,chatboxtitle,titlename) {
	if(event.keyCode == 13 && event.shiftKey == 0)  {
	
	if(username =="")
	{
	  username ='me';
	}
		
		message = $(chatboxtextarea).val();
		message = message.replace(/^\s+|\s+$/g,"");
		$(chatboxtextarea).val('');
		$(chatboxtextarea).focus();
		$(chatboxtextarea).css('height','44px');
		if (message != '') {
				$.post(SITEROOT+"/modules/chat/chat.php?action=sendchat", {to: chatboxtitle, message: message ,toname: titlename} , function(data){
				message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
				$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+username+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+message+'</span></div>');
				$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
			});
		}
		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');
	}
}



function startChatSession(){
	$.ajax({
		url: SITEROOT+"/modules/chat/chat.php?action=startchatsession",
	  	cache: false,
	  	dataType: "json",
	  	success: function(data) {
			username = data.username;
			$.each(data.items, function(i,item){
				if (item){ // fix strange ie bug
					chatboxtitle = item.f;
					titlename = item.n;
					if ($("#chatbox_"+chatboxtitle).length <= 0) {
						createChatBox(chatboxtitle,1,titlename);
					}
					if (item.s == 1) {
						item.n = username;
					}
					if (item.s == 2) {
						$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
					} else {
					
					if(item.n =="")
					{ item.n ="me"; }					
						$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom"> '+item.n+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
					}
					
					
					
					
				}
			});
			for (i=0;i<chatBoxes.length;i++) {
				chatboxtitle = chatBoxes[i];
				$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
				setTimeout('$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);', 70); // yet another strange ie bug
			}
			setTimeout('chatHeartbeat();',chatHeartbeatTime);
		}
	});
}


function allowchat(chatboxtitle) {        
       // alert('hi2');
         $('.chatboxallow').css('display','none');
	$.post(SITEROOT+"/modules/chat/chat.php?action=allowchat", { chatbox: chatboxtitle} , function(data){
	chatHeartbeat();
	});
	
	
	 $('.chatboxcontent').css('display','block');	
           $('.chatboxtextarea').css('display','block');	
           $('.chatboxallow').css('display','none');	
}

/**

 * 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

 *

 */



$.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
		}

      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 = $.trim(cookies[i]);
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
           return cookieValue;
	}	
};

