var windowFocus = true;
var username;
var chatHeartbeatCount = 0;
var minChatHeartbeat = 1000;
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();

var sounds = {
	newmessage:'components/com_xchat/assets/sounds/incomingmessage.swf',
	contactonline : 'components/com_xchat/assets/sounds/contactonline.swf',
	contactoffline : 'components/com_xchat/assets/sounds/contactoffline.swf'
};


$(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][1];

		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(userString) {
	if (username.split(/\|/)[1] == '0') {
		window.location.href = "?component=signup";
		return 0;
	}
	createChatWindow(userString);
	$("#chatbox_"+userString.split(/-/)[1]+" .chatboxtextarea").focus();
}

function createBoxInfomation(userString) {
	var splitedUserString = userString.split(/-/);
	$(' <div />').attr('id','chatbox_'+splitedUserString[1])
	.addClass('chatbox')
	.html('<div class="chatboxhead"><div class="chatboxtitle"><a href="javascript:void(0);" onclick="window.location.href=\'?component=profileview&id='+splitedUserString[1]+'\'">'+splitedUserString[0]+'</a></div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+splitedUserString[0]+'-'+splitedUserString[1]+'\')">X</a></div><br clear="all"/></div><div class="chatboximage"><img src="?component=xchat&action=getAvatar&wid='+splitedUserString[1]+'" alt="'+splitedUserString[0]+'" /><div id="chatboxstatus_'+splitedUserString[1]+'" class="chatboxstatus"><b>She is now <span style="color:#2fd53e;">online</span></b><br /><br /><a href="javascript:void(0);" onclick="chatWith(\''+userString+'\')" id="chatwith_'+splitedUserString[1]+'" style="color:#000;font-weight:bold;"><span style="color:#2fd53e;font-weight:bold;">Chat</span> now</a></div><br clear="both" /></div>')
	.appendTo( $('body') );
	
	$("#chatbox_"+splitedUserString[1]).css('bottom', '0px');
	
	chatBoxeslength = 0;

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

	if (chatBoxeslength == 0) {
		$("#chatbox_"+splitedUserString[1]).css('right', '20px');
	} else {
		width = (chatBoxeslength)*(225+7)+20;
		$("#chatbox_"+splitedUserString[1]).css('right', width+'px');
	}
	
	//chatBoxes.push(Array(splitedUserString[0],splitedUserString[1], 'inf'));
	
	chatboxFocus[splitedUserString[1]] = false;

	$("#chatbox_"+splitedUserString[1]).show();
	restructureChatBoxes();
}

