/*

Copyright (c) 2009 Anant Garg (anantgarg.com | inscripts.com)

This script may be used for non-commercial purposes only. For any
commercial purposes, please contact the author at 
anant.garg@inscripts.com

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/

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();

//Variables para el arreglo que hace que se actualicen las capas
//de los chats de cada usuario.
var cantAmigos = 0;
var amigosChat = new Array();
var contAmigos = 0;

$(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, imagenEstado) {
//function chatWith(chatuser, imagenEstado) {
	//createChatBox(chatuser, imagenEstado);
	createChatBox(chatuser);
	cambiaImagenEstado(chatuser, imagenEstado);
	$("#chatbox_"+chatuser+" .chatboxtextarea").focus();
}

function cambiaImagenEstado(chatuser, imagenEstado){
	//$("#chatbox_"+chatuser+" .chatboxtextarea").focus();
	$('#capaImagenEstado_'+chatuser+'').html('<img src="../images/'+imagenEstado+'" width="8" height="8" border="0">');
}



/////////
function createUsersBox(chatboxtitle,minimizeChatBox) {
	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("chatboxconectados")

	.html('<table width="140" height="" border="0" cellpadding="0" cellspacing="0"><tr><td width="13" height="23"><img src="../images/chat1.png" width="13" height="23" /></td><td width="114" height="23" valign="middle" background="../images/chat2.png"><div class="chatboxhead"><div class="chatboxtitle"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowthUsers(\''+chatboxtitle+'\')"><font color="#FFFFFF">'+chatboxtitle+'</font></a></div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+chatboxtitle+'\')"><font color="#FFFFFF">X</font></a></div><br clear="all"/></div></td><td width="13" height="23"><img src="../images/chat3.png" width="13" height="23" /></td></tr><tr><td colspan="3" background="../images/blocktexto.png" width="140" height=""><div id="listaActu" class="chatboxcontentconectados"></div></td></tr><tr><td width="13" height="29"><img src="../images/barra_user1.png" width="13" height="29" /></td><td width="114" height="29" background="../images/barra_user2.png">&nbsp;</td><td width="13" height="29"><img src="../images/barra_user3.png" width="13" height="29" /></td></tr></table>')

	.appendTo($( "body" ));
	

	//Separamos 30px hacia arriba del pie de la pagina el div
	$("#chatbox_"+chatboxtitle).css('bottom', '0px');
	
	//Separamos 2% de la orilla izquierda el div
	$("#chatbox_"+chatboxtitle).css('margin-left', '2%');
	
	//Le agregamos borders a la capa de la lista de usuarios conectados
	/*
	$("#chatbox_"+chatboxtitle).css('border-left', '1px solid #cccccc');
	$("#chatbox_"+chatboxtitle).css('border-right', '1px solid #cccccc');
	$("#chatbox_"+chatboxtitle).css('border-bottom', '1px solid #eeeeee');
	*/
	
	//Hacemos a la izquierda la ventana
	//$("#chatbox_"+chatboxtitle).css('margin-left', '200px');
	//$("#chatbox_"+chatboxtitle).css('margin-right', '200px');	
	
	//Minizamos el chat cuando se abre
	//toggleChatBoxGrowthUsers(chatboxtitle);
	
	/*
	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();

		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+' .chatboxfoot').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 enArreglo(cadena, arreglo){
	var i;
	for(i=0; i<arreglo.length; i++){
		if(cadena == arreglo[i]){
			//alert(cadena + ' == ' + arreglo[i] + ' - ' + i);
			return true;
		}
	}
	
	return false;
}

function createChatBox(chatboxtitle, minimizeChatBox) {
//function createChatBox(chatboxtitle, imagenEstado, minimizeChatBox) {
	//Si no haz abierto la conversacion con chatboxtitle, este se agrega al arreglo de amigosChat
	if(!enArreglo(chatboxtitle, amigosChat)){
		amigosChat[contAmigos] = chatboxtitle;
		contAmigos++;
		$.cookie('cookieAmigosChat', amigosChat);		
	}
	
	//alert($.cookie('cookieAmigosChat'));	

	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('<table width="225" height="" border="0" cellpadding="0" cellspacing="0"><tr><td width="13"><img src="../images/chat1.png" width="13" height="23" /></td><td width="199" valign="middle" background="../images/chat2.png" class="estiloBarra"><div class="chatboxhead"><div class="chatboxtitle"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\')"><font color="#FFFFFF">'+chatboxtitle+'</font></a></div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\')"><font color="#FFFFFF">-</font></a> <a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+chatboxtitle+'\')"><font color="#FFFFFF">X</font></a></div><br clear="all"/></div></td><td><img src="../images/chat3.png" width="13" height="23" /></td></tr><tr><td colspan="3" valign="top"><div class="chatboxcontent"></div><div class="chatboxinput"><table width="195" border="0" cellpadding="0" cellspacing="0" align="center"><tr><td width="10" height="7"><img src="../images/chatusuarios_1.png" width="10" height="7"></td><td width="175" height="7" background="../images/chatusuarios2.png"></td><td width="10" height="7"><img src="../images/chatusuarios_31.png" width="10" height="7"></td></tr><tr><td width="10" height="34" background="../images/chatusuarios2.png"></td><td width="175" height="34" background="../images/chatusuarios2.png"><textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxtitle+'\');"></textarea></td><td width="10" height="34" background="../images/chatusuarios2.png"></td></tr><tr><td width="10" height="7"><img src="../images/chatusuarios_3.png" width="10" height="7"></td><td width="175" height="7" background="../images/chatusuarios2.png"></td><td width="10" height="7"><img src="../images/chatusuarios_33.png" width="10" height="7"></td></tr></table></div></td></tr><tr><td width="13"><img src="../images/barra_user1.png" width="13" height="29" /></td><td background="../images/barra_user2.png"><table width="190" height="" border="0" cellpadding="0" cellspacing="0"><tr><td width="20"><img src="../images/puntogreen.png" width="8" height="8"></td><td><div class="chatboxhead"><div class="chatboxtitle"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\')"><font color="#FFFFFF">'+chatboxtitle+'</font></a></div></div></td><td valign="middle" align="center"><div class="chatboxhead"><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+chatboxtitle+'\')"><font color="#FFFFFF">X</font></a></div></div></td></tr></table></td><td width="13"><img src="../images/barra_user3.png" width="13" height="29" /></td></tr></table>')
	*/
	
	.html('<table width="225" height="" border="0" cellpadding="0" cellspacing="0"><tr><td colspan="3"><div class="chatboxtitulo"><table border="0" cellpadding="0" cellspacing="0"><tr><td width="13"><img src="../images/chat1.png" width="13" height="23" /></td><td width="199" valign="middle" background="../images/chat2.png" class="estiloBarra"><div class="chatboxhead"><div class="chatboxtitle"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\')"><font color="#FFFFFF">'+chatboxtitle+'</font></a></div><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\')"><font color="#FFFFFF">-</font></a> <a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+chatboxtitle+'\')"><font color="#FFFFFF">X</font></a></div><br clear="all"/></div></td><td><img src="../images/chat3.png" width="13" height="23" /></td></tr></table></div></td></tr><tr><td colspan="3" valign="top"><div id="capaChat_'+chatboxtitle+'" class="chatboxcontent"></div><div class="chatboxinput"><table width="210" border="0" cellpadding="0" cellspacing="0" align="center"><tr><td width="10" height="7"><img src="../images/chatusuarios_1.png" width="10" height="7"></td><td width="190" height="7" background="../images/chatusuarios2.png"></td><td width="10" height="7"><img src="../images/chatusuarios_31.png" width="10" height="7"></td></tr><tr><td width="10" height="34" background="../images/chatusuarios2.png"></td><td width="190" height="34" background="../images/chatusuarios2.png"><textarea class="chatboxtextarea" onkeydown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxtitle+'\');"></textarea></td><td width="10" height="34" background="../images/chatusuarios2.png"></td></tr><tr><td width="10" height="7"><img src="../images/chatusuarios_3.png" width="10" height="7"></td><td width="190" height="7" background="../images/chatusuarios2.png"></td><td width="10" height="7"><img src="../images/chatusuarios_33.png" width="10" height="7"></td></tr></table></div></td></tr><tr><td width="13"><img src="../images/barra_user1.png" width="13" height="29" /></td><td background="../images/barra_user2.png"><table width="190" height="" border="0" cellpadding="0" cellspacing="0"><tr><td width="20"><div id="capaImagenEstado_'+chatboxtitle+'"></div></td><td><div class="chatboxfoot"><a href="javascript:void(0)" onclick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\')"><font color="#FFFFFF">'+chatboxtitle+'</font></a></div></td><td valign="middle" align="center"><div class="chatboxhead"><div class="chatboxoptions"><a href="javascript:void(0)" onclick="javascript:closeChatBox(\''+chatboxtitle+'\')"><font color="#FFFFFF">X</font></a></div></div></td></tr></table></td><td width="13"><img src="../images/barra_user3.png" width="13" height="29" /></td></tr></table>')	
	.appendTo($( "body" ));



	$("#chatbox_"+chatboxtitle).css('bottom', '0px');
	$("#chatbox_"+chatboxtitle).css('z-index', '11');
	
	//Minizamos el chat cuando se abre
	//toggleChatBoxGrowth(chatboxtitle);
	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();

		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+' .chatboxfoot').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(){

	var itemsfound = 0;
	var contAvisosMensajes = 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+' dice...';
					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) {
				contAvisosMensajes++;

				//FIXME: add toggle all or none policy, otherwise it looks funny
				$('#chatbox_'+x+' .chatboxhead').toggleClass('chatboxblink');
				$('#chatbox_'+x+' .chatboxfoot').toggleClass('chatboxblink');
				/*
				if(contAvisosMensajes == 1){
					soundManager.play('nuevoMensaje');
				}
				*/
			}
		}
	}

	$.ajax({
	  url: "../chat.php?action=chatheartbeat",
	  cache: false,
	  dataType: "json",
	  success: function(data) {
	  //var cont = 0;

		$.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug
				//cont++;

				chatboxtitle = item.f;
				/*
				//Aqui refrescamos la ventana del chat.
				if(cont == 1){
					//alert(chatboxtitle);
					$('#capaChat_'+chatboxtitle+'').html('');
				}
				*/
				
				if ($("#chatbox_"+chatboxtitle).length <= 0) {
					//createChatBox(chatboxtitle, imagenEstado);
					createChatBox(chatboxtitle);
				}
				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[chatboxtitle] = true;
					newMessagesWin[chatboxtitle] = true;
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+' dice:&nbsp;&nbsp;<br></span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
					soundManager.play('nuevoMensaje');
				}

				$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
				itemsfound += 1;
			}
		});

		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) {
	//Actualizamos los tiempo de la actividad de los usuarios
	iniciarRelojTemporizador(true, true, true);
	$('#chatbox_'+chatboxtitle).css('display','none');
	restructureChatBoxes();

	$.post("../chat.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);
		$('#chatbox_'+chatboxtitle+' .chatboxtitulo').css('display','block');		
	} 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');
		$('#chatbox_'+chatboxtitle+' .chatboxtitulo').css('display','none');
	}
	
}

