﻿// JScript File
function getHtmlObjectById(vId) {

    if (document.getElementById && document.getElementById(vId) != null) {
         return document.getElementById(vId);
    }
    else if (document.layers && document.layers[vId] != null) {
        return document.layers[vId];
    }
    else if (document.all) {
        return document.all[vId];
    }
}

function hideObject(aObj) {
    
    if (document.getElementById && document.getElementById(aObj) != null) {
         node = document.getElementById(aObj).style.display='none';
    }
    else if (document.layers && document.layers[aObj] != null) {
        document.layers[aObj].display = 'none';
    }
    else if (document.all && document.all[aObj] != null) {
        document.all[aObj].style.display = 'none';
    }
}

function showObject(aObj) {

    if (document.getElementById && document.getElementById(aObj) != null) {
         node = document.getElementById(aObj).style.display='';
    }
    else if (document.layers && document.layers[aObj] != null) {
        document.layers[aObj].display = '';
    }
    else if (document.all && document.all[aObj] != null) {
        document.all[aObj].style.display = '';
    }
}

function ifbsOnOthersSelected(isChecked, strSectionForOthers)
{
    if (isChecked) 
        showObject(strSectionForOthers); 
    else 
        hideObject(strSectionForOthers); 
}

function ifbsSetLabelText( strLabelClientID, strValue) { 
    var theLabel = getHtmlObjectById(strLabelClientID);
    if (theLabel.innerText || theLabel.innerHTML) {
        theLabel.innerText = strValue;
        theLabel.innerHTML = strValue;
    }
    else {
        theLabel.textContent = strValue;
    }
}

//Function to Detect if 'Val' exist in the array 'listArray'
//if yes, return true
//if no, return false
function ExistInArray( listArray, Val )
{
    var a = 0
    while (a < listArray.length)
    {
        if (listArray[a] == Val)
        {
            return true;
        }
        a++;
    }
    return false;
}

