﻿// JScript File
var lastIndex = -1;
var loadingDiv = getDOMElementById("loadingDiv"); 
var chatDiv = getDOMElementById("chatDiv"); 
var chatText = getDOMElementById("chattext"); 
var waitingText = getDOMElementById("txtWaitingMessages");
var sentText = getDOMElementById("senttext"); 
var btnSend = getDOMElementById("btnSend"); 
var conversation ="";
var jc;
var conversationUsers;
var license ="";
var langCode="";
var machinecode="";
var source = "";
var idUser;
var updatePeriod = 4000;
var bShowSurvey = false;
var offlineLoops = 10;
var insertMessageRetries = 3;
var waitingMessageLoops = 5;
var bIsOurCustomBrowser = false;
var parameterArray;
var ieMobile = (navigator.userAgent.indexOf("IEMobile") > 0) || (navigator.appName.indexOf("IE Mobile") > 0) || (navigator.appName.indexOf("Pocket") > 0);
var lang = new Language();
var conversationIsLost = false;
var failedCalls = 0;
var pseudoVipDivShown = false;
var startConversation = new Date().getTime(); 

// Checks if a something is defined
function isDefined(type) 
{   
    return type != 'undefined' && type != 'unknown';
}

// getDOMElementById wrapper
function getDOMElementById(id) 
{
    if (isDefined(typeof document.getElementById)) 
        return document.getElementById(id);
    else if (isDefined(typeof document.all)) 
        return document.all[id];
    else 
       return null;
}

// Function to handle OnLoad Window event
window.onload = function() 
{    
    try
    {
        bIsOurCustomBrowser = (window.external && window.external.IsOurCustomBrowser != null);		
    }
    catch(exception)
    {
        // Ignores exception
    }

    try
    {
        // Get and load client parameters
        LoadParameters();
        LoadLanguage();
    		
		// Hide web divs
        loadingDiv.style.display = "" 
        chatDiv.style.display = "none"; 

        // Logon the end user
        jc = new JsonCore();
        jc.LogOnEndUser(license, machinecode, langCode, LogOnEndUserCallback);
	}
	catch(exception)
	{
		if(jslog != null)
			jslog.error("Error on window.onload: " + exception.name + ": " + exception.message);
	}
}

// Traduces every text depending on conversation language
function LoadLanguage()
{
    lang.init();
    lang.setLanguage(langCode);
    
    var oObj;
    oObj = getDOMElementById("selectingOperLabel");
    if(oObj)
        oObj.innerHTML = lang.getText("selectingOperLabel");
        
    oObj = getDOMElementById("offlineContactLabel");
    if(oObj)
        oObj.innerHTML = lang.getText("offlineContactLabel");
        
    oObj = getDOMElementById("offlineContactLabel2");
    if(oObj)
        oObj.innerHTML = lang.getText("offlineContactLabel2");
        
    oObj = getDOMElementById("offlineContactLabel3");
    if(oObj)
        oObj.innerHTML = lang.getText("offlineContactLabel3");
        
    oObj = getDOMElementById("btnGoToOffline");
    if(oObj)
        oObj.value = lang.getText("btnGoToOffline");
        
    oObj = getDOMElementById("btnGoToOffline1");
    if(oObj)
        oObj.value = lang.getText("btnGoToOffline");
        
    oObj = getDOMElementById("btnGoToVIP");
    if(oObj)
        oObj.value = lang.getText("btnGoToVIP");
        
    oObj = getDOMElementById("btnSend");
    if(oObj)
        oObj.value = lang.getText("btnSend");
      
    oObj = getDOMElementById("aumentarLetra");
    if(oObj)
        oObj.alt = lang.getText("aumentarLetra");
        
    oObj = getDOMElementById("disminuirLetra");
    if(oObj)
        oObj.alt = lang.getText("disminuirLetra");
        
    oObj = getDOMElementById("restaurarLetra");
    if(oObj)
        oObj.alt = lang.getText("restaurarLetra");
        
    oObj = getDOMElementById("recibirConversacion");
    if(oObj)
        oObj.alt = lang.getText("recibirConversacion");
        
    oObj = getDOMElementById("imgCerrar");
    if(oObj)
        oObj.alt = lang.getText("imgCerrar");    
}

// Log On callback
function LogOnEndUserCallback(answer)
{     
    try
    {
        var oUser = answer.result;
        if(oUser != null)
        {
            // When logged, create a new conversation and join it
            idUser = oUser._idUser;
            
            if (parameterArray.length > 2)
                conversation = jc.CreateConversationWithSkills(idUser, idUser, parameterArray); 
            else
                conversation = jc.CreateConversation(idUser, idUser);     
                
            if (conversation == null)
                GoToOfflineWindow();
            
            jc.JoinConversation (idUser, conversation, idUser);              
               
            // Send the conversation id to UlisesClient App if it is needed
            if(bIsOurCustomBrowser)
            {	    
                window.external.SetParameter("SessionId", conversation + "");
            }   
            
            // Wait until the system assign an operator to our conversation
            WaitForOperator();
        }    
        else
            // If the logon process fails, go to offline window
            GoToOfflineWindow();      
    }
    catch (exception)
    {
        if(jslog != null)
			jslog.error("Error on LogOnEndUserCallback: " + exception.name + ": " + exception.message);
        GoToOfflineWindow();
    }
}

