////////////////////////////////////////////////////////////////////////////////////
//
//    File Description        : Login javascript file that contain function to initialize virtual keyboard
//                              and enable/disable it                     
// ---------------------------------------------------------------------------------
//    Date Created            : Jan 15, 2009)
//    Author                  : Abhishek K 
// ---------------------------------------------------------------------------------
//    Change History
//    Date Modified           :    
//    Changed By              : 
//    Change Description      : 
//
////////////////////////////////////////////////////////////////////////////////////

var MainWindow;
var keyboardImgUrl = '';
//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;
var secretAnsLen;
var bSubmitClicked = true; 
//disabling popup with jQuery magic!
function disablePopup()
{
    //disables popup only if it is enabled
    if(popupStatus==1)
    {
        $('#dvbackgroundPopup').fadeOut("slow");
        $('#dvpopupContact').fadeOut("slow");
        popupStatus = 0;
    }
}
 
// function to enable/disable keyboard input on textbox   
function CheckKBStatus()
{
  try
  {
        // if use virtual keyboard checkbox is checked, block input from normal keyboard
        if(document.getElementById('chkUseVK') != null)
        {
            if(chkVkb && chkVkb.checked == true)
            {
                VKEnabled();            
                txtBox.readOnly = true;
                txtBox.blur();
            }
            else if(chkVkb)
            {
                VKDisabled();
                txtBox.readOnly = false;
                //txtBox.blur();      
            }
        }
   }catch(e)
    {alert(e)}
}   
var vkb = null, txtBox; var chkVkb 

// Virtual keyboard constructor that takes the textbox to bind and checkbox
function init(txtpwd, chkVk,length)
{
    chkVkb =  chkVk;
    VKDisabled();
    vkb = new VKeyboard("keyboard",    // container's id
                       keyb_callback, // reference to the callback function
                       false,          // create the arrow keys or not? (this and the following params are optional)
                       false,          // create up and down arrow keys? 
                       false,         // reserved
                       true,          // create the numpad or not?
                       CONST_VK_FONT,                   // font name ("" == system default)
                       CONST_VK_FONT_SIZE,              // font size in px
                       CONST_VK_FONT_COLOR,             // font color
                       CONST_VK_DEAD_FONT_COLOR,        // font color for the dead keys
                       CONST_VK_BASE_BGCOLOR,           // keyboard base background color
                       CONST_VK_KEY_BGCOLOR,            // keys' background color
                       CONST_VK_KEY_SELECTED_BGCOLOR,   // background color of switched/selected item
                       CONST_VK_BORDER_COLOR,           // border color
                       CONST_VK_INACTIVE_KEY_COLOR,     // border/font color of "inactive" key (key with no value/disabled)
                       CONST_VK_INACTIVE_KEY_BGCOLOR,   // background color of "inactive" key (key with no value/disabled)
                       "#F77",        // border color of the language selector's cell
                       true,          // show key flash on click? (false by default)
                       CONST_VK_FLASH_FONT_COLOR,       // font color during flash
                       CONST_VK_FLASH_KEY_BGCOLOR,      // key background color during flash
                       CONST_VK_FLASH_BORDER_COLOR,     // key border color during flash
                       true,         // embed VKeyboard into the page?
                       CONST_VK_GAP,                    // true for gap between the keys else false
                       0,           // index(0-based) of the initial layout
                       "url("+keyboardImgUrl+")", // bacground image for the keyboard 
                        chkVk,                          // to know the status of virtual keyboard
                        CONST_VK_GAP_PX,                // if gap between the keys is true then pixels for gap
                        CONST_VK_BORDER,                // Outer border of VK 
                        CONST_VK_GAP_NUM);              // Gap between Keyboard and Numpad  
                       
                       secretAnsLen = length;
                       txtBox = txtpwd;
}

// Callback function called from virtual keyboard:
function keyb_callback(ch)
{
    // If use virtual keyboard chechbox is not checked then return without doing anything
    if(!chkVkb.checked)
    {
        return;
    }
//    if(ch == '"')
//        return;
    var val = txtBox.value;
    
    chkPass(val);
    switch(ch)
    {
       case "BackSpace":
         var min = (val.charCodeAt(val.length - 1) == 10) ? 2 : 1;
         txtBox.value = val.substr(0, val.length - min);
         break;

       case "Enter":
         //txtBox.value += "\n";
         Submit();
         break;

       default:
       if(txtBox.value.length < secretAnsLen)
            txtBox.value += ch;
     }
}