//Function to Limit the control to be able to insert the indicated maxlength of characters.
//For validation of Maxlength of MultiLine Textbox.
function ConcatMaxLength(control, maxlength) 
{
    //var maxlength = new Number(strlength);
    var CtrlValue = control.value;   //Get the value
    var bConcat = false;
    var iCount = 0;
    
    //check if length already exceeds the maxlength
    if (CtrlValue.length  > maxlength) {
      //if not then truncate the exceeding text
      CtrlValue = CtrlValue.substring(0,maxlength);
      bConcat = true;
    }
    
    //Replace special characters with 2 chars
    //The problem is due to .NET and javascript difference when trying 
    //to read the number of chars. So we need to make it 
    //the same as .NET
    
    //*Note: need to add /g to make it a global string replace 
    // if not then the first occurence of text will only be replaced   
      CtrlValue = CtrlValue.replace(/\'/g, "");
      CtrlValue = CtrlValue.replace(/\&/g, "");
      CtrlValue = CtrlValue.replace(/\\/g, "");
      CtrlValue = CtrlValue.replace(/\n/g, "");
      CtrlValue = CtrlValue.replace(/\r/g, "");
      CtrlValue = CtrlValue.replace(/\r/g, "");
      CtrlValue = CtrlValue.replace(/\t/g, "");
      CtrlValue = CtrlValue.replace(/\b/g, "");
      CtrlValue = CtrlValue.replace(/\f/g, "");
                                                           

    //after replacing the special chars 
    //check max length
    if ( CtrlValue.length > maxlength) {
         //get the number of characters to be truncated
         iCount = CtrlValue.length - maxlength;
         //subtract the number of characters to be truncated to the maxlength
         control.value = control.value.substring(0,maxlength - iCount);
    } 
    else if ( bConcat ) {
    
      	control.value = control.value.substring(0,maxlength);
   }
    
}
    
function SafeValidatorEnable( ControlName, Enabled )
{
    if( getHtmlObjectById(ControlName) != undefined ){
        ValidatorEnable( getHtmlObjectById(ControlName), Enabled);  
    }  
}    
    
//Put this into the javascript file
function CheckAllValidatorsValid()
{
    //Check if Page_Validators are already generated
    if ((typeof(Page_Validators) != "undefined") && (Page_Validators != null)) 
    {
        //Variable declaration
        var i;

        //Check All Validators
        if ( Page_Validators.length > 0 )
        {
            try
            {
                for (i = 0; i < Page_Validators.length; i++) 
                {
                    //If Validator is invalid
                    if (!Page_Validators[i].isvalid) 
                    {
                        //set focus to control to validate
                        ValidatorSetFocus(Page_Validators[i], this.event);
                        //additional line just to make sure it focus due to problems in mulitple checkbox, 
                        //multiple radio button and multi select listbox
                        getHtmlObjectById(GetControlToValidate(Page_Validators[i].controltovalidate)).focus();
                        return;
                    }
                }
                //If all validators are valid then focus on the first control
                getHtmlObjectById(GetControlToValidate(Page_Validators[0].controltovalidate)).focus();
            }
            catch(ex)
            {
                //Need this exception handling to capture hidden or controls that 
                //cannot be focused like custom validators controltovalidate
            }
        }
    }
}

function GetControlToValidate(ControlToValidate)
{
    //get handle of the control
    var ctrl = getHtmlObjectById(ControlToValidate);
    //check if ordinary control
    if (typeof(ctrl.value) == "string" && (ctrl.type != "radio" || ctrl.checked == true)) 
    {
        return ControlToValidate;
    }
    else  //not ordinary control (multiple checkbox , multiple radiobutton , 
    //multiselect dropdown and etc.
    {
        //Append _0 to focus on the first item
        return ControlToValidate + '_0';
    }
}

//=====Functions needed for Master/Detail GridView===
function switchViews(obj)
{
    var div = document.getElementById(obj);
    var img = document.getElementById('img' + obj);
    
    if (div.style.display=="inline")
    {
        div.style.display = "none";        
        img.src="../../../Images/add.gif";
        img.alt = "Expand to show Miscellaneous Items";
    }
    else
    {
        div.style.display = "inline";
        img.src="../../../Images/minus.gif"           
        img.alt = "Close Miscellaneous Items";
    }
   
}

var latestTotalPayable;
var selectedIndexArray = new Array();
function ReCalculateSubTotal(ddl, ddlId, tblId, tdTopTotal, parentTotalPrice, parentPrice, parentQty)
{
    var price=0;
    var qty =0;    
    var totalAmt = 0;
    var currAmt = 0;
    var totalMinusAmt = 0;
    var isConcession = false;
    var ddlVal = ddl.options[ddl.selectedIndex].value;    
    var discntAmt = 0;
    //if discntAmt is passed from Counter Staff Login Discount DDL, its format is ID:Value
    if(ddlVal.indexOf(':') > -1)
    { 
        if(ddlVal.split(':')[3] == 'V') 
            discntAmt = parseFloat(parentQty * parseFloat(ddlVal.split(':')[2]));
        else
            discntAmt = parentQty * parentPrice * (parseFloat(ddlVal.split(':')[2]) / 100);
    }
    
    if(discntAmt > (parentQty * parentPrice)) {discntAmt= (parentQty * parentPrice);} // checking for negative value;
    //parent total price
    totalAmt = parentTotalPrice - discntAmt;    
    //calculate the amout to subtract from total
    totalMinusAmt = parseFloat(discntAmt);
    if(tblId != '') //changed on 25 Feb 2010 (CR by SSC)
    {
        var table = document.getElementById(tblId);           
        for(var trIndex=0; trIndex<table.rows.length -1; trIndex++)
        {   
            //to skip header row
            discntAmt = 0;
            if(trIndex > 0)
            {
                    isConcession = false;
                    
                    if(table.rows[trIndex].cells[3] != null) { price = table.rows[trIndex].cells[3].innerHTML; }
                    if(table.rows[trIndex].cells[4] != null) { qty = table.rows[trIndex].getElementsByTagName("input")[1].value; } //table.rows[trIndex].cells[4].innerHTML; }
                    if(table.rows[trIndex].cells[5] != null) 
                    {   
                        if(price.indexOf('$') > -1) { price = price.split('$')[1]; }
                        //if(qty.indexOf('$') > -1) { qty = qty.split('$')[1]; }
                        if(table.rows[trIndex].cells[6] != null)
                        {
                            if(table.rows[trIndex].cells[6].innerHTML == "Y"){ isConcession=true; }
                        }
                        if(isConcession == true)                        
                        {
                            if((qty * price) > 0)
                            {
                                if(ddlVal.indexOf(':') > -1)
                                { 
                                    if(ddlVal.split(':')[3]=='P') 
                                        discntAmt = qty * price * (parseFloat(ddlVal.split(':')[2]) / 100);                                        
                                    //else
                                    //discntAmt = parseFloat(qty * parseFloat(ddlVal.split(':')[2]));                                    
                                }
                                if(discntAmt > (qty * price)) {discntAmt= (qty * price);} // checking for negative value;
                                
                                currAmt = parseFloat(qty * price) - parseFloat(discntAmt);                                
                                totalMinusAmt = parseFloat(totalMinusAmt) + parseFloat(discntAmt);                                
                            }
                            else { currAmt = 0; }
                        }
                        else
                        {
                            currAmt = ((qty * price) > 0) ? parseFloat(qty * price) : 0;                            
                        }                        
                        table.rows[trIndex].cells[5].innerHTML = formatCurrency(currAmt); //'$' + currAmt.toFixed(2);
                    }                
                    totalAmt =  parseFloat(totalAmt) + parseFloat(currAmt);
            }
        }
    }
    
    //save latest applied amount (discount included) for this item
    var latestPrice = 0;
    var foundIndex = -1;
    if(selectedIndexArray.length > 0)
    {
        for(var i in selectedIndexArray) 
        {            
	        var value = selectedIndexArray[i];
	        var ctlId;
	        if(value.indexOf(':') > -1)
	        {
	            ctlId = value.split(':')[0];
	            latestPrice = value.split(':')[1];	            
	        }	        
	        if(ctlId == ddlId)
	        {
	            //latestTotalPayable = parseFloat(latestTotalPayable) + parseFloat(latestPrice);
	            foundIndex = i;
	            break;	            
	        }	        
        }        
        //save latest price in js array
        if(foundIndex > -1) { selectedIndexArray.splice(foundIndex,1); }
        if(ddlVal.indexOf(':') > -1)
        {
            selectedIndexArray.push(ddlId + ':'  + parseFloat(totalMinusAmt));
        }
        //alert(latestPrice);
    }
    else
    {
        if(ddlVal.indexOf(':') > -1)
        {
            selectedIndexArray[0]=ddlId + ':'  + parseFloat(totalMinusAmt);
        }
    }
    
    var topTotal = document.getElementById(tdTopTotal);
    if(topTotal != null)
    {
        totalAmt = parseFloat(totalAmt);
        if(totalAmt <= 0){totalAmt = 0;}
        topTotal.innerHTML = formatCurrency(totalAmt);//'$' + totalAmt.toFixed(2);
    }
}

function formatCurrency(num) 
{
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}



function openlink(link)
{
    window.open(link);

}


//=== End of Master/Detail GridView Functions ===

//=== update panel animation ===
function onPanelUpdating(progressPnl, targetCtl) 
{    // get the divImage
    var panelProg = $get(GetClientId(progressPnl));
    // set it to visible
    panelProg.style.display = '';
    
    //  get the target element
   var tgCtl = $get(GetClientId(targetCtl));
    
    // get the bounds of both the gridview and the progress div
    var tgCtlBounds = Sys.UI.DomElement.getBounds(tgCtl);
    var panelProgBounds = Sys.UI.DomElement.getBounds(panelProg);
    
    //	do the math to figure out where to position the element (the center of the gridview)
    var x = tgCtlBounds.x + Math.round(tgCtlBounds.width / 2) - Math.round(panelProgBounds.width / 2);    
    var y = tgCtlBounds.y + Math.round(tgCtlBounds.height / 2) - Math.round(panelProgBounds.height / 2);
    
    //	set the progress element to this position
    Sys.UI.DomElement.setLocation (panelProg, x, y);
}
function onPanelUpdated(progressPnl) 
{    // get the divImage
    var panelProg = $get(GetClientId(progressPnl));
    // set it to invisible
    panelProg.style.display = 'none';
}
//=== end of update panel animation ===

//get the client id of control by passing the design-time name
function GetClientId(strid)
{
     var count=document.getElementsByTagName ('*').length; //document.forms[0].length;
     var i=0;
     var eleName;
     for (i=0; i < count; i++ )
     {
       eleName=document.getElementsByTagName ('*')[i].id; //document.forms[0].elements[i].id;
       pos=eleName.indexOf(strid);
       if(pos>=0)  break;           
     }
    return eleName;
}

//disable and show animation when submit button was clicked 
//before redirecting to another page
function disableButtonOnClick(oButton, progressPnl, targetCtl)
{   
    oButton.disabled = true; 
    onPanelUpdating(progressPnl, targetCtl) 
}

function disableKioskButtonOnClick(oButton, progressPnl, targetCtl)
{   
    oButton.value = "Processing. Please wait...";
    oButton.disabled = true; 
    onPanelUpdating(progressPnl, targetCtl) 
}

//==Page Freezing block===
function disableEntirePage(element)
{
    var blurDiv = document.createElement("div");
    blurDiv.id = "blurDiv";    
    //blurDiv.style.cssText = "position:absolute; top:0; right:0; text-align: center; vertical-align: bottom; width:" + document.body.scrollWidth + "px; height:" + document.body.scrollHeight + "px; font-size: 24px; font-family: verdana; color:#c0c0c0; background-color: Gray; opacity: 0.8; filter:alpha(opacity=80)";
    blurDiv.style.cssText = "position:fixed; top:0; right:0; left:0; bottom:0; text-align: center; vertical-align: bottom; font-size: 24px; font-family: verdana; color:#c0c0c0; background-color: Gray; opacity: 0.8; filter:alpha(opacity=80)";
    document.getElementsByTagName("body")[0].appendChild(blurDiv);
    blurDiv.setAttribute("align","center");
    
    var spanTag = document.createElement("span");
    spanTag.id = "imgSpan";
    spanTag.style.cssText = "color: Navy; margin:3px; vertical-align: bottom; font:bold 12px Arial, Helvetica, sans-serif;";
    spanTag.innerHTML = "<img src='../../../Images/progress.gif' style='border-width:0px;' />";
    document.getElementById('blurDiv').appendChild(spanTag);
    
    var tgCtl = Sys.UI.DomElement.getLocation(element);
    var progressBounds = Sys.UI.DomElement.getBounds(document.getElementById('imgSpan'));
    var x = document.body.scrollWidth / 2; //center of the screen
    var y = tgCtl.y - (progressBounds.height * 2); //just above the postback control
    Sys.UI.DomElement.setLocation(spanTag, parseInt(x), parseInt(y));
    return true;
}

function enableEntirePage()
{
    var blurDiv = document.getElementById("blurDiv");
    blurDiv.parentNode.removeChild(blurDiv); 
    return true;   
}

function disableEntirePage2(element)
{
    var blurDiv = document.createElement("div");
    blurDiv.id = "blurDiv";    
    //blurDiv.style.cssText = "position:absolute; top:0; right:0; text-align: center; vertical-align: bottom; width:" + document.body.scrollWidth + "px; height:" + document.body.scrollHeight + "px; font-size: 24px; font-family: verdana; color:#c0c0c0; background-color: Gray; opacity: 0.8; filter:alpha(opacity=80)";
    blurDiv.style.cssText = "position:fixed; top:0; right:0; left:0; bottom:0; text-align: center; vertical-align: bottom; font-size: 24px; font-family: verdana; color:#c0c0c0; background-color: Gray; opacity: 0.8; filter:alpha(opacity=80)";
    document.getElementsByTagName("body")[0].appendChild(blurDiv);
    blurDiv.setAttribute("align","center");
    
    var spanTag = document.createElement("span");
    spanTag.id = "imgSpan";
    spanTag.style.cssText = "color: Navy; margin:3px; vertical-align: bottom; font:bold 12px Arial, Helvetica, sans-serif;";
    spanTag.innerHTML = "<img src='../Images/progress.gif' style='border-width:0px;' />";
    document.getElementById('blurDiv').appendChild(spanTag);
    
    var tgCtl = Sys.UI.DomElement.getLocation(element);
    var progressBounds = Sys.UI.DomElement.getBounds(document.getElementById('imgSpan'));
    var x = document.body.scrollWidth / 2; //center of the screen
    var y = tgCtl.y - (progressBounds.height * 2); //just above the postback control
    Sys.UI.DomElement.setLocation(spanTag, parseInt(x), parseInt(y));
    return true;
}

//function showKioskKeyboard(app, ctlId) {
//  //WshShell = new ActiveXObject("WScript.Shell");
  //WshShell.Run (app,0,false);
  //document.getElementById(ctlId).focus();
//}
//disable the freetexbox content
/*function FreeTextboxDesignAreaEnableDisable(FreeTextBoxID, ReadOnly)
{
    var designFrame = document.getElementById(FreeTextBoxID);
    //Get the document of that iframe
    var doc = designFrame.contentDocument;
    if (doc == undefined || doc == null )
       doc = freetextboxDesignFrame.contentWindow.document;
    //Disable the Document Body
    doc.body.disabled = ReadOnly;
    //Make the Content Not Editable
    doc.activeElement.contentEditable = ReadOnly == true ? false : true ;    
}*/

//----disable Right-Click on browser---
/*var message="Sorry, right-click has been disabled";
function clickIE() {if (document.all) {(message);return false;}}
function clickNS(e) {if
(document.layers||(document.getElementById&&!document.all)) {
if (e.which==2||e.which==3) {(message);return false;}}}
if (document.layers)
{document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}
document.oncontextmenu=new Function("return false")*/
//-------------------------------------

function chkDate_Changed(chkCtl, trDate, trTime)
{
    if(chkCtl.checked == true)
    {
        document.getElementById(trDate).style.display='';
        document.getElementById(trTime).style.display='';
    }
    else
    {
        document.getElementById(trDate).style.display='none';
        document.getElementById(trTime).style.display='none';        
    }
}

//-----------Encryption/Dencryption-------------
var pwd ="iFbsJsEnDe009%$#"
function encrypt(str) 
{
    if(pwd == null || pwd.length <= 0) 
    {
        alert("Please enter a password with which to encrypt the message.");
        return null;
    }
    var prand = "";
    for(var i=0; i<pwd.length; i++) 
    {
        prand += pwd.charCodeAt(i).toString();
    }
    var sPos = Math.floor(prand.length / 5);
    var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));
    var incr = Math.ceil(pwd.length / 2);
    var modu = Math.pow(2, 31) - 1;
    if(mult < 2) 
    {
        alert("Algorithm cannot find a suitable hash. Please choose a different password. \nPossible considerations are to choose a more complex or longer password.");
        return null;
    }
    var salt = Math.round(Math.random() * 1000000000) % 100000000;
    prand += salt;
    while(prand.length > 10) 
    {
        prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
    }
    prand = (mult * prand + incr) % modu;
    var enc_chr = "";
    var enc_str = "";
    for(var i=0; i<str.length; i++) 
    {
        enc_chr = parseInt(str.charCodeAt(i) ^ Math.floor((prand / modu) * 255));
        if(enc_chr < 16) 
        {
            enc_str += "0" + enc_chr.toString(16);
        } 
        else enc_str += enc_chr.toString(16);
        prand = (mult * prand + incr) % modu;
    }
    salt = salt.toString(16);
    while(salt.length < 8)salt = "0" + salt;
    enc_str += salt;
    return enc_str;
}