// Obtains list of skills from GET params
function GetSkillsByParams()
{ 
    try
    {
        parameterArray = unescape(self.location.search).substring(1).split( "&");       
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on GetSkillsByParams: " + exception.name + ": " + exception.message);
    }
}
  
// Load client parameters
function LoadParameters()
{
    try
    {
        // Get License, machine code, language and source parameters
        var oLicense = getDOMElementById('m_txtLicense');
        var oMachineCode = getDOMElementById('m_txtCIS');
        var oLangCode = getDOMElementById('m_txtLanguageCode');
        var oSource = getDOMElementById('m_txtSource');
        var oOfflineLoops = getDOMElementById('m_txtOfflineLoops');
        // To Get Skills List
        GetSkillsByParams();

        if(oLicense != null)
            license = oLicense.value;

        if(oMachineCode != null)
            machinecode = oMachineCode.value;

        if(oLangCode != null)
            langCode= oLangCode.value;
    	
        if(oSource != null)
            source = oSource.value;
            
        if(oOfflineLoops != null)
        {
            if (oOfflineLoops.value != "")
                offlineLoops = parseInt(oOfflineLoops.value);
        }
    }
    catch(exception)
    {       
       if(jslog != null)
			jslog.error("Error on LoadParameters: " + exception.name + ": " + exception.message);
    }
                
}

// Show operator in the operator's label
function ShowOperators()
{
    try
    {
        var numOps = 0;
        var lblOperator = getDOMElementById("labelOperator");
        var opName = lang.getText("attendingText") + "<br>";

        for (var i = 0; i < conversationUsers.length; i++)
        {
            // Only add operators or administrators
            if ((conversationUsers[i]._type == "Operator")||(conversationUsers[i]._type == "Administrator")||(conversationUsers[i]._type == "SiteUser"))
            {           
                if (numOps > 0)
                    opName += ", ";
                 
                 opName += conversationUsers[i]._nickname; 
                 numOps +=1;                 
            }
        } 
        
        lblOperator.innerHTML = opName;
    }
    catch(exception)
    {      
       if(jslog != null)
			jslog.error("Error on ShowOperators: " + exception.name + ": " + exception.message);
    }
} 

// Show go to offline window button
function ShowGoToOfflineWindowButton()
{
    try
    {
        if (pseudoVipLicense == "false")
            getDOMElementById("GoToOfflineWindowDiv").style.display = "block";
        else
        {
            getDOMElementById("GoToOfflinePseudoVIPWindowDiv").style.display = "block";
            if (conversation != "")
            {
                pseudoVipDivShown = true;            
                jc.LeaveConversation (idUser, conversation, idUser); 
            }           
        }
    }
    catch(exception)
    {       
       if(jslog != null)
			jslog.error("Error on ShowGoToOfflineWindowButton: " + exception.name + ": " + exception.message);
    }
}

// Go to offline window
function GoToOfflineWindow()
{ 
    try
    {
        // Leave the current conversation and logs off
        if (conversation != "")
            jc.LeaveConversation (idUser, conversation, idUser);                    
    }
    catch(exception)
    {    
        jslog.error("Error on GoToOfflineWindow: " + exception.name + ": " + exception.message);
    }
    finally
    {
        bShowSurvey = false;
        document.location="Offline.aspx?License=" + license +"&Cis=" + machinecode+'&LanguageCode='+langCode;
    }
}

function GoToPseudoVIPWindow()
{
    try
    {
        jc.MakePseudoVipUser(idUser, license, MakePseudoVipUserCallback);
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on GoToPseudoVIPWindow: " + exception.name + ": " + exception.message);
    }
    finally
    {
        bShowSurvey = false;
        document.location="PseudoVip.aspx";
    }
}

function MakePseudoVipUserCallback(answer)
{
    if (answer.result == null)
        if(jslog != null)
			jslog.error("Error on MakePseudoVipUserCallback");    
}

// Function to wait for an operator
function WaitForOperator()
{
    try
    {
        // Get conversation users
        if (!pseudoVipDivShown)
        jc.GetConversationUsers(idUser, conversation, WaitForOperatorCallback);
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on WaitForOperator: " + exception.name + ": " + exception.message);
    }
}     

