﻿/*---------------It Prevents a request to server before ending a previous request-----------------*/
var prm;
var onClickLoadModal = true;
var zoomIndex = 0;
var PageIndex = 0;
var FamilyIndex = 0;
var PersistZoomIndex = 0;
var time;
function Load() {
    if (Sys != null) {
        prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_initializeRequest(initializeRequest);
        prm.add_endRequest(endRequest);
    }

    placeFocus();
}

//Used to fired the modal progress behavior
function SuscribeToRequestEvent() {
    if (Sys != null) {
        prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_beginRequest(beginReq);
        prm.add_endRequest(endReq);
    }
}

function initializeRequest(sender, args) {
    document.body.style.cursor = "wait";
    if (prm.get_isInAsyncPostBack()) {
        args.set_cancel(true);
    }
}

function endRequest(sender, args) {
    document.body.style.cursor = "default";
}
/*--------------------------------------------------------------------------------*/
//This is used to ConfirmDelete message
function ConfirmDelete(msg) {

    if (confirm(msg))
        return true;
    else
        return false;
}

//This is used to allow writing just of numeric values
function CheckNumericValue(e) {
    BrowserDetect.init();

    var key;
    key = e.which ? e.which : e.keyCode;

    if (BrowserDetect.browser == "Firefox" || BrowserDetect.browser == "Opera") {
        if (e.keyCode) {
            if ((key == 37) || (key == 38) || (key == 39) || (key == 40) || (key == 9) || (key == 13) || (key == 8))//Mozilla (left,up,right,down,tab,enter,backspace)
                return true;
        }
    }

    if (key == 13)
        return true;

    if ((key < 48 || key > 57)) //only numeric keys
        return false;
}

//This is used to allow writing decimal values
function CheckDecimalValue(control, e) {
    var key;
    key = e.which ? e.which : e.keyCode;

    BrowserDetect.init();

    if (BrowserDetect.browser == "Firefox" || BrowserDetect.browser == "Opera") {
        if (e.keyCode) {
            if ((key == 37) || (key == 38) || (key == 39) || (key == 40) || (key == 9) || (key == 13) || (key == 8))//Mozilla (left,up,right,down,tab,enter,backspace)
                return true;
        }
    }

    if ((key < 48 || key > 57) && (key != 46)) //only numeric keys, (.)
    {
        return false;
    }
    if (key == 46) //period key
    {
        if (control.value != "") {
            if (control.value.indexOf('.') != -1)//Already exists a period in the string
                return false;
        }
        else
            return false;
    }
}

//This is used to put zero in a textbox when the user left it empty
function checkTextFieldOnZero(txt) {
    if (txt) {
        if (txt.value == "") {
            txt.value = "1";
            txt.select();
        }
    }
    return true;
}

//This is used to remove spaces from text fields
//Left and Right
//Ascii 32 = space 
//Ascii 9 = Tab
function removeSpaces(txt) {
    var str = txt.value;
    //ltrim
    while (str.charCodeAt(0) == 32 || str.charCodeAt(0) == 9)
        str = str.substring(1);
    //rtrim
    while (str.charCodeAt(str.length - 1) == 32 || str.charCodeAt(str.length - 1) == 9)
        str = str.substring(0, str.length - 1);
    txt.value = str;
}

//Tis used to display the Item Cross Reference Information
function DisplayCrossRefInfo(callback) {
    var items = new Array();
    items = callback.split("|@#"); //item separator        

    for (var i = 1; i < items.length; i++)//set every label
    {
        var item = new Array();
        item = items[i].split("@#!"); //controlID - value separator

        var id = item[0];
        var value = item[1];

        var control = document.getElementById(id);
        control.innerHTML = value; //set the value to the label
    }

    Show(items[0]); //display the Panel
}

//This is used to display any hidden control
function Show(id) {
    var control = document.getElementById(id);
    if (control != null) {
        control.style.visibility = 'visible';
    }
}

function ValidatePageError(lblErrors, group) {

    // Do nothing if client validation is not active
    if (typeof (Page_Validators) != "undefined") {
        Page_ClientValidate(group);
        if (!Page_IsValid) {
            // There are fields on the page that are invalid.
            HideAtAll(lblErrors);
        }
    }
}

