var windowFocus = true;
var username;
var chatHeartbeatCount = 0;
var minChatHeartbeat = 1000;
var maxChatHeartbeat = 2000;
var chatHeartbeatTime = minChatHeartbeat;
var originalTitle;
var blinkOrder = 0;
var align;

var chatboxFocus = new Array();
var newMessages = new Array();
var newMessagesWin = new Array();
var chatBoxes = new Array();

var chatsound = null;
var chatboxuserid = null;
var otherusertyping = false;

var refreshInterval = null;
var chatInterval = null;

function playSound()
{
	if (chatsound == null)
	{
		chatsound = document.createElement('embed');
		chatsound.setAttribute('src', 'chat/chatsound.mp3');
		chatsound.setAttribute('autostart', true);
		chatsound.setAttribute('hidden', true);
		chatsound.setAttribute('type', 'audio/mpeg');
		document.body.appendChild(chatsound);
	}
	else
	{
		document.body.removeChild(chatsound);
		chatsound = document.createElement('embed');
		chatsound.setAttribute('src', 'chat/chatsound.mp3');
		chatsound.setAttribute('autostart', true);
		chatsound.setAttribute('hidden', true);
		chatsound.setAttribute('type', 'audio/mpeg');
		document.body.appendChild(chatsound);
	}
}

$(document).ready(function(){
	originalTitle = document.title;
	startChatSession();
	$([window, document]).blur(function(){
		windowFocus = false;
	}).focus(function(){
		windowFocus = true;
		document.title = originalTitle;
	});
});

function restructureChatBoxes() {
	if ($("#chatbox_"+chatboxtitle) != null)
	{
		$("#chatbox_"+chatboxtitle).draggable({containment: "body", handle: " .chatboxhead"});
		$("#chatbox_"+chatboxtitle+" .chatboxhead").each(function() {
		  this.onselectstart = function() { return false; };
		});
	}
	for (x in chatBoxes) {
		chatboxtitle = chatBoxes[x];
		if ($("#chatbox_"+chatboxtitle).css('display') != 'none') {
			if (chatBoxeslength == 0) {
				$("#chatbox_"+chatBoxeslength).css('left', '165px');
			} 
		}
	}
}

function chatWith(chatuser,chatuserid) {
	var chatuserfixed = chatuser.replace(" ", "_");
	chatboxuserid = chatuserid;
	createChatBox(chatuserfixed);
}

function checkChatBoxLength(cbtitle,cbuid)
{
	var message =$("#chatbox_"+cbtitle+" .chatboxtextarea").val();	
	$.ajax({
	  url: "chatserver.php",
	  data: "action=usertyping&msglength="+message.length+"&cbuserid="+cbuid,
	  success: function(data) {
		  if (data == 'true')
		  {
			  otherusertyping = true;
			  if (refreshInterval != null)
			  {
				clearInterval(refreshInterval);
			  }
			  refreshInterval = setInterval('TellOtherUser(\''+cbtitle+'\',\''+otherusertyping+'\',\''+cbuid+'\');', 2000);
		  }
		  else
		  {
			  otherusertyping = false;
			  if (refreshInterval != null)
			  {
				clearInterval(refreshInterval);
			  }
			  refreshInterval = setInterval('TellOtherUser(\''+cbtitle+'\',\''+otherusertyping+'\',\''+cbuid+'\');', 2000);
		  }
	  }
	});
}

function TellOtherUser(chatboxtitle,tellotherusertype,cbuserid){
	$.ajax({
	  url: "chatserver.php",
	  data: "action=tellusertyping&usertyping="+tellotherusertype+"&cbuserid="+cbuserid,
	  success: function(data) {
		  if (data == 'true')
		  {
			  $("#chatbox_"+chatboxtitle+" .chatboxtyping").css('display', 'block');
		  }
		  else
		  {
			  $("#chatbox_"+chatboxtitle+" .chatboxtyping").css('display', 'none');
		  }
	  }
	});
}

