/* Chat Inicio v2.0.0 */
$(document).ready(function(){
	$.getScript("chat/scripts/comet.js", function()
	{
		$("#windowstatus").css({
			'width':'100px', 
			'height':'140px'
		});
		
		$('body').append('<div id="chat_beep"></div>')
		
		/* ASIGNO EL EVENTO DE CONECTAR Y DESCONECTAR */
		$('#chatDisconnect').click(function(){
			comet.disconnect();
		});
		$('#chatConnect').click(function(){
			comet.connect();
		});
		
		/* 	
			SI LA COOKIE CHATCONNECTION ESTA EN 1 LO CONECTO AL CHAT Y 
			ABRO TODAS LAS VENTANAS QUE ESTAN EN LA COOKIE CHATWINDOWS
		*/
		
		if (getCookie('chatConnection') != null)
		{
			var estaConectado = getCookie('chatConnection');
			if (estaConectado == '1')
			{
				comet.connect();
				
				if (getCookie('chatWindows') != null)
				{
					var chatWindows = getCookie('chatWindows').split('---');
					var strWindows = new String();
					for (var i = 0; i<chatWindows.length-1; i++)
					{
						var aux = chatWindows[i].split('--');
						if (aux[0] != "")
						{
							windowview(aux[0], aux[1]);
						}
					}
				}
			}
		}
		else
		{
			comet.connect();
		}
		
	});
});