function decrypt(str) 
{
    if(str == null || str.length < 8) 
    {
        alert("A salt value could not be extracted from the encrypted message because it's length is too short. The message cannot be decrypted.");
        return;
    }
    if(pwd == null || pwd.length <= 0) 
    {
        alert("Please enter a password with which to decrypt the message.");
        return;
    }
    var prand = "";
    for(var i=0; i<pwd.length; i++) 
    {
        prand += pwd.charCodeAt(i).toString();
    }
    var sPos = Math.floor(prand.length / 5);
    var mult = parseInt(prand.charAt(sPos) + prand.charAt(sPos*2) + prand.charAt(sPos*3) + prand.charAt(sPos*4) + prand.charAt(sPos*5));
    var incr = Math.round(pwd.length / 2);
    var modu = Math.pow(2, 31) - 1;
    var salt = parseInt(str.substring(str.length - 8, str.length), 16);
    str = str.substring(0, str.length - 8);
    prand += salt;
    while(prand.length > 10) 
    {
        prand = (parseInt(prand.substring(0, 10)) + parseInt(prand.substring(10, prand.length))).toString();
    }
    prand = (mult * prand + incr) % modu;
    var enc_chr = "";
    var enc_str = "";
    for(var i=0; i<str.length; i+=2) 
    {
        enc_chr = parseInt(parseInt(str.substring(i, i+2), 16) ^ Math.floor((prand / modu) * 255));
        enc_str += String.fromCharCode(enc_chr);
        prand = (mult * prand + incr) % modu;
    }
    return enc_str;
}
//--------------end of Encryption---------------