// Callback for WaitForOperator function
function WaitForOperatorCallback(answer)
{
    try
    {
        // Get the answer
        conversationUsers = answer.result;
        
        if (conversationUsers != null)
        {
            // Check if we have an operator or administrator in the conversation
            var bHaveSpeaker = false;
            for (var i = 0; i < conversationUsers.length; i++)
            {
                if ((conversationUsers[i]._type == "Operator")||(conversationUsers[i]._type == "Administrator")||(conversationUsers[i]._type == "SiteUser")) 
                {   
                    if  (conversationUsers[i]._status == "Connected" )
                    {
                        bHaveSpeaker = true;                 
                        break;
                    }
                }
            } 
                
            // If we have an operator or administrator, enable the chat window and show operators
            if (bHaveSpeaker)
            {            
                bShowSurvey = true;
                
                sentText.disabled = false;
                btnSend.disabled  = false; 
                loadingDiv.style.display = "none" 
                chatDiv.style.display = "block";    
                ShowOperators();
                
                // Create the conversation timer
                setTimeout(ClientTimer, 1000);
                
                if (sentText == null)
                    sentText = getDOMElementById("senttext"); 
                    
                if (sentText != null)
                    sentText.focus();
            }
            else
            { 
                // Disable chat controls and show "Looking for an operator" dialog
                if(sentText.disabled == false)
                {
                    sentText.disabled = true;
                    btnSend.disabled  = true;
                    var lblOperator = getDOMElementById("labelOperator");
                    lblOperator.innerHTML = ""; 
                    loadingDiv.style.display = "block" 
                    chatDiv.style.display = "none";
                }
                
                // If we reach the max wait time, shows the go to offline button
                offlineLoops = offlineLoops - 1; 
                if (offlineLoops < 0)
                {
                    ShowGoToOfflineWindowButton();
                    offlineLoops = -1;
                }
                
                //Send and Offline Message
                if (waitingMessageLoops == 0)
                {
                    var sOfflineMsg = jc.GetWaitingMessage(idUser, conversation); 
                    waitingText.innerHTML = sOfflineMsg;   
                    waitingMessageLoops = 13;
                }
                else               
                    waitingMessageLoops = waitingMessageLoops - 1;
                        
                // Check for operator again after update period milliseconds
                setTimeout("WaitForOperator();", updatePeriod);                
            } 
        }
        else
        {
            //Call failed, shows offline form and retries       
            if (offlineLoops >= 0)
            {
                ShowGoToOfflineWindowButton();
                offlineLoops = -1;
            }
            
            setTimeout("WaitForOperator();", updatePeriod);                
        }
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on WaitForOperatorCallback: " + exception.name + ": " + exception.message);
    }    
}

// Add a message to the text window
function AddClientMessage(sender, type, message)
{
    try
    {
        if(chatText != null)
        {
            var oNewLine;
            
            // We have to send a reply for each ping
            if (type == "Ping")
            {
                // The ping reply message contains user agent information (navigator, version, etc).
                var sAnswer = "";
                sAnswer = navigator.userAgent;
                jc.SendPingReply(idUser, conversation, idUser, sAnswer, NoOpCallback);
                return;
            }            
            else if (type == "ConversationMessage")
            {
                if(sender != idUser)
                {
                   var iConvUser;
                   iConvUser=-1;
                   if(conversationUsers != null && conversationUsers.length > 0)
                   {
						DisableWriting();
                   
					   if(document.createElement && !ieMobile)
						{
							oNewLine = document.createElement("p");
							oNewLine.className = "OperatorMessage";
							oNewLine.innerHTML = message;
						}
						else
						{
							chatText.innerHTML = chatText.innerHTML + "<p class='OperatorMessage'>" + message + "</p>";
							return;
						}
                   }
                }
                else
                    return; //User messages are ignored
            }
            else if ((type == "RemoteControlStart") ||
                    (type == "RemoteControlEnd") || (type == "ConversationStart") ||
                    (type == "ConversationEnd") || (type == "FileSend") || (type == "MessageError"))
            {
                if (type == "ConversationEnd")
                    conversationIsLost = true;
            
				if(document.createElement && !ieMobile)
				{
					oNewLine = document.createElement("p");
					oNewLine.className = "OtherMessage";
					oNewLine.innerHTML = message;
				}
				else
				{
					chatText.innerHTML = chatText.innerHTML + "<p class='OtherMessage'>" + message + "</p>";
					return;
				}
            }
            else if(type == "RemoteControlRequest")
            {
                // Get remote control params
                var oParams = message.split(";");
                
                // If there are any problem with parameters, go out
                if(oParams == null || oParams.length < 2)
                    return;
                    
                var oSessionId = oParams[0];
                var oServerInfo = oParams[1];
				
				if(document.createElement && !ieMobile)
				{
					oNewLine = document.createElement("span");
					oNewLine.innerHTML = "<div style='margin: auto'><table align='center' class='rcdiv'><tr><td align='center'><img src='../../App_Themes/Default/img/Inc_InSitu.gif' valign='middle' alt='remote control' /></td></tr><tr><td align='center'><font style=\"color: #555555;\">" + lang.getText("requestRCText") + "</font></td></tr>";
					oNewLine.innerHTML += "<tr><td align='center' style='text-align: center;'><input type='button' class='rcbutton' value='" + lang.getText("yesRCText") + "' id='accept_button_" + oSessionId + "' onclick='AcceptRemoteControl(\"" + oSessionId + "\",\"" + oServerInfo + "\");'/> &nbsp; <input type='button' class='rcbutton' value='" + lang.getText("noRCText") + "' id='reject_button_" + oSessionId + "'  onclick='RejectRemoteControl(\"" + oSessionId + "\");'/></td></tr></table></div>";
				}
				else
				{
					chatText.innerHTML += "<span><div style='margin: auto'><table style='text-align: center;' class='rcdiv'><tr><td align='center'><img src='../../App_Themes/Default/img/Inc_InSitu.gif' valign='middle' alt='remote control' /></td></tr><tr><td align='center'><font style=\"color: #555555;\">" + lang.getText("requestRCText") + "</font></td></tr>";
					chatText.innerHTML += "<tr><td align='center' style='text-align: center;'><input type='button' class='rcbutton' value='" + lang.getText("yesRCText") + "' id='accept_button_" + oSessionId + "' onclick='AcceptRemoteControl(\"" + oSessionId + "\",\"" + oServerInfo + "\");'/> &nbsp; <input type='button' class='rcbutton' value='" + lang.getText("noRCText") + "' id='reject_button_" + oSessionId + "'  onclick='RejectRemoteControl(\"" + oSessionId + "\");'/></td></tr></table></div></span>";
					return;
				}                
            }
            else if (type == "ConversationLost")
            {
                //message var contais operator username (if any)
				var operSelector = "";
				if (message != null)
				    operSelector = "&oper=" + message;
				
				DisableWriting();
				
                if(document.createElement && !ieMobile)
				{  
					oNewLine = document.createElement("span");
					oNewLine.innerHTML = "<div style='margin: auto'><table align='center' class='connectionErrordiv'>";
					oNewLine.innerHTML += "<tr><td align='center'><font style=\"color: #555555;\">" + lang.getText("conversationEndByConnText") + "</font></td></tr>";
					oNewLine.innerHTML += "<tr><td align='center'><input type='button' class='rcbutton' value='" + lang.getText("reconnectButton") + "' onclick='ReloadSelectingOperator(\"" + operSelector  + "\");'/></td></tr>";
					oNewLine.innerHTML += "</table></div>";
				}
				else
				{
					oNewLine.innerHTML = "<span><div style='margin: auto'><table align='center' class='connectionErrordiv'>";
					oNewLine.innerHTML += "<tr><td align='center'><font style=\"color: #555555;\">" + lang.getText("conversationEndByConnText") + "</font></td></tr>";
					oNewLine.innerHTML += "<tr><td align='center'><input type='button' class='rcbutton' value='" + lang.getText("reconnectButton") + "' onclick='ReloadSelectingOperator(\"" + operSelector  + "\");'/></td></tr>";
					oNewLine.innerHTML += "</table></div></span>";
				} 
            }
            else if (type == "InterlocutorStartWritting")
            {
				var showWritingDiv = getDOMElementById("ShowWritingDiv");
				if (showWritingDiv != null)
				{
					///showWritingDiv.style.display = "block";
					showWritingDiv.style.visibility = "visible";
			    }
			    return;
            }
            else if (type == "InterlocutorStopWritting")
            {
				DisableWriting();
				return;
            }
            else
            {
                //Unknown message type (as SessionMessage)
                return;
            }
            
			if(document.createElement != null && !ieMobile)
			{
				chatText.appendChild(oNewLine);
				chatText.scrollTop = 200000;
			}	 
        }  
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on AddClientMessage: " + exception.name + ": " + exception.message);
    }
}