function createChatBox(chatboxtitle,minimizeChatBox) {
	if ($("#chatbox_"+chatboxtitle).length > 0) {
		if ($("#chatbox_"+chatboxtitle).css('display') == 'none') {
			$("#chatbox_"+chatboxtitle).css('display','block');
			restructureChatBoxes();
		}
		$("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
		return;
	}
	
	var chatboxtitlefix = chatboxtitle.replace("_", " ");
	chatboxtitlefirstname = chatboxtitle.split("_");
	chatboxtitlefirstname = chatboxtitlefirstname[0];
	
	$(" <div />" ).attr("id","chatbox_"+chatboxtitle)
	.addClass("chatbox")
	.html('<div class="chatboxhead"><div class="chatboxtitle"><img style="float:left" width="16px" height="16px" title='+chatboxtitlefirstname+' alt='+chatboxtitlefirstname+' src=\'showimage.php?id='+chatboxuserid+'\' />&nbsp;&nbsp;<a href="#" onclick="return false" onmouseup="javascript:toggleProfileNoLoad(\''+chatboxuserid+'\');">'+chatboxtitlefix+'</a></div><div class="chatboxoptions"><img style="float:left;margin-top:2px;margin-right:20px" class="chatboxtyping" src="Images/icon_typing.gif" width="10px" height="10px" title=\''+chatboxtitlefirstname+' is typing...\' /><a href="#" onmouseup="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\')" title="Minimize Window" onclick=\"return false\">-</a> <a href="#" title="Close Window" onclick=\"return false\" onmouseup="javascript:closeChatBox(\''+chatboxtitle+'\')">X</a></div><br clear="all"/></div><div class="chatboxcontent"></div><div class="chatboxinput"><textarea class="chatboxtextarea" onkeyup="javascript:return checkChatBoxLength(\''+chatboxtitle+'\',\''+chatboxuserid+'\');" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxtitle+'\');"></textarea></div>').appendTo($("body"));
			   
	$("#chatbox_"+chatboxtitle).css('bottom', '0px');
	
	chatBoxeslength = 0;

	for (x in chatBoxes) {
		if ($("#chatbox_"+chatBoxes[x]).css('display') != 'none') {
			chatBoxeslength++;
		}
	}

	if (chatBoxeslength == 0) {
		$("#chatbox_"+chatboxtitle).css('left', '190px');
	} 
	else if (chatBoxeslength == 1)
			{
				width = (190*chatBoxeslength)+230;
				$("#chatbox_"+chatboxtitle).css('left', width+'px');
			}
			else if (chatBoxeslength == 2)
			{
				width = (190*chatBoxeslength)+300;
				$("#chatbox_"+chatboxtitle).css('left', width+'px');
			}
			else if (chatBoxeslength == 3)
			{
				width = (190*chatBoxeslength)+370;
				$("#chatbox_"+chatboxtitle).css('left', width+'px');
			}
			else
			{
				width = (190*chatBoxeslength)+455;
				$("#chatbox_"+chatboxtitle).css('left', width+'px');
			}
	
	chatBoxes.push(chatboxtitle);

	if (minimizeChatBox == 1) {
		minimizedChatBoxes = new Array();

		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).draggable({containment: "body", handle: " .chatboxhead"});
	
	$("#chatbox_"+chatboxtitle+" .chatboxhead").each(function() {
      this.onselectstart = function() { return false; };
    });
	
	$("#chatbox_"+chatboxtitle).fadeIn(500);
	$("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();
}

function chatCheck(){

	var itemsfound = 0;
	
	if (windowFocus == false) {
 
		var blinkNumber = 0;
		var titleChanged = 0;
		for (x in newMessagesWin) {
			if (newMessagesWin[x] == true) {
				++blinkNumber;
				if (blinkNumber >= blinkOrder) {
					x = x.replace("_", " ");
					document.title = 'Chat message from '+x+'!';
					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) {
				$('#chatbox_'+x+' .chatboxhead').toggleClass('chatboxblink');
			}
		}
	}
	
	$.ajax({
	  url: "chatserver.php?action=chatcheck",
	  dataType: "json",
	  async: true,
	  cache: "false",
	  success: function(data) {

		$.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug
				
				chatboxtitle = item.f;
				
				chatboxuserid = item.i;
				
				if ($("#chatbox_"+chatboxtitle).length <= 0) {
					createChatBox(chatboxtitle);
				}
				if ($("#chatbox_"+chatboxtitle).css('display') == 'none') {
					$("#chatbox_"+chatboxtitle).css('display','block');
					restructureChatBoxes();
				}	

				if (item.s == 1) {
					item.f = username;
					item.i = chatboxuserid;
				}

				if (item.s == 2) {
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
				} else {
					item.f = item.f.replace("_", " ");
					newMessages[chatboxtitle] = true;
					newMessagesWin[chatboxtitle] = true;
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
				}

				$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
				itemsfound += 1;
			}
		});

		chatHeartbeatCount++;

		if (itemsfound > 0) {
			chatHeartbeatTime = minChatHeartbeat;
			chatHeartbeatCount = 1;
			playSound();
		} else if (chatHeartbeatCount >= 10) {
			chatHeartbeatTime *= 2;
			chatHeartbeatCount = 1;
			if (chatHeartbeatTime > maxChatHeartbeat) {
				chatHeartbeatTime = maxChatHeartbeat;
			}
		}
		
		if (chatInterval != null)
		{
			clearInterval(chatInterval);
		}
	    chatInterval = setInterval('chatCheck();', chatHeartbeatTime);
	}});
}