// Function to validate keypress event 
function ValidatKeyPress(e, validationType, allowDecimal)
{
    var IsValid = false; 
    try
    {
        // if Validation Type is numeric type
        if(validationType == C_V_NUMERIC)
        {
            if(Text_NumKeyPress(e))
            {
                if(GetKeyCode(e) == 13)
                {
                    Submit();
                }
                IsValid = true;
            }
            if(document.all)
            {}
            else
            {
                if(GetKeyCode(e) < 32)
                {
                    return true;    
                }
            }
            // if allowDecimal is true and key pressed is '.'
            if(allowDecimal && GetKeyCode(e) == 46)
                IsValid = true;
        }
        // if Validation Type is alphanumeric type
        else if(validationType == C_V_ALPHANUM)
        {
            // check whether the key pressed is alphanumeric or not 
            if(Text_NumAlphaKeyPress(e))                                                
            {   
                // if enter key is pressed, submit the form
                if(GetKeyCode(e) == 13)
                {
                    Submit();
                }
                else
                {
                    // if key pressed is '&' or '-'
                    if(GetKeyCode(e) == 38 || GetKeyCode(e) == 45)
                    {
                        IsValid = false;
                    }
                    else
                        IsValid = true;
                }
            }
        }
    }
    catch(e)
    {
        alert(e.message);
    }
    return IsValid;
}
    
    // function to submit the form
    function Submit()
    {
        try
        {
            bSubmitClicked = false;
            document.getElementById('btnLogon').click();
        }
        catch(e) { alert(e.message); }
    }
    
    // This function is for Forgot Password 'Enter Key' functionality ...
    function ValidateKeyPressForgotPwd(e)
    {
        try
        {
            /*if(GetKeyCode(e) == 13)
                document.getElementById('btnSubmit').click();*/
        }
        catch(e)
        {
            alert(e.message);
        }
    }
    
    function ClearForm()
    {
        try
        {
            document.getElementById('txtClientID').value = "";
            if(document.getElementById('txtGroupID'))
                document.getElementById('txtGroupID').value = "";
            document.getElementById('txtPassword').value = "";
            document.getElementById('txtPassword').readOnly = false;
            document.getElementById('lblLogonMsg').innerHTML = "";
            
            $(document.getElementById('LoginValidationSummary')).text("");  
            
            if(document.getElementById('chkUseVK'))
                document.getElementById('chkUseVK').checked = false;
            document.getElementById('chkRememberMyId').checked = false;
            if(document.getElementById('hidDefaultLoginMode'))
            {
                if(document.getElementById('hidDefaultLoginMode').value == '0')
                    document.getElementById('rRefresh').checked = true;
                else
                    document.getElementById('rStream').checked = true;
            }
            if(document.getElementById('chkUseProxy').checked = true)
            {
                document.getElementById('txtProxyIP').value = "";
                document.getElementById('txtProxyPort').value = "";
                document.getElementById('txtProxyUid').value = "";
                document.getElementById('txtProxyPwd').value = "";
                document.getElementById('chkUseProxy').checked = false;
                document.getElementById('chkRememberProxy').checked = false;
               // document.getElementById('divProxy').style.display='none';
            }
            if(document.getElementById('divMemberId') != null)
            {
                document.getElementById('txtGroupID').focus();
            }
            else
            {
                document.getElementById('txtClientID').focus();
            }
            CheckKBStatus();
            return false;
        }
        catch(e) {alert(e.message); }
    }
    
    function OpenMainWindow()
    {
        MainWindow = window.open('" + Constants.LOGIN_NAVIGATION_URL + "','hMain" + FT.SessionManager.GetLoggedinUser.UserCode + "','maximize=no,toolbar=no,menubar=no,left=0,top=0,status=yes,width=1020px ,height=720px,scrollbars=yes'); 
        MainWindow.opener=top;
        window.close();
    }

    // function to check whether the key pressed is a valid password character
    // < > ' , . _ : ; these special characters are allowed for password
    function CheckPwdChars(eve)
    {
        try
        {
            // If use virtual keyboard checkbox is checked then return without doing anything
            if(chkVkb)
            {
                if(chkVkb.checked == true)
                {
                    return false;
                }
            }
            
            var eveKeyCode = GetKeyCode(eve);
            if (eveKeyCode == 13)
            {   
            //This is being commented since on click of Enter key EncryptPwd function was called for two times.
                //Submit();       
            }
            if(eveKeyCode == 8)
                return true;
                
            //for space
            if(eveKeyCode == 43)
                return true;
                
               if(eveKeyCode == 32)
                {
                    return false;    
                } 
                
            if(document.all)
            {}
            else
            {
                if(eveKeyCode == 32)
                {
                    return false;    
                }
            }
//            if(!(eveKeyCode >= 48 && eveKeyCode <= 57) && !(eveKeyCode >= 97 && eveKeyCode <= 122)&& !(eveKeyCode >= 65 && eveKeyCode <= 90))
//            {   		
//                if((eveKeyCode >= 58 && eveKeyCode <= 60) || eveKeyCode == 62 || eveKeyCode == 39
//                    || eveKeyCode == 44 || eveKeyCode == 46 || eveKeyCode == 95 )
//                    return true;	
//                return false;
//            }
            
//            if(eveKeyCode == 124  || eveKeyCode == 61)
//            {
//                return false;    
//            }
            return true;
        }
        catch(e)
        {
//          alert('CheckPwdChars' + e.message);
        }        
    }

    ////the function that retrieves MAC Address of client machine.
    function getMacAddress()
    {
        try
        {
            var macaddress = "-1";
            macaddress = document.macaddressapplet.getMacAddress();
            if(macaddress != "-1" && macaddress != null ) {
                if(macaddress != "Improper version") {
                    document.getElementById('hidMACAdress').value = unescape(macaddress);    
                    //alert( "Mac Address = " + document.getElementById('hidMACAdress').value );
                }
                else 
                {
                    showModalPopup('NetNet','JRE 1.6.0 or above Component is required',null);
                }
            }
            else {
                document.getElementById('hidMACAdress').value = "not found";    
            }
        }
        catch(e)
        {
            showModalPopup('NetNet','JRE 1.6.0 or above Component is required',null);
        }
    }
    
    ////the function that encrypts password of user.
    function EncryptPwd()
    {
        // Text to encrypt.
        var pwd = document.getElementById('txtPassword').value;
        // 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);
        //document.getElementById('hidEncryptPwd').value = encryptedPwd;
       
        var strLength = encryptedPwd.length;    
        document.getElementById('txtPassword').maxLength = strLength;
        document.getElementById('txtPassword').value = encryptedPwd;
        
    }
    
    function checkJavascriptValidity()
    {
        document.getElementById(C_S_LOGIN_JSENBL_ID).style.display='block';
//      document.getElementById(C_S_LOGIN_JSDEBL_ID).style.display='none';
        document.getElementById(C_S_LOGIN_BUTTONS_ID).style.display='block';
        document.getElementById(C_S_LOGIN_USRGUIDE_ID).style.display='block';
        if(document.getElementById('divLogin').style.display == 'block' || document.getElementById('divLogin').style.display == '')
        {
            if(document.getElementById('txtGroupID'))
                document.getElementById('txtGroupID').focus();
            else
                document.getElementById('txtClientID').focus();
        }
        CheckKBStatus();
    }
    
    //the function close current login page with disabled login div and opens a new login page 
    function DisplayLoginDiv()
    {   
        OpenWindow(LOGIN_URL, "");
    }
    
    function ClearMsg()
    {
        if(document.getElementById('lblLogonMsg') != null)
        {
            document.getElementById('lblLogonMsg').innerHTML = "";
        }
        if(bSubmitClicked == false)
        {
            bSubmitClicked = true;
            return false;
        }
    }
    //to check for poup blocker
    function isPopUpBlocked()
    {
        var retVal = false;
        if(C_S_POPUPCHECK == 'Y')
        {
            var popUpHandle = window.open('', '', "maximize=no, toolbar=no, menubar=no, left=0, top=0, status=no , width=1px, height=1px,scrollbars=no");
            if(popUpHandle)
            {
                popUpHandle.close();
            }
            else
            {
                retVal = true;
            }
            popUpHandle = null;
        }
        return retVal;
    }
    
    //show jquery alert for PopUpBlocker
    function showDisablePopUpBlockMsg()
    {
        if(isPopUpBlocked())
        {
            showModalPopup('Login', 'Please disable PopUp Blocker to proceed', null);
        }
    }  
    
    function ShowProxyFields()
    {
        try
        {
            if(document.getElementById('chkUseProxy').checked)
            {
                document.getElementById('divProxy').style.display='block';
                //document.getElementById('rfvProxyIP').disabled = false;
                //document.getElementById('rfvProxyPort').disabled = false;
                document.getElementById('revProxyPort').disabled = false;
                document.getElementById('txtProxyIP').focus();
            }
            else
            {
                document.getElementById('divProxy').style.display='none';                            
                //document.getElementById('rfvProxyIP').disabled = true;
                //document.getElementById('rfvProxyPort').disabled = true;
                document.getElementById('revProxyPort').disabled = true;
            }
        }
        catch(e)
        {alert('ShowProxyFields' + e);}
    }
    
    function ShowSyncFields()
    {
        try
        {   
            if(document.getElementById('divSync').style.display == 'none')
            {
               document.getElementById('divSync').style.display = 'block'
            }
            else
            {
               document.getElementById('divSync').style.display = 'none'
            }
            return false;
        }
        catch(e)
        {
            return false;
        }
    }
    
    function OpenLoginFAQ()
    {
        try
        {   
	        window.open(LOGINFAQ_URL, '', "maximize=no, toolbar=no, menubar=no, left=0, top=0, status=yes , width=1000px, height=600px, scrollbars=yes");
        }
        catch(e)
        {}
    }
    
    function OpenLoginJRE()
    {
      try
        {   
	        window.open(JRE_URL, '', "maximize=no, toolbar=no, menubar=no, left=0, top=0, status=yes , width=1000px, height=600px, scrollbars=yes");
        }
        catch(e)
        {}
    }
    
    function ValidateFields()
    {   
        try
        {
            // if it is Authentication request
            if(document.getElementById('divSync').style.display == 'none')
            {
                document.getElementById('hidAction').value = '0';
                if(document.getElementById('txtOtp1').value == '')
                {
                    document.getElementById('lblAuth').innerHTML = OTP1_MSG;
                    return false;
                }
                return true;
            }
            // if its synchronization request
            if(document.getElementById('divSync').style.display == 'block')
            {
                document.getElementById('hidAction').value = '1';
                if(document.getElementById('txtOtp1').value == '')
                {
                    document.getElementById('lblAuth').innerHTML = OTP1_MSG;
                    return false;
                }
                if(document.getElementById('txtOtp2').value == '')
                {
                    document.getElementById('lblAuth').innerHTML = OTP2_MSG;
                    return false;
                }
                return true;
            }
        }
        catch(e)
        {}
    }
    
function VKDisabled()
{
 $(document.getElementById('keyboard')).fadeTo("slow",0.25);
}

function VKEnabled()
{
 $(document.getElementById('keyboard')).fadeTo("slow",1);
}

function openWindow(strValue)
{
try
   {
    window.open(strValue, '', "maximize=no, toolbar=no, menubar=no, left=0, top=0, status=yes , width=1000px, height=600px, scrollbars=yes");
   }
catch(e)
    { 
    }
}
//Log Out User on closing the browser without using LogOut option-- Added for CR 1194 by ShwetaA
 function LogOutUser()
 {
      bLogOffClicked=true;//To avoid opening of session expiry page
       if (!bSessionExpire)
        {
            var params = "param=" + C_V_TAG_MSGCODE + ND + C_V_LOGOFFUSER;
            
            $.ajax({
               type: "POST",
               async: false,
               url: AJAXDATAFETCHER_URL,
               data: params,
               dataType: "text",               
               error: HandleAjaxError
         });
         bSessionExpire = true;
      }
  }