function DisableWriting()
{
	var showWritingDiv = getDOMElementById("ShowWritingDiv");
	if (showWritingDiv != null)
		///showWritingDiv.style.display = "none";
		showWritingDiv.style.visibility = "hidden";
}

function ReloadRemoteControl(sessionid, servers)
{
    var oControl = getDOMElementById('RemoteControl');
    if( oControl != null)
    {
        // If we can access to the iframe, reuse the remote control instantiated
        if( window.frames['RemoteControl'].ConnectFromParent)
        {
            window.frames['RemoteControl'].ConnectFromParent(sessionid, servers);
        }
        else
            oControl.src = "ClientRemoteControl.aspx?rcinstalled=1&session="+sessionid+"&servers="+servers;                
    }
}

function CancelLoadRemoteControl(sessionid)
{
    // Allow RC based on application
    //AddClientMessage("", "ConversationMessage", "Haga click <a href='javascript: void(0)' onclick='jc.SendRemoteControlAcceptAnswer(\"" + idUser + "\", \"" + conversation + "\", \"" + idUser +"\", \"" + sessionid + ";" + servers + "\", NoOpCallback); window.open(\"ClientRemoteControlExe.aspx?session=" + encodeURIComponent(sessionid) + "\");'>aquí</a> para descargar y ejecutar el archivo que dará comienzo a la sessión de control remoto.");    
    
    // Send notification to operator
    //jc.SendPingReply(idUser, conversation, idUser, "Info: El usuario ha cancelado la instalación del ActiveX. Se le ha mostrado un enlace para que descargue y ejecute el control remoto basado en aplicación ('Haga click aquí para descargar y ejecutar el archivo que dará comienzo a la sessión de control remoto.').", NoOpCallback);    
}

