﻿var ChatUrl = "/Webchat/chat.dll";

var zeropad = function (num) { return ((num < 10) ? '0' : '') + num; }

////////////////////////////////////////////////////////////////////
/// Retorna el offset de un elemento en forma portable (IE, Mozilla)
function getElementOffset(elem, property) {
	var p = elem;
	var offset = 0;
	while(p) {
		offset += p[property];
		p = p.offsetParent;
	}
	return offset;
}

////////////////////////////////////////////////////////////////
/// Constructor del objeto InconcertChat
function InconcertChat(userID, sessionID, userName) {
	this.m_sUserId = userID;
	this.m_sSessionId = sessionID;
	this.m_sUsername = userName;
	this.m_nMsgCount = 0;

	this.cnxSend = new inConcert.AjaxObject();
	//this.cnxSend.debug = 1;
	this.cnxSend.ident = "cnxSend";
	this.cnxGet = new inConcert.AjaxObject();
	//this.cnxGet.debug = 1;
	this.cnxGet.ident = "cnxGet";

	this.m_fStopping = false;
	this.vDebug = false;
	this.m_sSessionExpired_Page = "chatsessexpired.html";	// por defecto
	
	this.toString = function() { return "[object inConcertChat]"; };
	
	////////////////////////////////////////////////////////////////
	/// Callback del objeto XmlHttpRequest (evento onload)
	this.handleOnload = function(ajaxRequest) {
		try {
			if(this.m_fStopping == true) {
				// no hacer más nada
				return;
			}
			if(typeof(this) == 'undefined') {
				//alert("chat (this) es undefined");
				return;
			}
			var httpCnx = ajaxRequest.connection;
  		try {
  			//alert("200: " + unescape(httpGetChat.responseText));
  			eval(unescape(httpCnx.responseText));
  		}
  		catch (e) {
  			alert(e);
  			alert("'"+ httpCnx.responseText + "'");
  		};
  		if(this.m_fStopping == false) {
  			//console.log("pido mas mensajes");
  			var param = "reason=moremsgs&userId=" + this.m_sUserId + "&SesionId=" + this.m_sSessionId;
			ajaxRequest.resend(param);
  		}
  	}
  	catch(e) { /*console.log(e.message);*/ };
	}
	
	////////////////////////////////////////////////////////////////
	/// Callback del objeto XmlHttpRequest (evento onerror)
	this.handleOnerror = function(ajaxRequest) {
		try {
			if(this.m_fStopping == true) {
				// no hacer más nada
				return;
			}
			if(typeof(this) == 'undefined') {
				//alert("chat (this) es undefined");
				return;
			}
			var httpCnx = ajaxRequest.connection;
  		// probable fallo en moremsg (usuario o sesion no existentes)
  		this.m_fStopping = true;
  		if( httpCnx.responseText == "chatSessionExpired" ) {
	  		window.location.href = this.m_sSessionExpired_Page;
  		}
  		else {
  			// todos menos el puto Opera me devuelven el responseText aunque haya sido 404
  			window.location.href = this.m_sSessionExpired_Page;
  		}
  	}
  	catch(e) { /*console.log(e.message);*/ };
	}
	
	////////////////////////////////////////////////////////////////
	/// Inicializo el objeto chat
	this.Initialize = function()
	{
		var param = "reason=chat&userId=" + this.m_sUserId + "&SesionId=" + this.m_sSessionId;
		this.cnxGet.open({
			url: ChatUrl,
			method: 'post'
		});
		var thisClosure = this;
		this.cnxGet.bind({
			onload: function(xhr) { thisClosure.handleOnload(xhr); },
			onerror: function(xhr) { thisClosure.handleOnerror(xhr); }
		});
		this.cnxGet.send(param);
	}
	
	////////////////////////////////////////////////////////////////
	/// Finalizo el objeto chat
	this.Finalize = function()
	{
		//alert("finalize: "+ this);
		try {
		this.cnxSend.abort();
		this.cnxSend.abort();
		this.m_fStopping = true;
	
		this.cnxSend = null;
		this.cnxSend = null;
	} catch(e) { alert(e.message); }
	
	};
	
	////////////////////////////////////////////////////////////////
	/// Asigna la pagina a la que se va cuando expira la sesion
	this.PutSessionExpiredPage = function (valor)
	{
		this.m_sSessionExpired_Page = valor;
	}
	
	////////////////////////////////////////////////////////////////
	/// OnNewMessage: Recibe un mensaje, lo formatea y agrega una línea de chat
	this.OnNewMessage = function (msg)
	{
		var vBody = document.getElementById("tkChatBody");
		var div = document.createElement("div");
		var divUser = document.createElement("span");
		var divMsg = document.createElement("span");
		var vMsg = this.ParseMessage(msg);
		div.className = "tkChatMsg";
  	
		if(this.m_nMsgCount % 2 == 0) {
			//div.style.backgroundColor = "#EFFFFF";
			div.style.backgroundColor = "#FFFFCF";
		};
		this.m_nMsgCount++;
  
		if(this.m_sUserId == vMsg.userId) {
			divUser.className = "tkChatMsgUserSelf";
			divMsg.className = "tkChatMsgText";
		}
		else if(typeof(vMsg.username) == 'undefined') {
			divUser.className = "tkChatMsgSystem";
			divMsg.className = "tkChatMsgSystemText";
		}
		else {
			divUser.className = "tkChatMsgUser";
			divMsg.className = "tkChatMsgText";
		}
 
 		div.appendChild(divUser);
		div.appendChild(divMsg);
		vBody.appendChild(div);
		
		divUser.innerHTML = "[" + vMsg.msgtime + "] " + vMsg.username + ":";
  	
		var vText = vMsg.text.replace(/\r\n/g, "<br/>");
		vText = vText.replace(/  /g, "&nbsp;");
		vText = ParseEmoticons(vText);
		divMsg.innerHTML = vText;
  
		vBody.scrollTop = vBody.scrollHeight;
	}
	
	////////////////////////////////////////////////////////////////
	/// OnPushUrl: Hace un popup de una url ?
	this.OnPushUrl = function (nuevaUrl, username)
	{
		var vBody = document.getElementById("tkChatBody");
		var div = document.createElement("div");
		var divUser = document.createElement("div");
		var divMsg = document.createElement("div");
		
		div.className = "tkChatPushUrl";
		divUser.className = "tkChatMsgUser";
		divMsg.className = "tkChatMsgText";
		
		vBody.appendChild(div);
  	//div.appendChild(divUser);
  	div.appendChild(divMsg);
  	
  	divUser.innerHTML = username + ":";
  	
		var vText = username + " le envi&oacute; el siguiente enlace: <br ?><a href=\"" + nuevaUrl + "\" target=\"_blank\">" + nuevaUrl + "</a><br /><br />"
		vText += "Haga click sobre enlace si desea abrirlo en una ventana nueva.";
  	divMsg.innerHTML = vText;
  
  	vBody.scrollTop = vBody.scrollHeight;
	}
	
	////////////////////////////////////////////////////////////////
	/// OnUserJoin: Un usuario ha entrado a la sesión
	this.OnUserJoin = function (userId, username)
	{
		var vBody = document.getElementById("tkChatBody");
		var div = document.createElement("div");
		var divUser = document.createElement("div");
		var divMsg = document.createElement("div");
		
		div.className = "tkChatUserJoin";
		divUser.className = "tkChatMsgUser";
		divMsg.className = "tkChatMsgText";
		
		vBody.appendChild(div);
  	div.appendChild(divMsg);
  	
  	divUser.innerHTML = username + ":";
  	
		var vText = username + " se ha agregado a la conversaci&oacute;n."
  	divMsg.innerHTML = vText;
  
  	vBody.scrollTop = vBody.scrollHeight;
	}
	
	////////////////////////////////////////////////////////////////
	/// OnUserLeft: Un usuario se ha ido de la sesión
	this.OnUserLeft = function (userId, username)
	{
		var vBody = document.getElementById("tkChatBody");
		var div = document.createElement("div");
		var divUser = document.createElement("div");
		var divMsg = document.createElement("div");
		
		div.className = "tkChatUserLeft";
		divUser.className = "tkChatMsgUser";
		divMsg.className = "tkChatMsgText";
		
		vBody.appendChild(div);
  	div.appendChild(divMsg);
  	
  	divUser.innerHTML = username + ":";
  	
		var vText = username + " ha salido de la conversaci&oacute;n."
  	divMsg.innerHTML = vText;
  
  	vBody.scrollTop = vBody.scrollHeight;
	}
	
	////////////////////////////////////////////////////////////////
	///
	this.OnDisconnect = function()
	{
		this.m_fStopping = true;
		this.cnxGet.abort();
	}
	
	////////////////////////////////////////////////////////////////
	/// Parsea un mensaje recibido del server de chat
	this.ParseMessage = function(vMsgTxt)
	{
		var vSep = vMsgTxt.charAt(0);
		var vSubSep = vMsgTxt.charAt(1);
		vMsgTxt = vMsgTxt.substr(2);
		var arrData = vMsgTxt.split( vSep );
		var vItem;
	
		var vMsgObj = new Array();
		for(i = 0; i < arrData.length; i++) {
			vItem = arrData[i].split(vSubSep);
			vMsgObj[vItem[0]] = vItem[1];
		}
		if(typeof(vMsgObj.msgtime) != 'undefined') {
			var vDate = new Date();	// toma, te muestro la hora actual. Al diablo con la del server!
			vMsgObj.msgtime = zeropad(vDate.getHours()) + ":" + zeropad(vDate.getMinutes());
		}
		return vMsgObj;
	}
	
	////////////////////////////////////////////////////////////////
	/// Parsea un SYSTEMTIME de Windows formateado en hexadecimal.
	/// Devuelve una hora en UTC.
	this.ParseHexaUtcDate = function(vDate)
	{
		var wYear = parseInt(vDate.substr(0,4), 16);
		var wMonth = parseInt(vDate.substr(4,4), 16) - 1;
		var wDayOfWeek = parseInt(vDate.substr(8,4), 16);
		var wDay = parseInt(vDate.substr(12,4), 16);
		var wHour = parseInt(vDate.substr(16,4), 16);
		var wMinute = parseInt(vDate.substr(20,4), 16);
		var wSecond = parseInt(vDate.substr(24,4), 16);
		var wMilliseconds = parseInt(vDate.substr(28,4), 16);
	
		return new Date(Date.UTC(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds));
	}
	
	////////////////////////////////////////////////////////////////
	/// Envía un mensaje hacia el server de chat
	this.SendMessage = function(message)
	{
		var sReason = "send";

		if (message == '') return;
		var currentChatText = encodeURIComponent(message);
	
		if (this.cnxSend.connection.readyState == 4 || this.cnxSend.connection.readyState == 0) {
			var param = 'reason=' + sReason;
			param += '&userId=' + this.m_sUserId + '&SesionId=' + this.m_sSessionId;
			param += '&text='  + currentChatText;
			
			this.cnxSend.open({
				url: ChatUrl,
				method: 'post'
			});
			this.cnxSend.connection.setRequestHeader('Content-Type', 'application/xml');
			this.cnxSend.connection.setRequestHeader('Content-Encoding', 'utf-8');
  		this.cnxSend.send(param);
		}
		else {
			if( !this.m_fStopping ) setTimeout('SendMessage();', 1000);
		}
	}
	
	////////////////////////////////////////////////////////////////
	/// Manda un logout sincrónico al server
	this.LogOut = function()
	{
		if( this.m_fStopping ) {
			return;
		}
		this.m_fStopping = true;
		var param = 'reason=' + "logout";
		param += '&userId=' + this.m_sUserId + '&SesionId=' + this.m_sSessionId;
		this.cnxSend.open({
			url: ChatUrl,
			method: 'post',
			asynchronous: false
		});
		var thisClosure = this;
		this.cnxSend.bind({
			onload: function() {
  			thisClosure.Finalize;
  		}
		});
  	this.cnxSend.send(param);
  }
};