/////
function toggleChatBoxGrowthUsers(chatboxtitle) {
	if ($('#chatbox_'+chatboxtitle+' .chatboxcontentconectados').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+' .chatboxcontentconectados').css('display','block');
		$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','block');
		$("#chatbox_"+chatboxtitle+" .chatboxcontentconectados").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontentconectados")[0].scrollHeight);
	} else {
		
		var newCookie = chatboxtitle;

		if ($.cookie('chatbox_minimized')) {
			newCookie += '|'+$.cookie('chatbox_minimized');
		}


		$.cookie('chatbox_minimized',newCookie);
		$('#chatbox_'+chatboxtitle+' .chatboxcontentconectados').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,"");

		//Actualizamos los tiempo de la actividad de los usuarios
		iniciarRelojTemporizador(true, true, true);
		
		$(chatboxtextarea).val('');
		$(chatboxtextarea).focus();
		$(chatboxtextarea).css('height','44px');
		if (message != '') {
			message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
			message = message.wordWrap(20, "\n", true);
			$.post("../chat.php?action=sendchat", {to: chatboxtitle, message: message} , function(data){
				//message = message.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;");
				//message = message.wordWrap(20, "\n", true);
				$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+username+' dice:&nbsp;&nbsp;<br></span><span class="chatboxmessagecontent">'+message+'</span></div>');
				$("#chatbox_"+chatboxtitle+" .chatboxcontent").scrollTop($("#chatbox_"+chatboxtitle+" .chatboxcontent")[0].scrollHeight);
			});
		}
		
		chatHeartbeatTime = minChatHeartbeat;
		chatHeartbeatCount = 1;

		return false;
	}
	
	//Cerramos la ventana de la conversación con la tecla esc
	if(event.keyCode == 27 && event.shiftKey == 0)  {
		closeChatBox(chatboxtitle);
	}	

	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: "../chat.php?action=startchatsession",
	  cache: false,
	  dataType: "json",
	  success: function(data) {
	  var cont = 0;
	  var i;
		
		username = data.username;

		$.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug
				cont++;

				chatboxtitle = item.f;

				//Aqui refrescamos la ventana del chat.
				if(cont == 1){
					//alert(chatboxtitle);
					//$('#capaChat_'+chatboxtitle+'').html('');
					//$('#capaChat_soluna').html('');
					//Limpiamos todas las ventanas de chat para que no se repita
					//la conversacion al momento de la pulsación del chat.
					for(i=0; i<amigosChat.length; i++){
						$('#capaChat_'+amigosChat[i]+'').html('');					
					}
				}

				if ($("#chatbox_"+chatboxtitle).length <= 0) {
					//createChatBox(chatboxtitle, imagenEstado, 1);
					createChatBox(chatboxtitle, 1);
				}
				
				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 {
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+' dice:&nbsp;&nbsp;<br></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
		}
	
	//setTimeout('chatHeartbeat();',chatHeartbeatTime);
		
	}});
}

function startChatSession2(){  
	$.ajax({
	  url: "../chat.php?action=startchatsession",
	  cache: false,
	  dataType: "json",
	  success: function(data) {
	  var cont = 0;
	  var i;
		
		username = data.username;

		$.each(data.items, function(i,item){
			if (item)	{ // fix strange ie bug
				cont++;

				chatboxtitle = item.f;

				//Aqui refrescamos la ventana del chat.
				if(cont == 1){
					//alert(chatboxtitle);
					//$('#capaChat_'+chatboxtitle+'').html('');
					//$('#capaChat_soluna').html('');
					//Limpiamos todas las ventanas de chat para que no se repita
					//la conversacion al momento de la pulsación del chat.
					for(i=0; i<amigosChat.length; i++){
						$('#capaChat_'+amigosChat[i]+'').html('');					
					}
				}

				if ($("#chatbox_"+chatboxtitle).length <= 0) {
					//createChatBox(chatboxtitle, imagenEstado, 1);
					createChatBox(chatboxtitle, 1);
				}
				
				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 {
					$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+' dice:&nbsp;&nbsp;<br></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
		}
	
	//setTimeout('chatHeartbeat();',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;
    }
};