function ShowRCExeMessage(sessionid, servers)
{    
    if (langCode=="")
        langCode = "es-ES";
        
    if (navigator.appVersion.indexOf("Mac")!=-1) 
    {
        //AddClientMessage("", "ConversationMessage", "Not supported right now" );//
       AddClientMessage("", "ConversationMessage", lang.getText("rcExeLinkMac")+ "<br/>" + lang.getText("rcMacExplanation")+ "<br/>" + sessionid + "<br/><a href='\"ClientRemoteControlExe.aspx?os=MAC&session=" + encodeURIComponent(sessionid) + "\"' target='hiddenFrame' onclick='jc.SendRemoteControlAcceptAnswer(\"" + idUser + "\", \"" + conversation + "\", \"" + idUser +"\", \"" + sessionid + ";" + servers + "\", NoOpCallback);'>" + lang.getText("rcExeLink") + "</a> ");    
    }
    else
        AddClientMessage("", "ConversationMessage", lang.getText("rcExePre") + " <a href='javascript: void(0)'  target='hiddenFrame'  onclick='jc.SendRemoteControlAcceptAnswer(\"" + idUser + "\", \"" + conversation + "\", \"" + idUser +"\", \"" + sessionid + ";" + servers + "\", NoOpCallback); window.open(\"ClientRemoteControlExe.aspx?session=" + encodeURIComponent(sessionid) + "\");'>" + lang.getText("rcExeLink") + "</a> " + lang.getText("rcExePost"));    
}

// Function called to accept the remote control session
var g_sessionid = '';

function SendWebRemoteControlNonWindows( sessionid, servers )
{
	ShowRCExeMessage(sessionid, servers);
                
	// Send a notification to operator
	if(!bAllowActiveX)
		jc.SendPingReply(idUser, conversation, idUser, "Info: El usuario tiene deshabilitada la ejecución de ActiveX en su navegador. Navegador: " + navigator.userAgent, NoOpCallback);
		
	jc.SendPingReply(idUser, conversation, idUser, "Info: Se le ha mostrado un enlace para que descargue y ejecute el control remoto basado en aplicación ('Haga click aquí para descargar y ejecutar el archivo que dará comienzo a la sessión de control remoto.').", NoOpCallback);
                
}

function AcceptRemoteControl(sessionid, servers)
{
	if(g_sessionid == sessionid)
		return;
		
    try
    {    
        g_sessionid = sessionid;
        
        if(ieMobile)
            window.location.href = "ClientPPCRemoteControl.aspx?session="+sessionid+"&servers="+servers+"&iduser=" + encodeURIComponent(idUser) + "&idconvers=" + encodeURIComponent(conversation);
        else
        {
            // Disable remote control buttons
            DisableRemoteControlButtons(sessionid, 0);
        
            var bAllowActiveX = AreActiveXAllowed();
            if(navigator.appName == "Microsoft Internet Explorer" && bAllowActiveX)
            {
				// try to launch the remote control integrated with the client
				//if (window.external && window.external.LaunchRC != null)
				//{				
					try
					{// Communicate with the application
						if(window.external.LaunchRC(servers, sessionid, ''))
						{// Communicate the connection to the operator
							OnRemoteControlConnected(sessionid, servers);
						}
						else
						{// Open the checker Window
							window.open('ClientRemoteControlInstallerChecker.aspx?servers='+servers+'&session='+sessionid+'&languagecode='+langCode, '', 'height=200,width=600,status=no,toolbar=no,menubar=no,location=no');
						}
					}
					catch(exception)
					{// Open the checker Window
						window.open('ClientRemoteControlInstallerChecker.aspx?servers='+servers+'&session='+sessionid+'&languagecode='+langCode, '', 'height=200,width=600,status=no,toolbar=no,menubar=no,location=no');
					}
				//}
				//else
				//{// Open the checker Window
					//window.open('ClientRemoteControlInstallerChecker.aspx?servers='+servers+'&session='+sessionid+'&languagecode='+langCode, '', 'height=200,width=600,status=no,toolbar=no,menubar=no,location=no');            
				//}
            }	
            else if( Cocoa!=null && Cocoa.launchRCImplemented!=null)
            {	//Just Our Mac Client				
                try
                {
                    if( Cocoa.launchRCImplemented )
                    {
						Cocoa.launchRC( servers, sessionid, '');						
                        OnRemoteControlConnected(sessionid, servers);
                    }
                }
                catch(exception)
                {
					if(jslog != null)
						jslog.error("Error on AcceptRemoteControl on Mac Client: " + exception.name + ": " + exception.message);   
					SendWebRemoteControlNonWindows(sessionid, servers );
                }                
            }
            else
            {   
				SendWebRemoteControlNonWindows(sessionid, servers );                   
            }
        }
        
    }
    catch(exception)
    {
       if(jslog != null)
			jslog.error("Error on AcceptRemoteControl: " + exception.name + ": " + exception.message);   
        
        // Try to reload remote control
        ShowRCExeMessage(sessionid, servers);
    }
}

// Function to detect if activeX controls are allowed to execute
function AreActiveXAllowed()
{
	var bResult = false;
	var sUserAgent = navigator.userAgent.toLowerCase();
	if(sUserAgent.indexOf('msie')!=-1 && sUserAgent.indexOf('opera')==-1 && sUserAgent.indexOf('mac')==-1)
	{
		if(document.getElementById)
		{
			// Check creating a XMLHTTP object
			eval("var oActiveX=(sUserAgent.indexOf('msie 5')!=-1)?'Microsoft.XMLHTTP':'Msxml2.XMLHTTP';try{new ActiveXObject(oActiveX);bResult=true;}catch(e){bResult=false;}");
		}
	}
	return bResult;
}

// Function to handle json events.
// Used to make calls to json asyncronous with functions that not return nothing
function NoOpCallback(answer)
{
}