function createChatWindow(userString, minimazed) {
	var splitedUserString = userString.split(/-/);
	//alert($('#chatbox_'+splitedUserString[1]+' .chatboxcontent'));
	if ($('#chatbox_'+splitedUserString[1]).attr('id') != null && $('#chatwith_'+splitedUserString[1]).attr('id') != null) {
		//alert($('#chatwith_'+splitedUserString[1]).attr('id'));
		$('#chatbox_'+splitedUserString[1])
		.html('<div class="chatboxhead"><div class="chatboxtitle"><a href="javascript:void(0);" onclick="window.location.href=\'?component=profileview&id='+splitedUserString[1]+'\'">'+splitedUserString[0]+'</a></div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+splitedUserString[1]+'\')">-</a> <a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+splitedUserString[0]+'-'+splitedUserString[1]+'\')">X</a></div><br clear="all"/></div><div class="chatboximage"><img src="?component=xchat&action=getAvatar&wid='+splitedUserString[1]+'" alt="'+splitedUserString[0]+'" /><div id="chatboxstatus_'+splitedUserString[1]+'" class="chatboxstatus"></div><br clear="both" /></div><div class="chatboxcontent"></div><div class="chatboxinput"><textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+splitedUserString[1]+'\',\''+splitedUserString[0]+'\');"></textarea></div>');
	} else {
		$(' <div />').attr('id','chatbox_'+splitedUserString[1])
		.addClass('chatbox')
		.html('<div class="chatboxhead"><div class="chatboxtitle"><a href="javascript:void(0);" onclick="window.location.href=\'?component=profileview&id='+splitedUserString[1]+'\'">'+splitedUserString[0]+'</a></div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+splitedUserString[1]+'\')">-</a> <a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+splitedUserString[0]+'-'+splitedUserString[1]+'\')">X</a></div><br clear="all"/></div><div class="chatboximage"><img src="?component=xchat&action=getAvatar&wid='+splitedUserString[1]+'" alt="'+splitedUserString[0]+'" /><div id="chatboxstatus_'+splitedUserString[1]+'" class="chatboxstatus"></div><br clear="both" /></div><div class="chatboxcontent"></div><div class="chatboxinput"><textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+splitedUserString[1]+'\',\''+splitedUserString[0]+'\');"></textarea></div>')
		.appendTo( $('body') );
	}
	
	$("#chatbox_"+splitedUserString[1]).css('bottom', '0px');
	
	chatBoxeslength = 0;

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

	if (chatBoxeslength == 0) {
		$("#chatbox_"+splitedUserString[1]).css('right', '20px');
	} else {
		width = (chatBoxeslength)*(225+7)+20;
		$("#chatbox_"+splitedUserString[1]).css('right', width+'px');
	}
	
	chatBoxes.push(Array(splitedUserString[0],splitedUserString[1]));
	
	if (minimazed == 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] == splitedUserString[1]) {
				minimize = 1;
			}
		}

		if (minimize == 1) {
			$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
			$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
		}
	}
	
	chatboxFocus[splitedUserString[1]] = false;

	$("#chatbox_"+splitedUserString[1]+" .chatboxtextarea").blur(function(){
		chatboxFocus[splitedUserString[1]] = false;
		$("#chatbox_"+splitedUserString[1]+" .chatboxtextarea").removeClass('chatboxtextareaselected');
	}).focus(function(){
		chatboxFocus[splitedUserString[1]] = true;
		newMessages[splitedUserString[1]] = false;
		$('#chatbox_'+splitedUserString[1]+' .chatboxhead').removeClass('chatboxblink');
		$("#chatbox_"+splitedUserString[1]+" .chatboxtextarea").addClass('chatboxtextareaselected');
	});

	$("#chatbox_"+splitedUserString[1]).click(function() {
		if ($('#chatbox_'+splitedUserString[1]+' .chatboxcontent').css('display') != 'none') {
			$("#chatbox_"+splitedUserString[1]+" .chatboxtextarea").focus();
		}
	});
	
	$("#chatbox_"+splitedUserString[1]).show();
	restructureChatBoxes();
}

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 playMusic(music) {
	if ($('chatmusic'))
		$('chatmusic').remove();
	$(' <div />').attr('id', 'chatmusic')
	.html('<embed src="'+music+'" width="1" height="1" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash">')
	.appendTo($('body'));
	
}