function closeChatBox(chatboxtitle) {
	if (chatBoxes.length <= 1)
	{
		if (refreshInterval != null)
		{
			clearInterval(refreshInterval);
		}	
	}
	$('#chatbox_'+chatboxtitle).css('display','none');
	restructureChatBoxes();

	$.post("chatserver.php?action=closechat", { chatbox: chatboxtitle} , function(data){	
	});

}

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 checkChatBoxInputKey(event,chatboxtextarea,chatboxtitle) {
	 
	if(event.keyCode == 13 && event.shiftKey == 0)  {
		message = $(chatboxtextarea).val();
		message = message.replace(/^\s+|\s+$/g,"");

		$(chatboxtextarea).val('');
		$(chatboxtextarea).focus();
		$(chatboxtextarea).css('height','50px');
		if (message != '') {
			$.post("chatserver.php?action=sendmsg", { to: chatboxtitle, toid: chatboxuserid, message: message} , function(data){
				message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
				usernamefix = username.replace("_", " ");
				$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+usernamefix+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+message+'</span></div>');
				$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
			});
		}
		return false;
	}
}

function startChatSession(){  
	$.ajax({
	  url: "chatserver.php?action=startchatsession",
	  dataType: "json",
	  cache: "false",
	  success: function(data) {
		
		if (data != null)
		{
			
		username = data.username;
		
		$.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug

				chatboxtitle = item.f;
				chatboxtitleglobal = item.f;
				
				chatboxuserid = item.i;
				
				if ($("#chatbox_"+chatboxtitle).length <= 0) {
					createChatBox(chatboxtitle,1);
				}
				
				if (item.s == 1) {
					item.f = username;
					item.i = chatboxuserid;
				}

				if (item.s == 2) {
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
				} else {
					item.f = item.f.replace("_", " ");
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&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);', 100); // yet another strange ie bug
		}
		if (chatInterval != null)
		{
			clearInterval(chatInterval);
		}
	    chatInterval = setInterval('chatCheck();', chatHeartbeatTime);
		}
	}});
}

/**
 * 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;
    }
};