var lastSessionAccepted = '';
// Function to handle OnConnect event of the remote control
function OnRemoteControlConnected(sessionid, servers)
{  
    if(lastSessionAccepted == sessionid)
    {
        jc.SendPingReply(idUser, conversation, idUser, "Info: El control remoto del usuario ha sufrido un microcorte y se ha vuelto a reconectar.", NoOpCallback);
        jslog.error("Possible error on OnRemoteControlConnected. Session accepted more than one time");
        return;
    }
        
    try
    {
        // Send Accepted answer to the operator
        var oRemoteControlParams = sessionid + ";" + servers;
        jc.SendRemoteControlAcceptAnswer(idUser, conversation, idUser, oRemoteControlParams, NoOpCallback);
        
        lastSessionAccepted = sessionid;
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on OnConnected: " + exception.name + ": " + exception.message);
    }
}

// Function to handle OnObjectError event of the remote control
function OnObjectError(sessionid, servers)
{  
    ShowRCExeMessage(sessionid, servers);
    
    // Notify to operator
    jc.SendPingReply(idUser, conversation, idUser, "Info: El usuario no ha activado correctamente el control ActiveX. Se le ha mostrado un enlace para que descargue y ejecute el control remoto basado en aplicación ('Haga click aquí para descargar y ejecutar el archivo que dará comienzo a la sessión de control remoto.').", NoOpCallback);
}

// Function called to reject or cancel the remote control session
function RejectRemoteControl(sessionid)
{     

    try
    {      
        var oReject = getDOMElementById('reject_button_' + sessionid);
        
        if(navigator.appName == "Microsoft Internet Explorer")
        {
			// try to launch the remote control integrated with the client
			//if (window.external && window.external.CancelRC != null)
			
			try
			{ 
				if (window.external)
				{	
					window.external.CancelRC();
				}
			}
			catch(exception)
			{
				if(jslog != null)
					jslog.error("No window external. Cancel RC no defined. Exception: " + exception.name + ": " + exception.message);
			}
			
            var oControl = getDOMElementById('RemoteControl');
            
            if(oControl.src != "")
            {
                if( window.frames['RemoteControl'].DisconnectFromParent)
                    window.frames['RemoteControl'].DisconnectFromParent();
                else
                    oControl.src = "about:blank";

                // Send reject answer to the operator
                jc.SendRemoteControlRejectAnswer(idUser, conversation, idUser, "Remote Control Reject", NoOpCallback);
            }
        }
            
        DisableRemoteControlButtons(sessionid, 1);
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on RejectRemoteControl: " + exception.name + ": " + exception.message);
    }
}

// Function to disable remote control buttons
function DisableRemoteControlButtons(sessionid, reject)
{
    try
    {
        var oAccept = getDOMElementById('accept_button_' + sessionid);
        var oReject = getDOMElementById('reject_button_' + sessionid);
        
        if(oAccept != null)
            oAccept.disabled = true;
            
        if(oReject != null)
        {
            // If the conversation is instantiated, the reject button change its name to "Cancel" (only for internet explorer)
            if(reject == 1 || (navigator.appName != "Microsoft Internet Explorer"))
            {
                oReject.disabled = true;
			}
            else
            {
                oReject.value = lang.getText("cancelRCText");
            }
        }
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on DisableRemoteControlButtons: " + exception.name + ": " + exception.message);
    }    
}

// Function that handles the client timer event
function ClientTimer() 
{
    try
    {         
        // Get conversation events
        jc.GetConversationEvents(idUser, conversation, parseInt(lastIndex) + 1, GetConversationEventsCallback);    
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on ClientTimer: " + exception.name + ": " + exception.message);
    }
}

// Function called when GetConversationEvents function is completed
function GetConversationEventsCallback(answer)
{       
    if (conversationIsLost)
        return;
        
    try
    {
        var latestEvents = answer.result;    
    
        if(latestEvents != null) 
        {
            if (latestEvents.length > 0)
            {
                // For each event, add a client message
                for (var i = 0; i < latestEvents.length; i++)
                {       
                    // For conversation message, includes time
                    if(latestEvents[i]._type == "ConversationMessage")         
                        AddClientMessage(latestEvents[i]._sender, latestEvents[i]._type, GetCurrentTime() + " - " + latestEvents[i]._data);
                    else
                        AddClientMessage(latestEvents[i]._sender, latestEvents[i]._type, latestEvents[i]._data);
                }
                
                // Update the last index variable
                try
                {
                    lastIndex = parseInt(latestEvents[latestEvents.length - 1]._index);
                }
                catch(exception)
                {
                    lastIndex = -1;
                }
            }
        } 
        else if (latestEvents == null)
        {
            //Call failed, tries to log user again
            if(jslog != null)
				jslog.error("GetConversationEventsCallback: latestEvents == null");
            jc.LogOnEndUser(license, machinecode, langCode, NoOpCallback);            
            CheckConversationStatus();
        }   
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on GetConversationEventsCallback: " + exception.name + ": " + exception.message);
        jc.LogOnEndUser(license, machinecode, langCode, NoOpCallback);            
        CheckConversationStatus();
    }
    finally
    {
        // Launch the clientimer function again after updatePeriod time
        setTimeout(ClientTimer, updatePeriod);
    }
}