function HideAtAll(id) {
    var control = document.getElementById(id);
    if (control != null) {
        control.style.display = 'none';
    }
}
//This is used to Hide any control
function Hide(id) {
    var control = document.getElementById(id);
    if (control != null) {
        control.style.visibility = 'hidden';
    }
}

//This function replace all the 'regExpression' for the replaceString in the 'content' string
function replaceAll(content, regExpression, replaceString) {
    while (content.toString().indexOf(regExpression) != -1) {
        content = content.toString().replace(regExpression, replaceString);
    }
    return content;
}

function PrintFriendly(styleSheetUrl, printRegionID, pageTitle, printButtonText) {
    var disp_setting = "toolbar=no,location=no,directories=no,menubar=no,";
    disp_setting += "scrollbars=yes,width=750, height=600, left=100, top=25";
    var content_vlue = document.getElementById(printRegionID).innerHTML;
    var docprint = window.open("", "", disp_setting);

    content_vlue = replaceAll(content_vlue, "NormalDisplay", "PrintFriendlyDisplay");
    content_vlue = replaceAll(content_vlue, "HideOnLoad", "NormalDisplay");
    content_vlue = replaceAll(content_vlue, "ScrollArea", "");
    content_vlue = replaceAll(content_vlue, "ButtonPrint", "PrintFriendlyDisplay");

    docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
    docprint.document.write('<html xmlns="http://www.w3.org/1999/xhtml" >');
    docprint.document.write('<head runat="server"><title>');
    docprint.document.write(pageTitle);
    docprint.document.write('</title>');
    docprint.document.write('<link href="' + styleSheetUrl + '" rel="stylesheet" type="text/css" />');
    docprint.document.write('</head><body class="PrintFriendlyBody">');
    docprint.document.write('<table width="100%">');
    docprint.document.write('<tr><td align="right">');
    docprint.document.write('<INPUT class="Button" type="button" value="');
    docprint.document.write(printButtonText);
    docprint.document.write('" onclick="self.print();" />');
    docprint.document.write('</td></tr>');
    docprint.document.write('</table>');
    docprint.document.write(content_vlue);
    docprint.document.write('<table width="100%"');
    docprint.document.write('<tr><td align="right">');
    docprint.document.write('<br /><INPUT class="Button" type="button" value="');
    docprint.document.write(printButtonText);
    docprint.document.write('" onclick="self.print();" />');
    docprint.document.write('</td></tr></table>');
    docprint.document.write('</body></html>');
    docprint.document.close();
    docprint.focus();
}

//Updates value to the checkState input parameter, for each row
function ChangeCheckBoxState(id, checkStatus) {
    var chk = document.getElementById(id);
    if (chk != null)
        chk.checked = checkStatus;
}

// Toggles through all of the checkboxes defined in the CheckBoxIDs array
// and updates their value to the checkState input parameter
function ChangeAllCheckBoxStates(gridID, checkStatus) {
    var gridViewCtl = document.getElementById(gridID);

    //get the input type controls in the gridview (checkbox) 
    var CheckBoxs = gridViewCtl.getElementsByTagName("input");

    // Toggles through all of the checkboxes defined in the CheckBoxIDs array
    // and updates their value to the checkState input parameter
    if (CheckBoxs != null) {
        for (var i = 0; i < CheckBoxs.length; i++) {
            //only for "checkbox" type
            if (CheckBoxs[i].type == "checkbox")
                ChangeCheckBoxState(CheckBoxs[i].id, checkStatus);
        }
    }
}

// Whenever a checkbox in the GridView is toggled, we need to
// check the Header checkbox if ALL of the GridView checkboxes are
// checked, and uncheck it otherwise
function ChangeHeaderAsNeeded(gridID) {
    var gridViewCtl = document.getElementById(gridID);

    //get the input type controls in the gridview (checkbox) 
    var CheckBoxs = gridViewCtl.getElementsByTagName("input");

    if (CheckBoxs != null) {
        // check to see if all other checkboxes are checked
        for (var i = 1; i < CheckBoxs.length; i++) {
            if (CheckBoxs[i].type == "checkbox")//only for "checkbox" type
            {
                var chk = document.getElementById(CheckBoxs[i].id);
                if (!chk.checked) {
                    // Whoops, there is an unchecked checkbox, make sure
                    // that the header checkbox is unchecked
                    ChangeCheckBoxState(CheckBoxs[0].id, false);
                    return;
                }
            }
        }

        // If we reach here, ALL GridView checkboxes are checked
        ChangeCheckBoxState(CheckBoxs[0].id, true);
    }
}