function windowview(reciver, user)
{
	var sender = getCookie('SID');

	/* CONTROLO QUE SIEMPRE HAYA 3 VENTANAS ABIERTAS */
	if ($('#'+reciver).attr('id') != reciver)
	{
		if (comet.windows.length == 3)
		{
			var ventana = comet.windows.pop();
			$('#'+ventana).remove();
			
			var chatWindows = getCookie('chatWindows');
			
			var newChatWindows;
			
			var chatWindowsAux = chatWindows.split('---');
			for (var i=0; i<chatWindowsAux.length; i++)
			{
				var aux = chatWindowsAux[i].split('--');
				if (aux[0] != ventana && aux[0] !="")
				{
					newChatWindows += aux[0] +'--'+aux[1]+'---';	
				}
			}
			var myDate=new Date();
			myDate.setHours(myDate.getHours()+2);
			setCookie("chatWindows", newChatWindows, myDate);
			
		}
	}
	
	/* SI LA VENTANA NO ESTA EN LA COOKIE LA AGREGO */
	var existe = false;
	if (getCookie('chatWindows') != null)
	{
		var chatWindows = getCookie('chatWindows');
		
		if (chatWindows == 0)
		{
			chatWindows = "";
		}
		
		var chatWindowsAux = chatWindows.split('---');
		for (var i=0; i<chatWindowsAux.length; i++)
		{
			var aux = chatWindowsAux[i].split('--');
			if (aux[0] == reciver)
			{
				existe = true;
			}
		}
		
		if (!existe)
		{
			chatWindows += reciver + '--' + user + '---';	
		}
		var myDate=new Date();
		myDate.setHours(myDate.getHours()+2);
		setCookie("chatWindows", chatWindows, myDate);
	}
	else
	{
		var chatWindows = reciver+'--'+user+'---';	
		var myDate=new Date();
		myDate.setHours(myDate.getHours()+2);
		setCookie("chatWindows", chatWindows, myDate);
	}
	
	/* SI LA VENTANA NO EXISTE LA ABRO */
	if ($('#'+reciver).attr('id') != reciver)
	{
		guardarVentanaEnArray(reciver, user);
		var chatContenido = '<div class="chatCont" id="'+ reciver +'" class="clearfix">'+
								  '<div class="chatMostrar">'+
									'<div class="chatMostrarDer"></div>'+
									'<div class="chatMostrarTxt">'+$('#chat_mostrar_traduccion').val()+'</div>'+
									'<div class="chatMostrarIzq"></div>'+
								  '</div>'+
								  '<div class="chatSup">'+
									'<div class="chatNombreHeader">'+ user +'</div>'+
									'<div class="chatBtn">'+
									  '<div class="chatBtns chatBtnMinimizar"></div>'+
									  '<div class="chatBtns chatBtnMaximizar"></div>'+
									  '<div class="chatBtns chatBtnCerrar"></div>'+
									'</div>'+
								  '</div>'+
								  '<div class="chatInf clearfix">'+
									'<div class="chatInfSup clearfix">'+
									  '<div class="chatVisor">'+
									  '</div>'+
									  '<div class="chatCampo">'+
										'<div class="chatBandera"><img src="images/flags/'+getCookie('lang')+'.jpg" /></div><textarea class="chatCampoTxt chatVisorTxt" id="txt_'+ reciver +'"></textarea>'+
									  '</div>'+
									  '<div class="chatCheck">'+
										  '<div class="chatAncho" style="z-index:999;">'+
											'<div class="correoBtnIzq flotante"></div>'+
											'<div class="correoBtnTxt flotante chatPadding">'+$('#chat_enviar').val()+'</div>'+
											'<div class="correoBtnDer flotante"></div>'+
										  '</div>'+
									  '</div>'+
									'</div>'+
									'<div class="chatInfInf"></div>'+
								  '</div>'+
								'</div>';
		$("body").append(chatContenido);		
		reposicionarVentanas ();
			
		/* Cargo el contenido de la cookie en el chatVisor */
		if (getCookie(reciver) != null)
		{
			$('#'+reciver).find('.chatVisor').append(getCookie(reciver));
			/*Hago que el scroll baje*/
			$('#'+reciver).find('.chatVisor').scrollTo('100%',{axis:'y'});
		}
			
		/*Cargo el corrector de ortografia*/
		var googie1 = new GoogieSpell("chat/images/", "chat/sendReq.php?lang=");
		googie1.decorateTextarea("txt_"+reciver);
	
		/*--------------------------------*/
		
		/*							*
		*		ASIGNO EVENTOS		*
		*							*/			
		
		/* CUANDO APRIETO ENTER EN EL TEXTE AREA ENVIO EL MENSAJE */
		$(ventana).find('textarea').keypress(function(e){
			if(e.which == 13) // 13 es el enter
			{
				var mensaje = $('#'+reciver).find('textarea').val();
				if (mensaje.replace(/^\s*|\s*$/g,"") != "")
				{
					comet.doRequest(mensaje,sender,reciver);
					
					$('#'+reciver).find('.chatVisor').append('<div class="chatRenglon"> <span class="chatVisorTxt bold chatNombre">'+$('#chat_yo').val()+':</span> <span class="chatVisorTxt chatMensaje">'+mensaje+'<br></span> </div>');
					$('#'+reciver).find('textarea').val('');
					/*Hago que el scroll baje*/
		        	$('#'+reciver).find('.chatVisor').scrollTo('100%',{axis:'y'});
					
					guardarHistorial (reciver);
					
					e.preventDefault();
					e.stopPropagation();
				}
			}
		});
		
		/* ENVIO EL MENSAJE CUANDO HAGO CLICK EN EL BOTON ENVIAR*/
		$('#'+reciver).find('.correoBtnTxt').click(function(){
			var mensaje = $('#'+reciver).find('textarea').val();
			if (mensaje != "")
			{
				comet.doRequest(mensaje,sender,reciver);
				
				$('#'+reciver).find('.chatVisor').append('<div class="chatRenglon"> <span class="chatVisorTxt bold chatNombre">'+$('#chat_yo').val()+':</span> <span class="chatVisorTxt chatMensaje">'+mensaje+'<br></span> </div>');
				$('#'+reciver).find('textarea').val('');
				/*Hago que el scroll baje*/
				
				/*Guardo el contenido de la caja en una cookie*/
				guardarHistorial (reciver);
				
		        $('#'+reciver).find('.chatVisor').scrollTo('100%',{axis:'y'});
			}
		});
		
		/*Cargo el mostrar/ocultar Traduccion*/
		$('#'+reciver).find('.chatMostrarTxt').toggle(function(){
			$('.chatSintraducir').show();
			$('#'+reciver).find('.chatVisor').scrollTo('100%',{axis:'y'});
		}, function (){
			$('.chatSintraducir').hide();
			$('#'+reciver).find('.chatVisor').scrollTo('100%',{axis:'y'});
		});
		
		/*Cargo el cerrar*/
		$('#'+reciver).find('.chatBtnCerrar').click(function(){
			chat_cerrarVentana ($('#'+reciver));
		});
		
		/*Cargo el Minimizar*/
		$('#'+reciver).find('.chatBtnMinimizar').click(function(){
			$('#'+reciver).find('.chatMostrar').hide();
			$('#'+reciver).css({'bottom':'-212px'});
		});
		
		/*Cargo el Maximizar*/
		$('#'+reciver).find('.chatBtnMaximizar').click(function(){
			$('#'+reciver).find('.chatMostrar').show();
			$('#'+reciver).css({'bottom':'72px'});
		});
	}
	/*---------------------------------*/
}