// Checks conversation status, closing chat if required
function CheckConversationStatus()
{
    try
    {
        // Checks if conversation is still active
        if (failedCalls < 20)
        {
            var convInfo = jc.GetConversationInfo(idUser, conversation);
            failedCalls = 0;
        }
            
        if (failedCalls >= 20 || convInfo == null || convInfo._startDate != convInfo._endDate) // Conversation has ended
        {    
            chatText.style.backgroundColor = "#F0F0F0";
            sentText.disabled = true;
            sentText.style.backgroundColor = "#F0F0F0";
            var sendButton = getDOMElementById("btnSend");
            sendButton.disabled = true;
                        
            conversationIsLost = true;
            
            // Try to obtain operator name
            var cUsers;
            if (convInfo != null && convInfo._conversationUsers != null)
                cUsers = convInfo._conversationUsers;
            else if (conversationUsers != null)
                cUsers = conversationUsers;
            else
                cUsers = null;
            
            if (cUsers != null)
            {
                var operNick = null;
                
                for (var i=0; i < cUsers.length; i++)
                {
                    if (cUsers[i]._type == "Operator")
                        operNick = cUsers[i]._username;
                }            
            }
            
            // Inserts reconnection message
            AddClientMessage(null, "ConversationLost", operNick);
        }
        else
            jc.JoinConversation(idUser, conversation, idUser);
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on CheckConversationStatus: " + exception.name + ": " + exception.message); 
        failedCalls++;
    }
}

// Reloads chat selecting current operator
function ReloadSelectingOperator(operatorName)
{   
    bShowSurvey = false;
    if (operatorName != "")
        window.location = window.location.href + "&oper=" + operatorName;
    else
        window.location = window.location.href;
}

// Function to send a message
function ClientSendMessage()
{   
    try
    {
        if(sentText == null)
            sentText = getDOMElementById("senttext"); 
            
        if (sentText != null)
        {
            // Only send the message if the text is not empty
            if (sentText.value.length > 0)
            {
                //Inserts text on chat before sending
                var textToInsert = GetCurrentTime() + " - " + escapeHTML(sentText.value);
                var oNewLine;
                if(document.createElement && !ieMobile)
				{
					oNewLine = document.createElement("p");
					oNewLine.className = "UserMessage";
					oNewLine.innerHTML = textToInsert;
					chatText.appendChild(oNewLine);
				    chatText.scrollTop = 200000;
				}
				else
					chatText.innerHTML = chatText.innerHTML + "<p class='UserMessage'>" + textToInsert + "</p>";
                                
                jc.InsertConversationMessage(idUser, conversation, idUser, null, sentText.value, InsertConversationMessageCallback);
            }
            
            // Set empty the text
            sentText.value = "";
        }
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on ClientSendMessage: " + exception.name + ": " + exception.message);
    }
}

// InsertConversationMessage method callback
function InsertConversationMessageCallback(answer)
{
    try
    {
        if (answer.xmlHTTP.status != 200 || answer.result === undefined)
        {
            // Response is not a 200 OK or result is undefined, resends message again after 2 seconds
            var anonFunc = function()
                           { 
                                var currentTry = 1;
                                while(currentTry <= insertMessageRetries)
                                {
                                    try
                                    {
                                        jc.InsertConversationMessage(answer.params[0], answer.params[1], answer.params[2], 
                                                                     answer.params[3], answer.params[4]);
                                        // Message sent
                                        return;
                                    }
                                    catch (exception)
                                    {
                                        if(jslog != null)
											jslog.error("Error on InsertConversationMessage: " + exception.name + ": " + exception.message);
                                        currentTry++;
                                    }
                                }
                                
                                // Message couldn't be sent
                                AddClientMessage(idUser, "MessageError", 
                                    lang.getText("messageErrorText") + escapeHTML(answer.params[4]));
                           };
            setTimeout(anonFunc, 2000); 
        }
    }
    catch (exception)
    {
        if(jslog != null)
			jslog.error("Error on InsertConversationMessageCallback: " + exception.name + ": " + exception.message);
    }
}

// Zoom in the conversation text
function ZoomInText()
{  
    try
    { 
        if(parseInt(chatText.style.fontSize) + 10 > 0)
            chatText.style.fontSize=parseInt(getDOMElementById("chattext").style.fontSize) + 10 + "%";
            
        if(parseInt(sentText.style.fontSize) + 10 > 0)
            sentText.style.fontSize=parseInt(getDOMElementById("senttext").style.fontSize) + 10 + "%";
    } 
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on ZoomInText: " + exception.name + ": " + exception.message);
    }
}

// Zoom out the conversation text
function ZoomOutText()
{  
    try
    { 
        if(parseInt(chatText.style.fontSize) - 10 > 0)
            getDOMElementById("chattext").style.fontSize=parseInt(getDOMElementById("chattext").style.fontSize) - 10 + "%";
            
        if(parseInt(sentText.style.fontSize) - 10 > 0)
            sentText.style.fontSize=parseInt(getDOMElementById("senttext").style.fontSize) - 10 + "%";
    } 
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on ZoomOutText: " + exception.name + ": " + exception.message);
    }
}