function triggerFileUpload(File) {
    document.getElementById(File).click();
}

function setHiddenValue(File, Hidden) {
    document.getElementById(Hidden).value = document.getElementById(File).value;
}


var navigate = false;
//This is used to avoid the browser back button navigation
function Unloaded() {
    if (navigate == false) {
        location.replace(self.location)
    }
    navigate = false;
}

//This is used to define when the browser should navigate (browser back button navigation)
var triggerControl;
function SetNavigation(e) {
    e = e || window.event;
    triggerControl = e.target || e.srcElement;
    if (triggerControl) {
        if (triggerControl.tagName == "A" || triggerControl.tagName == "IMG" ||
	        (triggerControl.tagName == "INPUT" && (triggerControl.type == "submit" || triggerControl.type == "button") || triggerControl.type == "image"))
            navigate = true;
    }
    else {
        //No browser management - Do not Stop browser back Button
        navigate = true;
    }
}

function beginReq(sender, args) {
    var control = args._postBackElement;
    BrowserDetect.init();
    if (BrowserDetect.browser == "Explorer") {
        //validate when premier button have a child (only when set UseSubmitBehavior="false")
        if (control.all[0]) {
            control = control.all[0];
        }
    }

    if (control) {
        if (control.tagName == "INPUT" && (control.type == "submit" || control.type == "button")) {
            var matchControl = control.id.search("wucAddToCartAsyncProcess");
            //if control match do not show popup
            if (matchControl == -1) {
                // show popup
                if (onClickLoadModal)
                    $find(ModalProgress).show();
                else
                    onClickLoadModal = true;
            }
        }
    }
}
function endReq(sender, args) {
    if (triggerControl) {
        if (triggerControl.tagName == "INPUT" && (triggerControl.type == "submit" || triggerControl.type == "button")) {
            //  hide popup
            $find(ModalProgress).hide();
        }
    }
    //validate if error occurred in updatePanel
    //    if (args.get_error() != undefined) {
    //        args.set_errorHandled(true);
    //        window.location = ResolveUrl("~/") + "ErrorPage.aspx";
    //    }
}


function ResolveUrl(url) {
    if (url.indexOf("~/") == 0) {
        url = baseUrl + url.substring(2);
    }
    return url;
}

/************** Set control focus ****************/
var controlID;
function placeFocus() {
    if (document.forms.length > 0) {
        var field = document.forms[0];
        for (i = 0; i < field.length; i++) {
            //validate when type is undefined
            var element = field.elements[i];
            if (element.type != undefined) {
                //validate when type is text
                if ((element.type == 'text' || element.type == 'password') && !element.readOnly && !element.disabled) {
                    controlID = document.forms[0].elements[i].id;
                    if (controlID != 'ctl00_txtSearch') {
                        window.setTimeout(focus, 0);
                        break;
                    }
                }
            }
        }
    }
}

function focus() {
    try {
        document.getElementById(controlID).focus();
    }
    catch (err) {
        //Handle errors
    }
}
/**************************************************/

//Used to check any control with "checked" property
function CheckControl(controlID) {
    control = document.getElementById(controlID);
    if (control != null)
        control.checked = true;
}


///////////////////////////////////////////////////////////////
//Used to round a numeric texbox
function RoundNumber(control, decimals) {
    var newString; // The new rounded number
    decimals = Number(decimals);
    if (decimals < 1) {
        newString = (Math.round(control.value)).toString();
    }
    else {
        var numString = control.value.toString();
        if (numString.lastIndexOf(".") == -1)// If there is no decimal point 
        {
            numString += "."; // give it one at the end
        }
        var cutoff = numString.lastIndexOf(".") + decimals; // The point at which to truncate the number
        var d1 = Number(numString.substring(cutoff, cutoff + 1)); // The value of the last decimal place that we'll end up with
        var d2 = Number(numString.substring(cutoff + 1, cutoff + 2)); // The next decimal, after the last one we want
        if (d2 >= 5) // Do we need to round up at all? If not, the string will just be truncated
        {
            if (d1 == 9 && cutoff > 0) // If the last digit is 9, find a new cutoff point
            {
                while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
                    if (d1 != ".") {
                        cutoff -= 1;
                        d1 = Number(numString.substring(cutoff, cutoff + 1));
                    } else {
                        cutoff -= 1;
                    }
                }
            }
            d1 += 1;
        }
        if (d1 == 10) {
            numString = numString.substring(0, numString.lastIndexOf("."));
            var roundedNum = Number(numString) + 1;
            newString = roundedNum.toString() + '.';
        } else {
            newString = numString.substring(0, cutoff) + d1.toString();
        }
    }
    if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
        newString += ".";
    }
    var decs = (newString.substring(newString.lastIndexOf(".") + 1)).length;
    for (var i = 0; i < decimals - decs; i++)
        newString += "0";

    control.value = newString; // Output the result to the form field (change for your purposes)
}