/* FUNCION QUE GUARDA LAS VENTANAS QUE SE ABREN EN EL OBJETO COMET */
function guardarVentanaEnArray(idVentana, nombreUsuario)
{
	if (comet.windows == null)
	{
		comet.windows = new Array();
	}

	comet.windows.push(idVentana);
}

/* FUNCION QUE REPOSICIONA TODAS LAS VENTANAS */
function reposicionarVentanas ()
{
	$('.chatCont').each(function(i){
		var separacion = (i)*240;
		$(this).css({'right':separacion+'px'});
		if ($.browser.msie == true && $.browser.version == 6.0)
		{
			var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body
			var dsoctop=document.all? iebody.scrollTop : pageYOffset
			var bottom = dsoctop;
			var winHeight  = $(window).height();
			var windowsBottom = dsoctop + winHeight - $(this).height();
			
			$(this).css({'top':windowsBottom+'px'});
		}
	});
}

function guardarHistorial (reciver)
{
	/*Guardo el contenido de la caja en una cookie*/
					
	/*Obtengo la posicion aparttir de la cual tengo que iterar*/
	
	var cantidad_renglones = $('#'+reciver).find('.chatRenglon').length;
	var desde;
	if (cantidad_renglones > 6)
	{
		desde =	cantidad_renglones - 7;
	}
	else
	{
		desde = 0;
	}
	
	//alert($('#'+reciver).find('.chatRenglon:gt('+desde+')').length);
	var myDate=new Date();
	myDate.setHours(myDate.getHours()+2);
	setCookie(reciver," ", myDate);
	if (cantidad_renglones == 1)
	{	
		var aux = getCookie (reciver);
		aux += '<div class="'+$('#'+reciver).find('.chatRenglon:eq(0)').attr('class')+'">'+$('#'+reciver).find('.chatRenglon:eq(0)').html()+'</div>';
		var myDate=new Date();
		myDate.setHours(myDate.getHours()+2);
		setCookie(reciver, aux, myDate);
	}
	else
	{
		$('#'+reciver).find('.chatRenglon:gt('+desde+')').each(function(i){
			var aux = getCookie (reciver);
			aux += '<div class="'+$(this).attr('class')+'">'+$(this).html()+'</div>';
			var myDate=new Date();
			myDate.setHours(myDate.getHours()+2);
			setCookie(reciver, aux, myDate);
		});
	}
}

function chat_cerrarVentana (ventana)
{
	var idventana = $(ventana).attr("id");
	/* ELIMINO LA VENTANA DE LA COOKIE */
	if (getCookie('chatWindows') != null)
	{
		var chatWindows = getCookie('chatWindows').split('---');
		var strWindows = new String();
		for (var i = 0; i<chatWindows.length-1; i++)
		{
			var aux = chatWindows[i].split('--');
			if (aux[0] != idventana)
			{
				strWindows += chatWindows[i]+'---';
			}
		}
		var myDate=new Date();
		myDate.setHours(myDate.getHours()+2);
		setCookie('chatWindows',strWindows, myDate);
	}
	
	/* ELIMINO LA VENTANA DEL ARRAY */
	var arrayAux = new Array();
	
	for (var i=0; i<comet.windows.length; i++)
	{	
		var aux = comet.windows.shift();
		if (aux != idventana)
		{
			arrayAux.push(aux);
		}
	}
	comet.windows = arrayAux;
	
	/* ELIMINO LA VENTANA DEL DOM */
	$(ventana).remove();
	
	/* REPOSICIONO TODAS LAS VENTANAS */
	reposicionarVentanas ();
}