//--------------get QueryString-----------------
function getQueryStrings() 
{
    var argList = new Object();

    if(window.location != null && window.location.search.length > 1) {
        var urlParms = window.location.search.substring(1);
        var argPairs = urlParms.split('&');

        for(var i = 0; i < argPairs.length; i++) {
            var pos = argPairs[i].indexOf('=')

            if(pos == -1)
                continue;
            else {
                var argName = argPairs[i].substring(0, pos);
                var argVal = argPairs[i].substring(pos + 1);

                if(argVal.indexOf('+') != -1)
                    argVal = argVal.replace(/\+/g, ' ');

                argList[argName] = unescape(argVal);
            }
        }
    }    
    return argList;
}
//--------------end of QueryString--------------


function checkForHTMLTags() {
    var rtnbool = true;
    var elems = document.getElementsByTagName('input');
    var elemval;
    if ((typeof (elems) != "undefined") && (elems != null)) {
        for (var i = 0; i < elems.length; i++) {
            if (elems[i].type == "text") {
                elemval = elems[i].value.toUpperCase().trim();
                if (elemval != null && elemval != "" && elemval.length > 1) {
                    if (elemval.match("<\[/a-zA-Z]{1,}>*") == null) {
                        return true;
                    }
                    alert("Sorry, Please remove the HTML tags (< />) and retry your last action.");
                    return false;
                }
            }
        }
    }
    return rtnbool;
}

function ClearAllTextFields() {
    var rtnbool = true;
    var elems = document.getElementsByTagName('input');
    if ((typeof (elems) != "undefined") && (elems != null)) {
        for (var i = 0; i < elems.length; i++) {
            if (elems[i].type == "text") {
                elems[i].value = "";
            }
        }
    }
}