////////////////Region: Fire Progress behavior for Wizards/////////////////////////

var wizardControlID;
var divModalProgressId;

//Used to fired the modal progress behavior
function SuscribeToWizardRequestEvent(wizardID, divModalId) {
    if (Sys != null) {
        prm = Sys.WebForms.PageRequestManager.getInstance();
        wizardControlID = wizardID;
        divModalProgressId = divModalId;
        prm.add_beginRequest(beginWizardReq);
        prm.add_endRequest(endWizardReq);
    }
}

//Fired when the user begin a request into the wizard
//Show the modalP progress
function beginWizardReq(sender, args) {
    if (args._postBackElement.tagName == "INPUT" && (args._postBackElement.type == "submit" || args._postBackElement.type == "button")) {
        // get the update progress div
        var updateProgressDiv = $get(divModalProgressId);
        // make it visible
        updateProgressDiv.style.display = '';

        //  get the wizard element        
        var wizard = $get(wizardControlID);

        // get the bounds of both the wizard
        var wizardBounds = Sys.UI.DomElement.getBounds(wizard);

        //set the div size according to wizard size
        updateProgressDiv.style.width = wizardBounds.width + "px";
        updateProgressDiv.style.height = wizardBounds.height + "px";

        //get the progress image to center it in the DIV
        var images = updateProgressDiv.getElementsByTagName('img');
        if (images) {
            //assume that there is only one image (use the first)
            var imageBounds = Sys.UI.DomElement.getBounds(images[0]);

            var xImage = Math.round((wizardBounds.width / 2) - (imageBounds.width / 2));
            var yImage = Math.round((wizardBounds.height / 2) - (imageBounds.height / 2));

            //	set the image element to this position
            Sys.UI.DomElement.setLocation(images[0], xImage, yImage);
        }

        //	set the progress element to this position
        Sys.UI.DomElement.setLocation(updateProgressDiv, wizardBounds.x, wizardBounds.y);
        // show popup
    }
}

//Fired when it has a wizard response
//Hide the modal progress
function endWizardReq(sender, args) {
    // get the update progress div
    var updateProgressDiv = $get(divModalProgressId);
    // make it invisible
    updateProgressDiv.style.display = 'none';
}

////////////////EngRegion: Fire Progress behavior for Wizards//////////////////////

function HideControls(check, gvItems, control) {
    if (document.getElementById(check) != null) {
        var ShowCrossRef = document.getElementById(check).checked;
    } else {
        return;
    }
    var grid = document.getElementById(gvItems);
    if (grid != null) {
        var controlList = grid.getElementsByTagName('div');

        var i = 0;

        var bDisplayCrossRef;

        if (ShowCrossRef == 'False') {
            bDisplayCrossRef = false;
        }
        else if (ShowCrossRef == 'True') {
            bDisplayCrossRef = true;
        }
        else {
            bDisplayCrossRef = ShowCrossRef;
        }

        while (true) {
            if (controlList[i] != null) {
                var parts = controlList[i].id.split("_");
                if (parts[parts.length - 1] == control) {
                    if (bDisplayCrossRef) {

                        controlList[i].style.display = 'block';
                    }
                    else {
                        controlList[i].style.display = 'none';
                    }
                }
            }
            else {
                return;
            }
            i++;
        }
    }
}


//Use this function to fire the default button.
//This function validate the Enter key to execute the action
function FireButton(e) {
    var key = e.which ? e.which : e.keyCode;
    if (key == 13) {
        var defaultButton = GetDefaultButton();
        if (defaultButton)
            defaultButton.click();
    }
}