function chatHeartbeat(){

	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.split(/-/)[0]+' says...';
					titleChanged = 1;
					break;
				}
			}
		}
		
		if (titleChanged == 0) {
			document.title = originalTitle;
			blinkOrder = 0;
		} else {
			++blinkOrder;
		}

	} else {
		for (x in newMessagesWin) {
			if (chatboxFocus[x] == true)
			newMessagesWin[x] = false;
		}
	}

	for (x in newMessages) {
		//alert(chatboxFocus);
		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: "?component=xchat&action=chatHeartbeat",
	  cache: false,
	  dataType: "json",
	  success: function(data) {

		$.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug

				chatboxtitle = item.f.split(/-/)[1];

				if ($("#chatbox_"+chatboxtitle).length <= 0) {
					createChatWindow(item.f);
				}
				if ($("#chatbox_"+chatboxtitle).css('display') == 'none') {
					$("#chatbox_"+chatboxtitle).css('display','block');
					restructureChatBoxes();
				}
				
				if (item.s == 1) {
					item.f = username;
				}

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

				$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
				itemsfound += 1;
			}
		});
		$.each(data.statuses, function(i,status){
			if (status) {
				//alert(status.f + status.status);
				if (status.status == 1) {
					if ($('#chatboxstatus_'+status.f.split(/-/)[1]+' .chatonline').length == 0)
						$(' <div />').addClass('chatonline').text('').appendTo($('#chatboxstatus_'+status.f.split(/-/)[1]));
		
					if ($('#chatboxstatus_'+status.f.split(/-/)[1]+' .chatonline').text() == 'Offline') {
						playMusic(sounds.contactonline);
					}
					$('#chatboxstatus_'+status.f.split(/-/)[1]+' .chatonline').text('Online')
					.css({'color':'#2fd53e'});
				} else {
					if ($('#chatboxstatus_'+status.f.split(/-/)[1]+' .chatonline').text() == 'Online') {
						playMusic(sounds.contactoffline);
					}
					$('#chatboxstatus_'+status.f.split(/-/)[1]+' .chatonline').text('Offline')
					.css({'color':'#d52f2f'});
				}
				itemsfound += 1;
			}
		});
		$.each(data.nowonline, function(i,onlines){
			if (onlines) {
				//alert(onlines.f);
				createBoxInfomation(onlines.f);
				itemsfound += 1;
				playMusic(sounds.contactonline);
			}
		});
		$.each(data.creditscount, function(i,credits){
			if (credits) {
				for(x in chatBoxes) {
					if (chatBoxes[x][2] != 'inf') {
					if ($("#chatboxstatus_"+chatBoxes[x][1]+" .chatminutes").length == 0)
						$(' <div />').addClass('chatminutes').text('').appendTo($("#chatboxstatus_"+chatBoxes[x][1]));
					
					minutes = credits.data / 1; // count credits div on time amount
					
					var time;
					
					var Hours = Math.floor(minutes/60);
					var Minutes = minutes%60;
					
					time = Hours+":"+Minutes;
					$("#chatboxstatus_"+chatBoxes[x][1]+" .chatminutes").text("Time left: "+time);
                                        }
				}
			}
		});
		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) {
	$('#chatbox_'+chatboxtitle.split(/-/)[1]).css('display','none');
	restructureChatBoxes();

	$.post("?component=xchat&action=closeChat", { chatbox: chatboxtitle} , function(data){	
	});
}

function startChatSession(){  
	$.ajax({
	  url: "?component=xchat&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.split(/-/)[1];
				//alert(chatboxtitle);
				if ($("#chatbox_"+chatboxtitle).length <= 0) {
					createChatWindow(item.f,1);
				}
				
				if (item.s == 1) {
					item.f = username.split(/\|/)[0];
				}

				if (item.s == 2) {
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
				} else {
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f.split(/-/)[0]+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
				}
			}
		});
		
		for (i=0;i<chatBoxes.length;i++) {
			chatboxtitle = chatBoxes[i][1];
			$("#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
		}
	
	setTimeout('chatHeartbeat();',chatHeartbeatTime);
		
	}});
}

function checkChatBoxInputKey(event,chatboxtextarea,chatboxtitle,toUsername) {
	 
	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 != '') {
			$.post("?component=xchat&action=sendchat", {to: toUsername+'-'+chatboxtitle, message: message}, function(data){
				//alert(data);
				$.each(data.items, function(i,item){
					if (item) {
						if (item.s == '2') {
							$("#chatbox_"+item.f.split(/-/)[1]+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo">'+item.m+'</span></div>');
						} else if (item.s == '1') {
							item.f = username.split(/\|/)[0];
							message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
							$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+':&nbsp;&nbsp;</span><span class="chatboxmessagecontent">'+message+'</span></div>');
						}
						$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
					}
				});
			}, "json");
		}
		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;
    }
};

