/*

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;
	alignMin = 0;
	//alert('entrando rest');
	if(screen.width == 800){
		var separacion = 20;
	} else {
		var separacion = (((screen.width-999-17)/2)+20);
	}
	
	for (x in chatBoxes) {
		chatboxtitle = chatBoxes[x];

		if ($("#chatbox_"+chatboxtitle).css('display') != 'none') {
			//alert('xD');
			if (align == 0) {
				$("#chatbox_"+chatboxtitle).css('right', separacion+'px');
				//$("#chatbox_"+chatboxtitle+"_minimizado").css('right', separacion+'px');
				//alert('rest if: ' + separacion + ' - ' + align);
			} else {
				width = (align)*(181+7);
				width = separacion+width;
				$("#chatbox_"+chatboxtitle).css('right', width+'px');
				//$("#chatbox_"+chatboxtitle+"_minimizado").css('right', width+'px');
				//alert('rest else: ' + width + ' - ' + align);
			}
			align++;
		} /*else {
			if (align == 0) {
				$("#chatbox_"+chatboxtitle+"_minimizado").css('right', separacion+'px');
				//$("#chatbox_"+chatboxtitle+"_minimizado").css('right', separacion+'px');
				//alert('rest if: ' + separacion + ' - ' + align);
			} else {
				width = (align)*(181+7);
				width = separacion+width;
				$("#chatbox_"+chatboxtitle+"_minimizado").css('right', width+'px');
				//$("#chatbox_"+chatboxtitle+"_minimizado").css('right', width+'px');
				//alert('rest else: ' + width + ' - ' + align);
			}
		}
		*/
		//alert('align2: ' + align);
	}
}