//this function look for the first button with submit behavior
//and return the control
function GetDefaultButton() {
    var buttonList = document.getElementsByTagName('input');
    if (buttonList) {
        for (i = 0; i < buttonList.length; i++) {
            if (buttonList[i].type == "submit")
                return buttonList[i];
        }
    }
}


// 0 parameter  = ClientId of the loading Image
// 1 parameter  = ClientId of the lblPrice
// 2 parameter  = Price
// 3 parameter  = ClientId of the lblCurrencyCode
// 4 parameter  = currencyCode

// 5 parameter  = ClientId of the lblBasePrice
// 6 parameter  = basePrice
// 7 parameter  = ClientId of the lblSaving
// 8 parameter  = saving
// 9 parameter  = ClientId of the lblYourPriceTitle
// 10 parameter = ClientId of the lblBasePriceTitle
// 11 parameter = ClientId of the lblSavingTitle
// 12 parameter = ClientId of the lblPriceTitle

// 13 parameter = ClientId of the lblBasePriceCurrencyCode
// 14 parameter = ClientId of the lblSavingCurrencyCode
function DisplayPrices(callback) {
    var items = new Array();
    items = callback.split("|"); //item separator

    var img = document.getElementById(items[0]);
    if (img == null) {
        return; //the wuc is hidden    
    }
    img.style.display = 'none';

    var lblPrice = document.getElementById(items[1]);
    lblPrice.innerHTML = items[2];

    var lblCurrencyCode = document.getElementById(items[3]);
    lblCurrencyCode.innerHTML = items[4];

    if (items[5]) { //displayOnlyUnitPrice = null

        if (items[8] != "") {

            var lblBasePrice = document.getElementById(items[5]);
            lblBasePrice.innerHTML = items[6];

            var lblSaving = document.getElementById(items[7]);
            lblSaving.innerHTML = items[8];

            var lblYourPriceTitle = document.getElementById(items[9]);
            lblYourPriceTitle.style.display = 'inline';
            var lblBasePriceTitle = document.getElementById(items[10]);
            lblBasePriceTitle.style.display = 'inline';
            var lblSavingTitle = document.getElementById(items[11]);
            lblSavingTitle.style.display = 'inline';

            var lblBasePriceCurrencyCode = document.getElementById(items[13]);
            lblBasePriceCurrencyCode.style.display = 'inline';
            lblBasePriceCurrencyCode.innerHTML = items[4];

            var lblSavingCurrencyCode = document.getElementById(items[14]);
            lblSavingCurrencyCode.style.display = 'inline';
            lblSavingCurrencyCode.innerHTML = items[4];


        } else {
            var lblPriceTitle = document.getElementById(items[12]);
            lblPriceTitle.style.display = 'inline';
        }
    }
}

//Set focus to Control
function CheckTab(e, controlID) {
    var key = e.which ? e.which : e.keyCode;
    if (key == 9) //Tab key
    {
        var txt = document.getElementById(controlID);
        if (txt.disabled == false && txt.style.display != 'none') {
            txt.focus();
            if (txt.type != 'select-one') {
                txt.select();
            }
            return false; //Avoid browser normal tab navigation
        }
        else//Validate control enabled/disabled status
        {//Look for the next enabled control
            if (txt.form) {
                var controlIndex = 0;
                for (var i = 0; i < txt.form.elements.length; i++) {
                    if (txt == txt.form.elements[i]) {
                        controlIndex = i;
                        break;
                    }
                }
                while (controlIndex <= txt.form.elements.length) {
                    controlIndex = controlIndex + 1;
                    if (txt.form.elements[controlIndex].type == 'text' || txt.form.elements[controlIndex].type == 'submit'
                        || txt.form.elements[controlIndex].type == 'button' || txt.form.elements[controlIndex].type == 'select-one'
                        || txt.form.elements[controlIndex].type == 'radio') {
                        if (txt.form.elements[controlIndex].disabled == false) {
                            txt.form.elements[controlIndex].focus();
                            if (txt.form.elements[controlIndex].type != 'select-one') {
                                txt.form.elements[controlIndex].select();
                            }
                            return false;
                        }
                    }
                }
            }
        }
    }
}

