﻿// JScript File
iXPrevMousePos = 0; // Previous Horizontal position of the mouse on the screen
iYPrevMousePos = 0; // Previous Vertical position of the mouse on the screen
iXMousePos = 0; // Horizontal position of the mouse on the screen
iYMousePos = 0; // Vertical position of the mouse on the screen
var tPrevDate=new Date(); 
var bConsoleLock = false;
var bSessionExpire = false;
var bReady = false;
//Default Console Session Timeout value as 3 min. The value is in ms
var iConsoleSessionTimeout = 180000;
icounter = 0;
var bLogOffClicked = false;

function setConsoleSessionTimeOut(iConSessionTimeout)
{     
  iConsoleSessionTimeout=iConSessionTimeout;  
}

function SetReady()
{
    bReady = true;
}

/* Following function is invoked on any mouse move event. It compares 
the x & y positions of mouse. if the mouse movement is after session timeout,
then it locks the console else it updates the timestamp 
*/
function UpdateClientSession(e)
{
    if (!bConsoleLock && !bSessionExpire)// && bReady) //Remaining condition is commented since console donot work properly for Net allied product
    {    
        var IsKeyEvent = false;
        if (GetKeyCode(e) != 0)
        {
            IsKeyEvent = true;
        }       
        else
        {
            if(document.all)
            {
                iXMousePos = e.x;
                iYMousePos = e.y;
            }
            else
            {
                iXMousePos = e.layerX;
                iYMousePos = e.layerY;
            }
        }
        
        lockConsole();
        if (iXMousePos != iXPrevMousePos ||  iYMousePos != iYPrevMousePos || IsKeyEvent == true)
        {   
            tPrevDate = new Date();
            iXPrevMousePos = iXMousePos;
            iYPrevMousePos = iYMousePos;
            //Uncomment below 2 lines for debugging console lock issues.             
            //icounter = icounter + 1;
            //window.status = "counter = " + icounter; 
        }  
    }   
}

/*The following function will check whether the time difference between the 
  current time and the time of last mouse move is greater than the console session timeout.
  If so then it will lock the console by sliding an opaque div and will also slide the div 
  for Password. Also a flag would be set when the console gets locked. The value of this 
  flag would be checked while opening any popup. This is just to avoid any pop up opening 
  after console lock by tab and then enter click*/
function lockConsole()
{    
    var tCurrDate=new Date();
    var nTimeDiff = tCurrDate - tPrevDate;
    if(nTimeDiff > iConsoleSessionTimeout)
    {
        centerPopup();
        loadPopup(); 
        closePopUps(); 
        bConsoleLock = true;
        HandleConsoleLock();//To check for consolelock timeout
        document.getElementById("ctl00_txtPassword").value = '';
        document.getElementById("ctl00_txtPassword").focus();                  
    } 
}

// this function is called when the user presses the HotKey for locking the console
function lockConsoleOnDemand()
{
    centerPopup();
    loadPopup(); 
    closePopUps(); 
    bConsoleLock = true;
    HandleConsoleLock();//To check for consolelock timeout
    document.getElementById("ctl00_txtPassword").value = '';
    document.getElementById("ctl00_txtPassword").focus();  
}

//loading popup with jQuery magic!
function loadPopup(){
//loads popup only if it is disabled

$(".sessionDiv").css({
"opacity": "0.5"
});
$(".sessionDiv").fadeIn("fast");
$(".popupPassword").fadeIn("slow");

}
 

//disabling popup with jQuery magic!
function disablePopup(){
//disables popup only if it is enabled
{
$(".sessionDiv").fadeOut("slow");
$(".popupPassword").fadeOut("slow");
}
}
 

//centering popup - Positions the opaque div and password div
function centerPopup(){
//request data for centering
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $(".popupPassword").height(); 
var popupWidth = $(".popupPassword").width(); //centering 
$(".popupPassword").css({
"position": "absolute",
"top": window.parent.document.getElementById('frOE').parentNode.offsetTop,//Modified for crossbrowser compatibility
"left": 0,
"height": C_V_ORDER_ENTRY_FRAME_HEIGHT
});
//only need force for IE6
$(".sessionDiv").css({
"height": windowHeight
});
}

/* This function will have synchronous AJAX implementation for Authentication.
After Console lock, user can unlock by keying the password. On successful authentication
of password and checking the session validity at server end, the console gets unlocked
and the timestamp of mouse move is updated
*/
function AuthenticatePwd()
{
    //Ajax Implementation 
    document.getElementById("ctl00_lblPwdMessage").style.display='none';
    var strPwd = document.getElementById("ctl00_txtPassword").value;
    EncryptPwd(strPwd);
    strPwd = document.getElementById("ctl00_txtPassword").value;
    var strData = "param=" + C_V_TAG_MSGCODE + ND + C_V_TAG_VALIDATEPWD + FD + C_V_TAG_PWD + ND + encodeURIComponent(strPwd);    
    $.ajax({
           async: false, 
           type: "POST",
            url: AJAXDATAFETCHER_URL,
           cache: false,
           dataType: "text",
           data: strData,
           success: PwdValidated,
           error: HandleAjaxError
     });
     return false;
}