// Reset the size of the conversation text
function ResetText()
{
    try
    {
        chatText.style.fontSize="100%";
        sentText.style.fontSize="100%";
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on ResetText: " + exception.name + ": " + exception.message);
    }
}

// Send the conversation by email
function SendConversationByEmail()
{
	var Url = "SendConversationEmail.aspx";
    Url = Url + "?ConversationId=" + encodeURIComponent(conversation) + "&LanguageCode=" + langCode;
    
    try
    {  
		// OPENS DIALOG BOX      
		$( "#sendConversationIframe" ).attr ("src", Url);

		var $panel = $('#SendConversationDiv');
		$panel.css('display', 'block');
		$panel.css('top', ($('body').height() - $panel.height())/2);
		$panel.css('left', ($('body').width() - $panel.width())/2);
    }
    catch(exception)
    {
 		CloseSendConversation();
		
		// SHOWS POPUP
		var centerTop = GetCenterTopPoint() - (115/2);
		var centerLeft = GetCenterLeftPoint() - (430/2); 
		window.open(Url,'_blank','resizable=no,toolbar=no,scrollbars=no,menubar=no,status=no,directories=no,width=430,height=115,top=' + centerTop + ',left=' + centerLeft);
        if(jslog != null)
			jslog.error("Error on SendConversationByEmail: " + exception.name + ": " + exception.message);
    }
}

// Closes send conversation by email
function CloseSendConversation()
{
    try
    {
		var panelSendConversationDiv = document.getElementById("SendConversationDiv"); 
		
		if (panelSendConversationDiv != null)
			panelSendConversationDiv.style.display = "none";
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on CloseSendConversation: " + exception.name + ": " + exception.message);
    }
}

// Called when the user wants to close the chat window 
function closeWindow() 
{
    if(confirm(lang.getText("closingText"))) 
        PreClose(); 
}

// Function to close the window
function PreClose() 
{
    try
    {
        window.open('','_parent','');
        window.close(); 
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on PreClose: " + exception.name + ": " + exception.message);
    }
}

// Unload window handler
function closeBrowser() 
{   
    try
    {
        // Leave the current conversation
        if (conversation != "")
            jc.LeaveConversation (idUser, conversation, idUser);                    
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on closeBrowser: " + exception.name + ": " + exception.message);
    }
    finally
    {
        var closedConversation = new Date().getTime();
        
        var diff = (closedConversation - startConversation) / 1000;       
        
        
        // Launch the survey if it is needed        
        if (bShowSurvey == true && diff > 120)
        { 
            if (langCode=="")
                langCode = "es-ES";
                
            var Url = "GenericSurvey.aspx?"; 
            Url = Url + "Licencia=" + license + "&IdSession=" + encodeURIComponent(conversation) + "&LanguageCode=" + langCode; 
        
            if(source == "win32")
            {
				var loc = new String(window.parent.document.location); 
				if (loc.indexOf("https://")!= -1)
					prefix = "https://"; 
				else 
					prefix = "http://";    
				 
                window.external.OpenNewBrowser(prefix + location.host + '/Webpages/Client/' + Url);     
            }
            else
                window.open(Url,'_blank','resizable=yes,toolbar=no,scrollbars=yes,menubar=no,status=no,directories=no,width=810,height=760');     
        }
    }
}

// Function to disable the F5 key
document.onkeydown = function()
{
    try
    {   
        if(window.event && window.event.keyCode == 116)
            window.event.keyCode = 505;
        if(window.event && window.event.keyCode == 505)
            return false;
    }
    catch(exception)
    {
        if(jslog != null)
			jslog.error("Error on document.onkeydown: " + exception.name + ": " + exception.message);
    }
} 

//Limits max length using "maxlength" attribute on component
function isMaxLength(obj)
{
    try    
    {
        var mlength = obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
        if (obj.getAttribute && obj.value.length>mlength)
            obj.value=obj.value.substring(0,mlength)
    }
    catch (exception)
    {
        jslog.error("Error on isMaxLength: " + exception.name + ": " + exception.message);
    }
}

//Checks if ENTER key is in event
function isEnterKey (event) 
{
    try
    {
	    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	    return (keyCode == 13);
	}
    catch (exception)
    {
        if(jslog != null)
			jslog.error("Error on isEnterKey: " + exception.name + ": " + exception.message);
    }	    
}  

function escapeHTML (msg)
{
    return msg.split("&").join("&amp;").split( "<").join("&lt;").split(">").join("&gt;");
}

// Center top point
function GetCenterTopPoint()
{
    try
    {
        return screen.height/2;
    }
    catch (exception)
    {
        return 400;
    }
}

// Center left point
function GetCenterLeftPoint()
{
    try
    {
        return screen.width/2;
    }
    catch (exception)
    {
        return 300;
    }
}

// Obtains current time HH:MM:SS
function GetCurrentTime()
{
    var d = new Date();
    var hour = d.getHours();
    var min = d.getMinutes();
    var sec = d.getSeconds();

    if (hour < 10)
        hour = "0" + hour;
    if (min < 10)
        min = "0" + min;
    if (sec < 10)
        sec = "0" + sec;
        
    return hour + ":" + min + ":" + sec;
}