// parameter = txtCity
// parameter = City value
// parameter = ddlState
// parameter = State value
// parameter = chkIsLocationOverride
// parameter = Is Dry State
function ValidateZipCode(callback) {
    if (callback != "") {
        var items = new Array();
        items = callback.split("|"); //item separator

        var txtCity = document.getElementById(items[0]);
        if (txtCity.value == "") {
            txtCity.value = items[1];
            //Raise on change event
            var jqIDtxtCity = '#' + items[0];
            $(jqIDtxtCity).change();
        }

        var ddlState = document.getElementById(items[2]);
        if (ddlState.value == "") {
            ddlState.value = items[3];
            //Raise on change event
            var jqIDddlState = '#' + items[2];
            $(jqIDddlState).change();
        }

        if (items[5] != null) { //Is Dry State value
            var chk = document.getElementById(items[4]);
            if (items[5] == "1") //is dryState
            {
                if (chk.parentElement.tagName == "SPAN")
                    chk.parentElement.disabled = false;
                chk.disabled = false;
            }
            else//is not dryState
            {
                chk.checked = false;
                if (chk.parentElement.tagName == "SPAN")
                    chk.parentElement.disabled = true;
                chk.disabled = true;
            }
        }
    }
}

//Class used to identify the current Browser.
//Validate BrowserDetect.browser against dataBrowser[].identity
var BrowserDetect =
{
    //Fire the browser search
    init: function() {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
    },
    //Look for the browser identity for the defined browser array (dataBrowser)
    searchString: function(data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    //Validated browser array
    dataBrowser:
	[
		{
		    string: navigator.userAgent,
		    subString: "Chrome",
		    identity: "Chrome"
		},
		{ string: navigator.userAgent,
		    subString: "OmniWeb",
		    versionSearch: "OmniWeb/",
		    identity: "OmniWeb"
		},
		{
		    string: navigator.vendor,
		    subString: "Apple",
		    identity: "Safari",
		    versionSearch: "Version"
		},
		{
		    prop: window.opera,
		    identity: "Opera"
		},
		{
		    string: navigator.vendor,
		    subString: "iCab",
		    identity: "iCab"
		},
		{
		    string: navigator.vendor,
		    subString: "KDE",
		    identity: "Konqueror"
		},
		{
		    string: navigator.userAgent,
		    subString: "Firefox",
		    identity: "Firefox"
		},
		{
		    string: navigator.vendor,
		    subString: "Camino",
		    identity: "Camino"
		},
		{		// for newer Netscapes (6+)
		    string: navigator.userAgent,
		    subString: "Netscape",
		    identity: "Netscape"
		},
		{
		    string: navigator.userAgent,
		    subString: "MSIE",
		    identity: "Explorer",
		    versionSearch: "MSIE"
		},
		{
		    string: navigator.userAgent,
		    subString: "Gecko",
		    identity: "Mozilla",
		    versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
		    string: navigator.userAgent,
		    subString: "Mozilla",
		    identity: "Netscape",
		    versionSearch: "Mozilla"
		}
	]
};


//This function validate the Maxlength Texbox
function checkMaxLength(textBox, e, length) {
    // Allow non-printing, arrow and delete keys
    var key = window.event ? e.keyCode : e.which;
    var isPermittedKeystroke = ((key < 32) || (key >= 33 && key <= 40) || (key == 46))
    // Decide whether the keystroke is allowed to proceed
    if (!isPermittedKeystroke) {
        var maxLength = parseInt(length);
        // Force a trim of the textarea contents if necessary
        if (textBox.value.length > maxLength - 1) {
            textBox.value = textBox.value.substring(0, maxLength);
            e.returnValue = false;
        }
    }
}
function checkMaxLengthPaste(textBox, e, length) {
    var pasteData = window.clipboardData.getData("Text");
    var maxLength = parseInt(length);
    var txtstring = textBox.value + pasteData;
    // Force a trim of the textarea contents if necessary
    if (txtstring.length > maxLength) {
        textBox.value = txtstring.substring(0, maxLength);
        e.returnValue = false;
    }
}

//This function disable Location Override check if the State is Dry
function DryStateValidation(callback) {
    var items = new Array();
    items = callback.split("|"); //item separator  

    var chk = document.getElementById(items[0]);
    var isDryState = items[1];

    //enabled or disabled checkbox according with the selected dryState
    if (isDryState == "1") //is dryState
    {
        if (chk.parentElement.tagName == "SPAN")
            chk.parentElement.disabled = false;
        chk.disabled = false;
    }
    else//is not dryState 
    {
        chk.checked = false;
        if (chk.parentElement.tagName == "SPAN")
            chk.parentElement.disabled = true;
        chk.disabled = true;
    }
}

//Use to reload page (GET method)
function ReloadPage() {
    window.location = window.location;
    return false; //Avoid POST of buttons
}

//Use for load the description in New Cross Reference
function DisplayDescription(callback) {
    var controls = new Array();
    controls = callback.split('|');

    var lblDesc = document.getElementById(controls[0]);
    var value = controls[1];

    var lblDesc2 = document.getElementById(controls[2]);
    var value2 = controls[3];

    if (lblDesc != null) {
        try {
            lblDesc.value = value;
        }
        catch (exception) {
            lblDesc.innerHTML = value;
        }
    }
    if (lblDesc2 != null) {
        try {
            lblDesc2.value = value2;
        }
        catch (exception) {
            lblDesc2.innerHTML = value2;
        }
    }
}
/*********************************************  Scripts for Gallery Control ****************************************/
function setImageOnView(ImageUrl, imageViewMed, imageLargeUrl, index) {
    var imageView = document.getElementById(imageViewMed);
    var imageViewZoom = document.getElementById(imageViewName);
    imageView.src = ImageUrl;
    imageViewZoom.src = imageLargeUrl;
    zoomIndex = parseInt(index) + parseInt(PageIndex);
}

function SetZoom() {
    var imageView = document.getElementById(imageViewName);
    var urls = UrlArrays.split('|');
    imageView.src = urls[zoomIndex];
    PersistZoomIndex = zoomIndex;
    $find(ModalZoom).show();
}

function ShowZoom(index) {
    var imageView = document.getElementById(imageViewName);
    var urls = UrlArrays.split('|');
    imageView.src = urls[(parseInt(index) + parseInt(PageIndex))];
    zoomIndex = (parseInt(index) + parseInt(PageIndex));
    PersistZoomIndex = zoomIndex;
    $find(ModalZoom).show();
}

function dummyTimeOut() {
    setTimeout('HideZoom()', 0);
}
function HideZoom() {
    zoomIndex = PersistZoomIndex;
    $find(ModalZoom).hide();
}

function NextZoom_event() {
    if ((parseInt(zoomIndex) + 1) < parseInt(imageCount)) {
        zoomIndex++;
    } else { zoomIndex = 0; }
    var imageView = document.getElementById(imageViewName);
    var urls = UrlArrays.split('|');
    imageView.src = urls[zoomIndex];
}
function PreviousZoom_event() {
    if ((parseInt(zoomIndex) - 1) >= 0) {
        zoomIndex--;
    }
    else { zoomIndex = parseInt(imageCount) - 1; }

    var imageView = document.getElementById(imageViewName);
    var urls = UrlArrays.split('|');
    imageView.src = urls[zoomIndex];
}

function NextIndex() {
    PageIndex = parseInt(PageIndex) + 1
    zoomIndex = PageIndex;
}
function PreviousIndex() {
    PageIndex = parseInt(PageIndex) - 1
    zoomIndex = PageIndex;
}
/**************************************  Family images ****************************/
function NextFamilyImage() {
    if (time != null)
        clearTimeout(time);
    if ((parseInt(FamilyIndex) + 1) < parseInt(imageCount)) {
        FamilyIndex++;
    } else { FamilyIndex = 0; }
    var imageView = document.getElementById(imageViewName);
    var urls = UrlArrays.split('|');
    imageView.src = urls[FamilyIndex];
    transparency = 0;
    time = setTimeout('NextFamilyImage()', 60000);

}
function PreviousFamilyImage() {
    if (time != null)
        clearTimeout(time);
    if ((parseInt(FamilyIndex) - 1) >= 0) {
        FamilyIndex--;
    }
    else { FamilyIndex = parseInt(imageCount) - 1; }

    var imageView = document.getElementById(imageViewName);
    var urls = UrlArrays.split('|');
    imageView.src = urls[FamilyIndex];
    time = setTimeout('NextFamilyImage()', 60000);
}

/*********************************** End Family images ****************************/

/*********************************** PayPal Express Checkout ****************************/

function RedirectAfterAsync(url) {
    $find(ModalProgress).hide();
    window.location.href = ResolveUrl(url);
}

/*********************************** End PayPal Express Checkout ****************************/


/*******************************************   End scripts Gallery Control  *******************************************/

/*********************************** Social Network Share custom buttons ****************************/
function mailpage(Url, Title, body, subject, showLink) {
    mail_str = "mailto:?subject=" + subject + Title;
    mail_str += "&body= " + body + Title + ". ";
    mail_str += showLink + Url;
    location.href = mail_str;
}
function OpenModal(URL) {
    window.open(URL, "Share", "location=1,status=1,toolbar=0,menubar=0,location=0,scrollbars=1,width=700,height=500");
}
/*********************************** End Social Network Share custom buttons ****************************/


function TotalQuantity() {
    var add = 0;
    $(".QuantityTextBox").each(function() {
        add += Number($(this).val());
    });
    $(".QuantitySummarized").val(add);
}

//Function used to copy the address information from BillTo to ShipTo. Used in Payment.aspx
function IsShipToSameAsBillTo(chkShipToAsBillTo) {
    var firstName = $('.FirstName');
    var lastName = $('.LastName');
    var addressLine1 = $('.Add1');
    var addressLine2 = $('.Add2');
    var city = $('.City');
    var zipCode = $('.ZipCode');
    var state = $('.State');
    var company = $('.Company');

    if (chkShipToAsBillTo.checked) {

        if (company.length > 0) {
            company[1].value = company[0].value;
            company[1].disabled = 'disabled';
            company.bind('blur', function() {
                company[1].value = company[0].value;
            });
        }

        firstName[1].value = firstName[0].value;
        firstName[1].disabled = 'disabled';
        firstName.bind('blur', function() {
            firstName[1].value = firstName[0].value;
        });

        lastName[1].value = lastName[0].value;
        lastName[1].disabled = 'disabled';
        lastName.bind('blur', function() {
            lastName[1].value = lastName[0].value;
        });

        addressLine1[1].value = addressLine1[0].value;
        addressLine1[1].disabled = 'disabled';
        addressLine1.bind('blur', function() {
            addressLine1[1].value = addressLine1[0].value;
        });

        addressLine2[1].value = addressLine2[0].value;
        addressLine2[1].disabled = 'disabled';
        addressLine2.bind('blur', function() {
            addressLine2[1].value = addressLine2[0].value;
        });

        city[1].value = city[0].value;
        city[1].disabled = 'disabled';
        city.bind('change', function() {
            city[1].value = city[0].value;
        });

        zipCode[1].value = zipCode[0].value;
        zipCode[1].disabled = 'disabled';
        zipCode.bind('blur', function() {
            zipCode[1].value = zipCode[0].value;
        });

        state[1].value = state[0].value;
        state[1].disabled = 'disabled';
        state.bind('change', function() {
            state[1].value = state[0].value;
        });
    }
    else {
        if (company.length > 0) {
            company[1].value = ''
            company[1].disabled = '';
            company.unbind('blur');
        }

    
        firstName[1].value = ''
        firstName[1].disabled = '';
        firstName.unbind('blur');

        lastName[1].value = ''
        lastName[1].disabled = '';
        lastName.unbind('blur');

        addressLine1[1].value = '';
        addressLine1[1].disabled = '';
        addressLine1.unbind('blur');

        addressLine2[1].value = '';
        addressLine2[1].disabled = '';
        addressLine2.unbind('blur');

        city[1].value = '';
        city[1].disabled = '';
        city.unbind('change');

        zipCode[1].value = '';
        zipCode[1].disabled = '';
        zipCode.unbind('blur');

        state[1].value = '';
        state[1].disabled = '';
        state.unbind('change');
    }
}

/*********************************** Enable or disable the CheckBox used just for the Contact Privileges ****************************/
function EnableCheckBox(ckbx_ModifyOrder, ckbx_CancelLine, ckbx_InsertLine) {
    AllowModifyOrder = document.getElementById(ckbx_ModifyOrder);
    AllowCancelLine = document.getElementById(ckbx_CancelLine);
    AllowInsertLine = document.getElementById(ckbx_InsertLine);

    if (!AllowModifyOrder.checked) {
        AllowCancelLine.disabled = true;
        AllowInsertLine.disabled = true;

        AllowCancelLine.checked = false;
        AllowInsertLine.checked = false;
    }
    else {
        AllowCancelLine.disabled = false;
        AllowInsertLine.disabled = false;
    }
}
/*********************************** End Disable or disable the CheckBox ****************************/