//Funcion que reestructura los chats minimziados
function restructureChatBoxesMin() {
	align = 0;
	//alert('entrando rest');
	if(screen.width == 800){
		var separacion = 20;
	} else {
		var separacion = (((screen.width-999-17)/2)+20);
	}
	
	for (x in chatBoxes) {
		chatboxtitle = chatBoxes[x];

		if ($("#chatbox_"+chatboxtitle+"_minimizado").css('display') != 'none') {
			//alert('xD');
			if (align == 0) {
				//$("#chatbox_"+chatboxtitle).css('right', separacion+'px');
				$("#chatbox_"+chatboxtitle+"_minimizado").css('right', separacion+'px');
				//alert('rest if: ' + separacion + ' - ' + align);
			} else {
				width = (align)*(181+7);
				width = separacion+width;
				//$("#chatbox_"+chatboxtitle).css('right', width+'px');
				$("#chatbox_"+chatboxtitle+"_minimizado").css('right', width+'px');
				//alert('rest else: ' + width + ' - ' + align);
			}
			align++;
		}
		//alert('align2: ' + 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">');
	$('#capaImagenEstado_'+chatuser+'_minimizado').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="143" height="29" border="0" cellpadding="0" cellspacing="0"><tr><td colspan="3" width="143" height="29" background="../images/bloque_conectados_01.png" align="center"><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></tr><tr><td width="4" background="../images/bloque_conectados_02.png"></td><td width="135" bgcolor="#000000"><div id="listaActu" class="chatboxcontentconectados"></div></td><td width="4" background="../images/bloque_conectados_04.png"></td></tr></table>')
	*/
	
	.html('<table width="164" height="67" border="0" cellpadding="0" cellspacing="0"><tr><td width="13" height="29"><img src="../images/bloque_conectados_01.png" width="13" height="29" alt=""></td><td width="139" height="29" background="../images/bloque_conectados_02.png" align="center"><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="12" height="29"><img src="../images/bloque_conectados_03.png" width="12" height="29" alt=""></td></tr><tr><td width="13" height="38" background="../images/bloque_conectados_04.png"></td><td width="139" height="38" bgcolor="#000000"><div id="listaActu" class="chatboxcontentconectados"></div></td><td width="12" height="38" background="../images/bloque_conectados_06.png"></td></tr></table>')
	
	.appendTo($( "body" ));
	

	//Separamos 30px hacia arriba del pie de la pagina el div
	$("#chatbox_"+chatboxtitle).css('bottom', '35px');
	
	//Separamos 2% de la orilla izquierda el div
	//Si la resolución es 800px de ancho la separacipon del bloque de conectados
	//es 18 pixeles
	if(screen.width == 800){
		var separacion = 18;
	} else {
		var separacion = (((screen.width-999-17)/2)+18);
	}
	
	$("#chatbox_"+chatboxtitle).css('margin-left', separacion+'px');
	
	//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();
		}
		alert('focus');
		//$('#chatbox_'+chatboxtitle+'_minimizado').css('display','none');
		$("#chatbox_"+chatboxtitle+" .chatboxtextarea").focus();

		return;
	}
	
	$(" <div />" ).attr("id","chatbox_"+chatboxtitle)
	.addClass("chatbox")
	
	.html('<table width="181" height="81" border="0" cellpadding="0" cellspacing="0"><tr><td colspan="3" width="181" height="46" background="../images/bloque_conversacion_01.png" align="center"><div class="chatboxhead"><div class="chatboxtitle"><a href="javascript:void(0)" onClick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\', false)"><font color="#FFFFFF">'+chatboxtitle+'</font></a></div><div class="chatboxoptions"><a href="javascript:void(0)" onClick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\', false)"><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></tr><tr><td width="4" background="../images/bloque_conversacion_02.png"></td><td width="173" bgcolor="#000000" valign="top"><div id="capaChat_'+chatboxtitle+'" class="chatboxcontent"></div><div class="chatboxinput" align="center"><table width="166" height="51" border="0" cellpadding="0" cellspacing="0"><tr><td width="12" height="11"><img src="../images/bloque_conver_texto_01.png" width="12" height="11" alt=""></td><td width="142" height="11" background="../images/bloque_conver_texto_02.png"></td><td width="12" height="11"><img src="../images/bloque_conver_texto_03.png" width="12" height="11" alt=""></td></tr><tr><td width="12" height="29" background="../images/bloque_conver_texto_04.png"></td><td width="142" height="29" bgcolor="#000000"><textarea class="chatboxtextarea" onKeyDown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxtitle+'\');"></textarea></td><td width="12" height="29" background="../images/bloque_conver_texto_06.png"></td></tr><tr><td width="12" height="11"><img src="../images/bloque_conver_texto_07.png" width="12" height="11" alt=""></td><td width="142" height="11" background="../images/bloque_conver_texto_08.png"></td><td width="12" height="11"><img src="../images/bloque_conver_texto_09.png" width="12" height="11" alt=""></td></tr></table></div></td><td width="4" background="../images/bloque_conversacion_04.png"></td></tr><tr><td colspan="3" width="181" height="35" background="../images/bloque_conversacion_05.png" align="center"><table width="170" height="" border="0" cellpadding="0" cellspacing="0"><tr><td width="20" align="center"><div id="capaImagenEstado_'+chatboxtitle+'"></div></td><td><div class="chatboxfoot"><a href="javascript:void(0)" onClick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\', false)"><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></tr></table>')


	.appendTo($( "body" ));

	$("#chatbox_"+chatboxtitle).css('bottom', '0px');
	$("#chatbox_"+chatboxtitle).css('z-index', '11');

	/*Chat minimizado
	$(" <div />" ).attr("id","chatbox_"+chatboxtitle+"_minimizado")
	
	.addClass("chatbox")
	.html('<table width="180" height="35" border="0" cellpadding="0" cellspacing="0"><tr><td width="181" height="35" background="../images/bloque_minimizado.png" align="center"><table width="170" height="" border="0" cellpadding="0" cellspacing="0"><tr><td width="20" align="center"><div id="capaImagenEstado_'+chatboxtitle+'_minimizado"></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></tr></table>')
	.appendTo($( "body" ));
	$("#chatbox_"+chatboxtitle+"_minimizado").css('bottom', '0px');
	$("#chatbox_"+chatboxtitle+"_minimizado").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(screen.width == 800){
		var separacion = 20;
	} else {
		var separacion = (((screen.width-999-17)/2)+20);
	}

	if (chatBoxeslength == 0) {
		$("#chatbox_"+chatboxtitle).css('right', separacion+'px');
		//$("#chatbox_"+chatboxtitle+"_minimizado").css('right', separacion+'px');
	} else {
		width = (chatBoxeslength)*(181+7);
		width = separacion+width;
		//alert(width + ' - ' + separacion);
		$("#chatbox_"+chatboxtitle).css('right', width+'px');
		//$("#chatbox_"+chatboxtitle+"_minimizado").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+"_minimizado").css('display', 'none');
	$("#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');
	$('#chatbox_'+chatboxtitle+'_minimizado').css('display','none');
	restructureChatBoxes();
	//restructureChatBoxesMin();

	$.post("../chat.php?action=closechat", { chatbox: chatboxtitle} , function(data){	
	});

}

function toggleChatBoxGrowth(chatboxtitle, maximizar) {
	//Maximizamos
	if(maximizar){
	//if ($('#chatbox_'+chatboxtitle).css('display') == 'none') {  
		//alert('max');
		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);
		/*Version anterior
		$('#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');
		*/
		
		//$("#chatbox_"+chatboxtitle).css('display','block');
		//$("#chatbox_"+chatboxtitle+"_minimizado").css('display','none');
		$("#chatbox_"+chatboxtitle).html('');
		$("#chatbox_"+chatboxtitle).html('<table width="181" height="81" border="0" cellpadding="0" cellspacing="0"><tr><td colspan="3" width="181" height="46" background="../images/bloque_conversacion_01.png" align="center"><div class="chatboxhead"><div class="chatboxtitle"><a href="javascript:void(0)" onClick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\', false)"><font color="#FFFFFF">'+chatboxtitle+'</font></a></div><div class="chatboxoptions"><a href="javascript:void(0)" onClick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\', false)"><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></tr><tr><td width="4" background="../images/bloque_conversacion_02.png"></td><td width="173" bgcolor="#000000" valign="top"><div id="capaChat_'+chatboxtitle+'" class="chatboxcontent"></div><div class="chatboxinput" align="center"><table width="166" height="51" border="0" cellpadding="0" cellspacing="0"><tr><td width="12" height="11"><img src="../images/bloque_conver_texto_01.png" width="12" height="11" alt=""></td><td width="142" height="11" background="../images/bloque_conver_texto_02.png"></td><td width="12" height="11"><img src="../images/bloque_conver_texto_03.png" width="12" height="11" alt=""></td></tr><tr><td width="12" height="29" background="../images/bloque_conver_texto_04.png"></td><td width="142" height="29" bgcolor="#000000"><textarea class="chatboxtextarea" onKeyDown="javascript:return checkChatBoxInputKey(event,this,\''+chatboxtitle+'\');"></textarea></td><td width="12" height="29" background="../images/bloque_conver_texto_06.png"></td></tr><tr><td width="12" height="11"><img src="../images/bloque_conver_texto_07.png" width="12" height="11" alt=""></td><td width="142" height="11" background="../images/bloque_conver_texto_08.png"></td><td width="12" height="11"><img src="../images/bloque_conver_texto_09.png" width="12" height="11" alt=""></td></tr></table></div></td><td width="4" background="../images/bloque_conversacion_04.png"></td></tr><tr><td colspan="3" width="181" height="35" background="../images/bloque_conversacion_05.png" align="center"><table width="170" height="" border="0" cellpadding="0" cellspacing="0"><tr><td width="20" align="center"><div id="capaImagenEstado_'+chatboxtitle+'"></div></td><td><div class="chatboxfoot"><a href="javascript:void(0)" onClick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\', false)"><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></tr></table>');
	} else {
		//alert('min');
		var newCookie = chatboxtitle;

		if ($.cookie('chatbox_minimized')) {
			newCookie += '|'+$.cookie('chatbox_minimized');
		}


		$.cookie('chatbox_minimized',newCookie);
		/*Version anterior
		$('#chatbox_'+chatboxtitle+' .chatboxcontent').css('display','none');
		$('#chatbox_'+chatboxtitle+' .chatboxinput').css('display','none');
		$('#chatbox_'+chatboxtitle+' .chatboxtitulo').css('display','none');
		*/
		
		//$("#chatbox_"+chatboxtitle).css('display','none');
		//$("#chatbox_"+chatboxtitle+"_minimizado").css('display','block');
		$("#chatbox_"+chatboxtitle).html('<table width="180" height="35" border="0" cellpadding="0" cellspacing="0"><tr><td width="181" height="35" background="../images/bloque_minimizado.png" align="center"><table width="170" height="" border="0" cellpadding="0" cellspacing="0"><tr><td width="20" align="center"><div id="capaImagenEstado_'+chatboxtitle+'_minimizado"></div></td><td><div class="chatboxfoot"><a href="javascript:void(0)" onClick="javascript:toggleChatBoxGrowth(\''+chatboxtitle+'\', true)"><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></tr></table>');
	}
	
}

/////
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;
		//alert('sesion abierta');
		$.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;
    }
};