function EncryptPwd(sDataToEncrypt)
{
    // Text to encrypt.
        var pwd = sDataToEncrypt;
        var sEncryptedData;
        // Use OAEP padding (PKCS#1 v2).
        var doOaepPadding = true;
        // RSA 512-bit key: Public (Modulus), Private (D) and CRT (P, Q, DP, DQ, InverseQ).
        var xmlParams =
        "<RSAKeyValue>" +
        "<Modulus>pxtmFnrGI6Sb8ziyY+NRUDuQ4b/ETw5WabQ4daFQqzsCEr/6J/LLBU/2D5mO5/Wu5U/Rya1E55aYFZeaZMNqAw==</Modulus>" +
        "<Exponent>AQAB</Exponent>" +
        "<P>2TsVXWPEvDIJv/gd2rX9k0UOyXuaYgoAchIH6vUicis=</P>" +
        "<Q>xO4+OYREQfqYRQK7y73+RaUG0IxobT0OQ0c+Ok2hc4k=</Q>" +
        "<DP>K7/xgpiIU9rECeyfnp/OjS14V+3T3vDivBaTj6eFI3c=</DP>" +
        "<DQ>K4N9ClZ4gp+tn6oP9t//XEIvtEsiE+kmyqTmUhmvMAk=</DQ>" +
        "<InverseQ>p7o4BOlKZQZ693R1ViZ66y5gTjUkNNTd2za7/1YGBCs=</InverseQ>" +
        "<D>XZqFVrYy4qhECruJgVZFp/GVuD5Y0gev88nVjl5r911QT+I8vgJSklTso7jTlpMtf2oe7UZ0WRWEtgPS3tZn4Q==</D>" +
        "</RSAKeyValue>"; 
        // ------------------------------------------------
        // RSA Keys
        // ------------------------------------------------
        var rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
        // Import parameters from XML string.
        rsa.FromXmlString(xmlParams);
        // Export RSA key to RSAParameters and include:
        //    false - Only public key required for encryption.
        //    true  - Private key required for decryption.
        // Export parameters and include only Public Key (Modulus + Exponent) required for encryption.
        var rsaParamsPublic = rsa.ExportParameters(false);
        // Export Public Key (Modulus + Exponent) and include Private Key (D) required for decryption.
        var rsaParamsPrivate = rsa.ExportParameters(true);
        // ------------------------------------------------
        // Encrypt Password
        // ------------------------------------------------
        var decryptedPwdBytes = System.Text.Encoding.UTF8.GetBytes(pwd);
        // Create a new instance of RSACryptoServiceProvider.
        rsa = new System.Security.Cryptography.RSACryptoServiceProvider();
        // Import the RSA Key information.
        rsa.ImportParameters(rsaParamsPublic);
        // Encrypt byte array.
        var encryptedPwdBytes = rsa.Encrypt(decryptedPwdBytes, doOaepPadding);
        // Convert bytes to base64 string.
        var encryptedPwd = System.Convert.ToBase64String(encryptedPwdBytes);
        sEncryptedData = encryptedPwd;
        document.getElementById('ctl00_txtPassword').value = sEncryptedData; 
   
}
    
// called when the AJAX call is executed successfully
function PwdValidated(strResponse)
{
    //Following function is invoked for Session Maangement.
    //In case Session has expired then the AJAX page would return Session Expiry code
    //as response
    if(!ValidateSession(strResponse))
        return false;
    if(strResponse == C_S_YES)
    {
        disablePopup();
        tPrevDate = new Date();
        bConsoleLock = false;
        document.getElementById("ctl00_txtPassword").value = '';
        HandleConsoleUnlock();//To start touchline request if it was stopped
    }
    if(strResponse == C_S_NO)
    {
        document.getElementById("ctl00_txtPassword").value = '';
        document.getElementById("ctl00_lblPwdMessage").style.display='block';
        return false;
    }
}

function EnterKeyforPwd(e)
{
    if(GetKeyCode(e) == 13)
    {
        AuthenticatePwd();
        return false;       
    }  
    
}

//Following Function would close all the pop ups and would replace to Session Expire Page
function ExpireSession()
{
    if(!bSessionExpire)
    {
        bSessionExpire = true;
        bConfirmExit = false;
        closePopUps();     
        OpenWindow(SESSIONEXPIRE_URL + '?SessionExpired=0','');
    }
}



