(function ($) {
    $.formatCurrency = {};
    $.formatCurrency.regions = [];
    $.formatCurrency.regions[''] = {
        symbol: '$',
        positiveFormat: '%s%n',
        negativeFormat: '(%s%n)',
        decimalSymbol: '.',
        digitGroupSymbol: ',',
        groupDigits: true
    };
    $.fn.formatCurrency = function (destination, settings) {
        if (arguments.length == 1 && typeof destination !== "string") {
            settings = destination;
            destination = false;
        }
        var defaults = {
            name: "formatCurrency",
            colorize: false,
            region: '',
            global: true,
            roundToDecimalPlace: 2,
            eventOnDecimalsEntered: false
        };
        defaults = $.extend(defaults, $.formatCurrency.regions['']);
        settings = $.extend(defaults, settings);
        if (settings.region.length > 0) {
            settings = $.extend(settings, getRegionOrCulture(settings.region));
        }
        settings.regex = generateRegex(settings);
        return this.each(function () {
            $this = $(this);
            var num = '0';
            num = $this[$this.is('input, select, textarea') ? 'val' : 'html']();
            if (num.search('\\(') >= 0) {
                num = '-' + num;
            }
            if (num === '') {
                return;
            }
            if (isNaN(num)) {
                num = num.replace(settings.regex, '');
                if (num === '') {
                    return;
                }
                if (settings.decimalSymbol != '.') {
                    num = num.replace(settings.decimalSymbol, '.');
                }
                if (isNaN(num)) {
                    num = '0';
                }
            }
            var numParts = String(num).split('.');
            var isPositive = (num == Math.abs(num));
            var hasDecimals = (numParts.length > 1);
            var decimals = (hasDecimals ? numParts[1].toString() : '0');
            var originalDecimals = decimals;
            num = Math.abs(numParts[0]);
            if (settings.roundToDecimalPlace >= 0) {
                decimals = parseFloat('1.' + decimals);
                decimals = decimals.toFixed(settings.roundToDecimalPlace);
                if (decimals.substring(0, 1) == '2') {
                    num = Number(num) + 1;
                }
                decimals = decimals.substring(2);
            }
            num = String(num);
            if (settings.groupDigits) {
                for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
                    num = num.substring(0, num.length - (4 * i + 3)) + settings.digitGroupSymbol + num.substring(num.length - (4 * i + 3));
                }
            }
            if ((hasDecimals && settings.roundToDecimalPlace == -1) || settings.roundToDecimalPlace > 0) {
                num += settings.decimalSymbol + decimals;
            }
            var format = isPositive ? settings.positiveFormat : settings.negativeFormat;
            var money = format.replace(/%s/g, settings.symbol);
            money = money.replace(/%n/g, num);
            var $destination = $([]);
            if (!destination) {
                $destination = $this;
            } else {
                $destination = $(destination);
            }
            $destination[$destination.is('input, select, textarea') ? 'val' : 'html'](money);
            if (hasDecimals && settings.eventOnDecimalsEntered) {
                $destination.trigger('decimalsEntered', originalDecimals);
            }
            if (settings.colorize) {
                $destination.css('color', isPositive ? 'black' : 'red');
            }
        });
    };
    $.fn.toNumber = function (settings) {
        var defaults = $.extend({
            name: "toNumber",
            region: '',
            global: true
        }, $.formatCurrency.regions['']);
        settings = jQuery.extend(defaults, settings);
        if (settings.region.length > 0) {
            settings = $.extend(settings, getRegionOrCulture(settings.region));
        }
        settings.regex = generateRegex(settings);
        return this.each(function () {
            var method = $(this).is('input, select, textarea') ? 'val' : 'html';
            $(this)[method]($(this)[method]().replace('(', '(-').replace(settings.regex, ''));
        });
    };
    $.fn.asNumber = function (settings) {
        var defaults = $.extend({
            name: "asNumber",
            region: '',
            parse: true,
            parseType: 'Float',
            global: true
        }, $.formatCurrency.regions['']);
        settings = jQuery.extend(defaults, settings);
        if (settings.region.length > 0) {
            settings = $.extend(settings, getRegionOrCulture(settings.region));
        }
        settings.regex = generateRegex(settings);
        settings.parseType = validateParseType(settings.parseType);
        var method = $(this).is('input, select, textarea') ? 'val' : 'html';
        var num = $(this)[method]();
        num = num ? num : "";
        num = num.replace('(', '(-');
        num = num.replace(settings.regex, '');
        if (!settings.parse) {
            return num;
        }
        if (num.length == 0) {
            num = '0';
        }
        if (settings.decimalSymbol != '.') {
            num = num.replace(settings.decimalSymbol, '.');
        }
        return window['parse' + settings.parseType](num);
    };

    function getRegionOrCulture(region) {
        var regionInfo = $.formatCurrency.regions[region];
        if (regionInfo) {
            return regionInfo;
        } else {
            if (/(\w+)-(\w+)/g.test(region)) {
                var culture = region.replace(/(\w+)-(\w+)/g, "$1");
                return $.formatCurrency.regions[culture];
            }
        }
        return null;
    }

    function validateParseType(parseType) {
        switch (parseType.toLowerCase()) {
        case 'int':
            return 'Int';
        case 'float':
            return 'Float';
        default:
            throw 'invalid parseType';
        }
    }

    function generateRegex(settings) {
        if (settings.symbol === '') {
            return new RegExp("[^\\d" + settings.decimalSymbol + "-]", "g");
        } else {
            var symbol = settings.symbol.replace('$', '\\$').replace('.', '\\.');
            return new RegExp(symbol + "|[^\\d" + settings.decimalSymbol + "-]", "g");
        }
    }
})(jQuery);
jQuery(document).ready(function () {
    jQuery('#smenu').show();
    jQuery('textarea#giftnotes').keyup(function () {
        var limit = parseInt(jQuery(this).attr('maxlength'));
        var text = jQuery(this).val();
        var chars = text.length;
        if (chars > limit) {
            var new_text = text.substr(0, limit);
            jQuery(this).val(new_text);
        }
    });
    if (jQuery('#isVisible').val() == "No") {
        jQuery('#rowNewCard').show();
        document.getElementById('new_card').checked = true;
    } else {}
});

function test(frm) {}

function contactValidiation(frm) {
    var error = "";
    $("#" + frm + " :input").each(function () {
        if ($(this).attr('type') == "text" && $(this).attr('mandatory') == "true") {
            error += emptyCheck($(this));
        } else if ($(this).is('textarea') && $(this).attr('mandatory') == "true") {
            error += emptyCheck($(this));
        } else if ($(this).is('select') && $(this).attr('mandatory') == "true") {
            if ($(this).val() == 0) {
                error += "You didn't select " + $(this).attr("title") + ".\n";
            }
        } else if ($(this).attr('type') == "checkbox" && $(this).attr('mandatory') == "true") {
            if (!$(this).is(':checked')) {
                error += "You didn't select " + $(this).attr("title") + ".\n";
            }
        }
        if ($(this).attr("title") == 'Email') {
            var tfld = contacttrim($(this).val());
            if (tfld != "") {
                error += validateContactEmail($(this));
            }
        }
        if ($(this).attr("title") == 'Telephone Number') {
            var tfld = contacttrim($(this).val());
            if (tfld != "") {
                error += validatephone($(this));
            }
        }
    });
    if (error == "") {
        return true;
    }
    alert(error);
    return false;
}

function validatephone(fld) {
    var error = "";
    var tfld = contacttrim(fld.val());
    if (tfld == "") {
        error = "You didn't enter a phone number.\n";
    } else if (isNaN(tfld)) {
        error = "The phone number contains illegal characters.\n";
    } else if (!(tfld.length == 10)) {
        error = "The phone number is the wrong length.\n";
    }
    return error;
}

function changefocusa() {
    var midinit = document.getElementById('billMidInit').value;
    var ls = midinit.substr(midinit.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!((chk >= 65 && chk <= 90) || (chk >= 97 && chk <= 122)) || (chk == 32)) {
        var newval = midinit.substr(0, midinit.length - 1)
        document.getElementById('billMidInit').value = newval;
    }
}

function changefocus() {
    var bphno1 = document.getElementById('billPhone1').value;
    var ls = bphno1.substr(bphno1.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = bphno1.substr(0, bphno1.length - 1)
        document.getElementById('billPhone1').value = newval;
    } else if (document.getElementById('billPhone1').value.length == 3) {
        document.getElementById('billPhone2').focus();
    }
}

function changefocus1() {
    var bphno2 = document.getElementById('billPhone2').value;
    var ls = bphno2.substr(bphno2.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = bphno2.substr(0, bphno2.length - 1)
        document.getElementById('billPhone2').value = newval;
    } else if (document.getElementById('billPhone2').value.length == 3) {
        document.getElementById('billPhone3').focus();
    }
}

function changefocus2() {
    var bphno3 = document.getElementById('billPhone3').value;
    var ls = bphno3.substr(bphno3.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = bphno3.substr(0, bphno3.length - 1)
        document.getElementById('billPhone3').value = newval;
    }
}

function changecellphone1() {
    var cphno1 = document.getElementById('billCell1').value;
    var ls = cphno1.substr(cphno1.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = cphno1.substr(0, cphno1.length - 1)
        document.getElementById('billCell1').value = newval;
    } else if (document.getElementById('billCell1').value.length == 3) {
        document.getElementById('billCell2').focus();
    }
}

function changecellphone2() {
    var cphno2 = document.getElementById('billCell2').value;
    var ls = cphno2.substr(cphno2.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = cphno2.substr(0, cphno2.length - 1)
        document.getElementById('billCell2').value = newval;
    } else if (document.getElementById('billCell2').value.length == 3) {
        document.getElementById('billCell3').focus();
    }
}

function changecellphone3() {
    var cphno3 = document.getElementById('billCell3').value;
    var ls = cphno3.substr(cphno3.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = cphno3.substr(0, cphno3.length - 1)
        document.getElementById('billCell3').value = newval;
    }
}

function changephoneno1() {
    var sphno1 = document.getElementById('shipPhone1').value;
    var ls = sphno1.substr(sphno1.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = sphno1.substr(0, sphno1.length - 1)
        document.getElementById('shipPhone1').value = newval;
    } else if (document.getElementById('shipPhone1').value.length == 3) {
        document.getElementById('shipPhone2').focus();
    }
}

function changephoneno2() {
    var sphno2 = document.getElementById('shipPhone2').value;
    var ls = sphno2.substr(sphno2.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = sphno2.substr(0, sphno2.length - 1)
        document.getElementById('shipPhone2').value = newval;
    } else if (document.getElementById('shipPhone2').value.length == 3) {
        document.getElementById('shipPhone3').focus();
    }
}

function changephoneno3() {
    var cphno3 = document.getElementById('shipPhone3').value;
    var ls = cphno3.substr(cphno3.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = cphno3.substr(0, cphno3.length - 1)
        document.getElementById('shipPhone3').value = newval;
    }
}

function changecellfocus() {
    if (document.getElementById('billCell1').value.length == 3) {
        document.getElementById('billCell2').focus();
    }
}

function changecellfocus2() {
    if (document.getElementById('billCell2').value.length == 3) {
        document.getElementById('billCell3').focus();
    }
}

function validateguestuser(theForm) { 
    theForm.action.value = "guestuser";
    var reason = "";
    var email;
    reason += validatetextfields(theForm.firstname);
    if (reason != "") reason = reason.replace("The required field", "First Name")
    reason += validatetextfields(theForm.lastname);
    if (reason != "") reason = reason.replace("The required field", "Last Name")
    reason += validateEmails(theForm.registeremail);
    if (reason != "") email = reason.replace("The required field", "Email")
    reason += validateEmpty(theForm.city, "City");
    if (reason != "") reason = reason.replace("The required field", "City")
    reason += validateselectfields(theForm.country);
    if (reason != "") reason = reason.replace("The required field", "Country")
    reason += validateselectfields(theForm.state2);
    if (reason != "") reason = reason.replace("The required field", "State")
    if (reason != "") {
        alert("Before submitting, please correct the following:\n\n" + reason);
        return false;
    }
    return true;
}
function validateRegisterFormOnSubmit(theForm) {
    theForm.action.value = "register";
    var reason = "";
    var email;
    var pass;
    var cregisteremail;
    var confirmpass;
    reason += validatetextfields(theForm.firstname);
    if (reason != "") reason = reason.replace("The required field", "First Name")
    reason += validatetextfields(theForm.lastname);
    if (reason != "") reason = reason.replace("The required field", "Last Name")
    reason += validateEmails(theForm.registeremail);
    if (reason != "") email = reason.replace("The required field", "Email")
    reason += validateConfirmEmail(theForm.cregisteremail);
    if (reason != "") cregisteremail = reason.replace("The required field", "Email")
    reason += validatePassword(theForm.registerPasswd);
    if (reason != "") pass = reason.replace("The required field", "Password")
    reason += validateConfirmPassword(theForm.cregisterPasswd);
    if (reason != "") confirmpass = reason.replace("The required field", "Password")
    reason += validateEmpty(theForm.street, "Address");
    if (reason != "") reason = reason.replace("The required field", "Address")
    reason += validateEmpty(theForm.city, "City");
    if (reason != "") reason = reason.replace("The required field", "City")
    reason += validateselectfields(theForm.country);
    if (reason != "") reason = reason.replace("The required field", "Country")
    reason += validateZipCodess(theForm.zip);
    if (reason != "") reason = reason.replace("The required field", "Zip")
    reason += validateselectfields(theForm.state2);
    if (reason != "") reason = reason.replace("The required field", "State")
    reason += validatePhoneFields("phone");
    if (reason != "") reason = reason.replace("The required field", "Phone")
    reason += validatetextfields(theForm.captcha);
    if (reason != "") reason = reason.replace("The required field", "Captcha")
    if (email != "" && cregisteremail != "") reason += compareEmail(theForm.registeremail, theForm.cregisteremail);
    if (pass != "" && confirmpass != "") reason += comparePassword(theForm.registerPasswd, theForm.cregisterPasswd);
    if (reason != "") {
        alert("Before submitting, please correct the following:\n\n" + reason);
        return false;
    }
    return true;
}

function validateSchoolsignupFormOnSubmit(theForm) {
    var reason = "";
    var email;
    var pass;
    var cregisteremail;
    var confirmpass;
    reason += validateEmail(theForm.registeremail);
    if (reason != "") email = reason.replace("The required field", "Email")
    reason += validateConfirmEmail(theForm.cregisteremail);
    if (reason != "") cregisteremail = reason.replace("The required field", "Email")
    reason += validatePassword(theForm.registerPasswd);
    if (reason != "") pass = reason.replace("The required field", "Password")
    reason += validateConfirmPassword(theForm.cregisterPasswd);
    if (reason != "") confirmpass = reason.replace("The required field", "Password")
    reason += validatetextfields(theForm.firstname);
    if (reason != "") reason = reason.replace("The required field", "First Name")
    reason += validatetextfields(theForm.lastname);
    if (reason != "") reason = reason.replace("The required field", "Last Name")
    reason += validateEmpty(theForm.street);
    if (reason != "") reason = reason.replace("The required field", "Address")
    reason += validateEmpty(theForm.city);
    if (reason != "") reason = reason.replace("The required field", "City")
    reason += validateselectfields(theForm.country);
    if (reason != "") reason = reason.replace("The required field", "Country")
    reason += validateselectfields(theForm.state2);
    if (reason != "") reason = reason.replace("The required field", "State")
    reason += validateZipCodess(theForm.zip);
    if (reason != "") reason = reason.replace("The required field", "Zip")
    reason += validatePhoneFields("phone");
    if (reason != "") reason = reason.replace("The required field", "Phone")
    reason += validatetextfields(theForm.captcha);
    if (reason != "") reason = reason.replace("The required field", "Captcha")
    if (email != "" && cregisteremail != "") reason += compareEmail(theForm.registeremail, theForm.cregisteremail);
    if (pass != "" && confirmpass != "") reason += comparePassword(theForm.registerPasswd, theForm.cregisterPasswd);
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }
    return true;
}

function validateSchoolsignupFormOnSubmit(theForm) {
    var reason = "";
    var email;
    var pass;
    var cregisteremail;
    var confirmpass;
    reason += validatetextfields(theForm.schoolname);
    if (reason != "") reason = reason.replace("The required field", "State")
    reason += validateEmail(theForm.registeremail);
    if (reason != "") email = reason.replace("The required field", "Email")
    reason += validateConfirmEmail(theForm.cregisteremail);
    if (reason != "") cregisteremail = reason.replace("The required field", "Email")
    reason += validatePassword(theForm.registerPasswd);
    if (reason != "") pass = reason.replace("The required field", "Password")
    reason += validateConfirmPassword(theForm.cregisterPasswd);
    if (reason != "") confirmpass = reason.replace("The required field", "Password")
    reason += validatetextfields(theForm.firstname);
    if (reason != "") reason = reason.replace("The required field", "First Name")
    reason += validatetextfields(theForm.lastname);
    if (reason != "") reason = reason.replace("The required field", "Last Name")
    reason += validateEmpty(theForm.street);
    if (reason != "") reason = reason.replace("The required field", "Address")
    reason += validateEmpty(theForm.city);
    if (reason != "") reason = reason.replace("The required field", "City")
    reason += validateselectfields(theForm.country);
    if (reason != "") reason = reason.replace("The required field", "Country")
    reason += validateselectfields(theForm.state2);
    if (reason != "") reason = reason.replace("The required field", "State")
    reason += validateZipCodess(theForm.zip);
    if (reason != "") reason = reason.replace("The required field", "Zip")
    reason += validatePhoneFields("phone");
    if (reason != "") reason = reason.replace("The required field", "Phone")
    reason += validatetextfields(theForm.captcha);
    if (reason != "") reason = reason.replace("The required field", "Captcha")
    if (email != "" && cregisteremail != "") reason += compareEmail(theForm.registeremail, theForm.cregisteremail);
    if (pass != "" && confirmpass != "") reason += comparePassword(theForm.registerPasswd, theForm.cregisterPasswd);
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }
    return true;
}

function forgotPassword(theForm) {
    theForm.action.value = "login";
    var reason = "";
    reason += validateEmail(theForm.loginemail);
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }
    return true;
}

function showhidePass() {
    if (document.getElementById('changepass').style.display == 'none') {
        jQuery("#changepass").show();
        jQuery("#buttonrow").show();
        jQuery("#buttonrow1").hide();
    } else {
        jQuery("#changepass").hide();
        jQuery("#buttonrow").hide();
        jQuery("#buttonrow1").show();
        if (document.getElementById('changepasserr')) {
            jQuery("#changepasserr").hide();
        }
    }
}

function loadShipAddys() {
    jQuery("#shiplist").html('<p><span class=processing>Loading...</span></p>');
    jQuery('#shiplist').load("/fetchaddress/");
    Close();
}

function addAddress() {
    if (jQuery("#addshipform").html().length == 0) {
        jQuery('#addshipform').replaceWith("<div id='addshipform'></div>");
        jQuery('#addshipform').load('/addaddress/');
    }
}

function submitShipAddress() {
    var reason = "";
    reason += validateEmpty(document.getElementById('shipFirstName'), "First Name");
    if (reason != "") reason = reason.replace("The required field", "First Name");
    reason += validateEmpty(document.getElementById('shipLastName'), "Last Name");
    if (reason != "") reason = reason.replace("The required field", "Last Name");
    reason += validateEmpty(document.getElementById('shipAddress'), "Address");
    if (reason != "") reason = reason.replace("The required field", "Address");
    reason += validateEmpty(document.getElementById('shipCity'), "City");
    if (reason != "") reason = reason.replace("The required field", "City");
    reason += validateselectfields(document.getElementById('shipState'));
    if (reason != "") reason = reason.replace("The required field", "State");
    reason += validateZipCodess(document.getElementById('shipZip'));
    if (reason != "") reason = reason.replace("The required field", "Zip");
    reason += validatePhoneFields("shipPhone");
    if (reason != "") reason = reason.replace("The required field", "Phone");
    if (reason != "") {
        alert("Before submitting, please correct the following:\n\n" + reason);
        return false;
    } else {
        jQuery("#submitbutton").attr("disabled", true);
        jQuery.post("/myaccount", {
            fname: jQuery("input#shipFirstName").val(),
            lname: jQuery("input#shipLastName").val(),
            company: jQuery("input#shipCompany").val(),
            address: jQuery("input#shipAddress").val(),
            address2: jQuery("input#shipAddress2").val(),
            city: jQuery("input#shipCity").val(),
            state: jQuery("#shipState option:selected").val(),
            zip: jQuery("input#shipZip").val(),
            phone: jQuery("input#shipPhone1").val() + '-' + jQuery("input#shipPhone2").val() + '-' + jQuery("input#shipPhone3").val(),
            pl: "add"
        }, function (data) {
            loadShipAddys();
        });
        return false;
    }
}

function showHideShipRow(id) {
    if (document.getElementById('editShipRow' + id).style.display == 'none') {
        jQuery("#displayShipRow" + id).hide();
        jQuery("#editShipRow" + id).show();
        document.getElementById('editShipRow' + id).style.position = 'static';
    } else {
        jQuery("#displayShipRow" + id).show();
        jQuery("#editShipRow" + id).hide();
        document.getElementById('editShipRow' + id).style.position = 'absolute';
    }
    loadShipAddys();
}

function updateShipRow(id) {
    var reason = "";
    reason += validateEmpty(document.getElementById('shipFirstName' + id), "Firstname");
    if (reason != "") reason = reason.replace("The required field", "First Name");
    reason += validateEmpty(document.getElementById('shipLastName' + id), "Lastname");
    if (reason != "") reason = reason.replace("The required field", "Last Name");
    reason += validateEmpty(document.getElementById('shipAddress' + id), "Address");
    if (reason != "") reason = reason.replace("The required field", "Address");
    reason += validateEmpty(document.getElementById('shipCity' + id), "City");
    if (reason != "") reason = reason.replace("The required field", "City");
    if (document.getElementById('shipState' + id).value == '...') {
        if (reason != "") reason += "The required field", "State";
        else reason = "State";
    }
    reason += validateZipCodess(document.getElementById('shipZip' + id));
    reason += validatePhoneFields(id + "shipPhone");
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    } else {
        jQuery("#addshipform").hide();
        jQuery.post("/myaccount", {
            id: id,
            fname: jQuery("input#shipFirstName" + id).val(),
            lname: jQuery("input#shipLastName" + id).val(),
            company: jQuery("input#shipCompany" + id).val(),
            address: jQuery("input#shipAddress" + id).val(),
            address2: jQuery("input#shipAddress2" + id).val(),
            city: jQuery("input#shipCity" + id).val(),
            state: jQuery("#shipState" + id + " option:selected").val(),
            zip: jQuery("input#shipZip" + id).val(),
            phone: jQuery("input#" + id + "shipPhone1").val() + '-' + jQuery("input#" + id + "shipPhone2").val() + '-' + jQuery("input#" + id + "shipPhone3").val(),
            contactid: jQuery("input#contactId" + id).val(),
            accountid: jQuery("input#accountId" + id).val(),
            pl: "update"
        }, function (data) {
            jQuery("#addshipform").html('');
            loadShipAddys();
        });
    }
}

function deleteShipRow(id) {
    jQuery("#ajaxLoader").show();
    jQuery.post('/myaccount', {
        contactId: jQuery("input#contactId" + id).val(),
        pl: "delete"
    }, function () {
        loadShipAddys();
        jQuery("#ajaxLoader").hide();
    });
}

function loadPayments() {
    jQuery("#paymentlist").html('<p><span class=processing>Loading...</span></p>')
    jQuery('#paymentlist').load("/paymentdetail");
}

function addPayment() {
    if (jQuery("#payform").html().length == 0) {
        jQuery('#payform').replaceWith("<div id='payform'></div>");
        jQuery('#payform').load('/addcreditcard');
    }
}

function showHideBillRow(id) {
    if (document.getElementById('editBillRow' + id).style.display == 'none') {
        jQuery("#displayBillRow" + id).hide();
        jQuery("#editBillRow" + id).show();
    } else {
        jQuery("#displayBillRow" + id).show();
        jQuery("#editBillRow" + id).hide();
    }
}

function deleteBillRow(id) {
    jQuery("#payform").hide();
    jQuery("#ajaxLoader").show();
    jQuery.post('/deletebillingaddress', {
        contactId: jQuery("input#contactId" + id).val(),
        creditCartId: jQuery("input#creditCartId" + id).val()
    }, function (data) {
        jQuery("#payform").html('');
        jQuery("#ajaxLoader").hide();
        loadPayments();
    });
}

function savePayment() {
    var reason = "";
    var validCCN = "";
    var validCVV = "";
    reason += validateEmpty(document.getElementById('billFirstName'));
    if (reason != "") reason = reason.replace("The required field", "First Name");
    reason += validateEmpty(document.getElementById('billLastName'));
    if (reason != "") reason = reason.replace("The required field", "Last Name");
    reason += validateEmpty(document.getElementById('billAddress'));
    if (reason != "") reason = reason.replace("The required field", "Address");
    reason += validateEmpty(document.getElementById('billCity'));
    if (reason != "") reason = reason.replace("The required field", "City");
    reason += validateEmpty(document.getElementById('billState'));
    if (reason != "") reason = reason.replace("The required field", "State");
    reason += validateZipCodess(document.getElementById('billZip'));
    reason += validatePhoneFields("billPhone");
    reason += validateEmpty(document.getElementById('selCardType'));
    if (reason != "") reason = reason.replace("The required field", "Credit Card Type");
    reason += validateEmpty(document.getElementById('txtCreditCard'));
    if (reason != "") reason = reason.replace("The required field", "Credit Card Number");
    if (document.getElementById('txtCreditCard').value.length != 0) {
        validCCN = validateCreditCardNumber(document.getElementById('selCardType'), document.getElementById('txtCreditCard'));
        if (validCCN != "") {
            reason += validCCN;
        }
    }
    reason += validateEmpty(document.getElementById('selExpMonth'));
    if (reason != "") reason = reason.replace("The required field", "Expiration Month");
    reason += validateEmpty(document.getElementById('selExpYear'));
    if (reason != "") reason = reason.replace("The required field", "Expiration Year");
    if (reason == "") reason += validateExpDate(document.getElementById('selExpMonth').value, document.getElementById('selExpYear').value)
    reason += validateEmpty(document.getElementById('txtCardVerificationValue'));
    if (reason != "") reason = reason.replace("The required field", "Card Verification Value");
    if (document.getElementById('txtCardVerificationValue').value.length != 0) {
        validCVV = validateCvvCode(document.getElementById('selCardType'), document.getElementById('txtCardVerificationValue'));
        if (validCVV != "") {
            reason += validCVV;
        }
    }
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    } else {
        jQuery.post("/createcreditcard", {
            fname: jQuery("input#billFirstName").val(),
            lname: jQuery("input#billLastName").val(),
            company: jQuery("input#billCompany").val(),
            address: jQuery("input#billAddress").val(),
            address2: jQuery("input#billAddress2").val(),
            city: jQuery("input#billCity").val(),
            state: jQuery("#billState option:selected").val(),
            zip: jQuery("input#billZip").val(),
            phone: jQuery("input#billPhone1").val() + '-' + jQuery("input#billPhone2").val() + '-' + jQuery("input#billPhone3").val(),
            cname: jQuery("input#billFirstName").val() + ' ' + jQuery("input#billLastName").val(),
            ctype: jQuery("#selCardType option:selected").val(),
            cnum: jQuery("input#txtCreditCard").val(),
            cmonth: jQuery("#selExpMonth option:selected").val(),
            cyear: jQuery("#selExpYear option:selected").val(),
            cvv: jQuery("input#txtCardVerificationValue").val(),
            pl: "add"
        }, function (data) {
            jQuery("#payform").html('');
            loadPayments();
            document.getElementById('light').style.display = 'none';
            document.getElementById('light4').style.display = 'none';
        });
    }
}

function loginToCheckoutValidate(frm) {
    document.logintocheckout.actionParam.value = "login";
    var elem = document.getElementById(frm).elements;
    var str = '';
    for (var i = 0; i < elem.length; i++) {
        if ((elem[i].type == 'text')) {
            if (elem[i].name == 'email' && trim(elem[i].value).length == 0) {
                str += elem[i].title + ' is Empty.\n';
                elem[i].style.background = 'Yellow';
            } else if ((elem[i].name == 'email') && (elem[i].value.length != 0)) {
                str += validateEmail(elem[i]);
            }
        }
        if ((elem[i].type == 'password')) {
            if (elem[i].name == 'pass' && trim(elem[i].value).length == 0) {
                str += elem[i].title + ' is Empty.\n'
                elem[i].style.background = 'Yellow';
            } else if ((elem[i].name == 'email') && (elem[i].value.length != 0)) {
                str += validatePassword(elem[i]);
            }
        }
    }
    if (str != '') {
        alert(str);
        return false;
    }
    return true;
}

function loginToCheckoutValidatePword(frm) {
    var reason = "";
    reason += validateEmails(document.logintocheckout.email);
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        document.getElementById("email").style.background = 'Yellow';
        return false;
    } else {
        document.logintocheckout.actionParam.value = "lostpass";
        document.logintocheckout.submit();
    }
}

function checkoutStep1Validate(frm, buttonId) {
    var elem = document.getElementById(frm).elements;
    var reason = "";
    var validZip = "";
    var validBillEmail = "";
    var validBillCEmail = "";
    var validBillPhone = "";
    var validShipPhone = "";
    var validBillCell = "";
    var validBillPassword = "";
    var validBillCPassword = "";
    var emailFlag = false;
    var str = 'Before submitting, please correct the following:.\n\n';
    for (var i = 0; i < elem.length; i++) {
        if ((elem[i].type == 'text') || (elem[i].type == 'password')) {
            if (((elem[i].id != 'billMidInit') && (elem[i].id != 'billCell1') && (elem[i].id != 'billCell2') && (elem[i].id != 'billCell3') && (elem[i].id != 'billPhone1') && (elem[i].id != 'billPhone2') && (elem[i].id != 'billPhone3') && (elem[i].id != 'shipPhone1') && (elem[i].id != 'shipPhone2') && (elem[i].id != 'shipPhone3') && (elem[i].id != 'billCompany') && (elem[i].id != 'billAddress2') && (elem[i].id != 'shipCompany') && (elem[i].id != 'shipAddress2'))) {
                reason += validateEmpty(document.getElementById(elem[i].id), elem[i].title);
                if (reason != "") if (elem[i].title == 'Bill E-mail') {
                    elem[i].title = 'E-mail';
                }
                if (elem[i].title == 'Bill Confirm E-mail') {
                    elem[i].title = 'Confirm E-mail';
                }
                if (elem[i].title == 'Bill Password') {
                    elem[i].title = 'Password';
                }
                if (elem[i].title == 'Bill Confirm Password') {
                    elem[i].title = 'Confirm Password';
                }
                reason = reason.replace("The required field", elem[i].title);
            }
            if ((elem[i].name == 'billZip' || elem[i].name == 'shipZip') && (elem[i].value.length != 0)) {
                validZip = validateZipCodess(elem[i]);
            }
            if ((elem[i].name == 'billEmail') && (elem[i].value.length != 0)) {
                emailFlag = true;
                validBillEmail = validateEmails(elem[i]);
                if (validBillEmail != '') validBillEmail = validBillEmail.replace("email", (elem[i].title).toLowerCase());
            }
            if ((elem[i].name == 'billcEmail') && (elem[i].value.length != 0)) {
                validBillCEmail = validateEmails(elem[i]);
                if (validBillCEmail != '') validBillCEmail = validBillCEmail.replace("email", (elem[i].title).toLowerCase());
            }
            if (((elem[i].name == 'billPass') && (elem[i].value.length != 0))) {
                validBillPassword = validatePassword(elem[i]);
                if (validBillPassword != '') validBillPassword = validBillPassword.replace("password", (elem[i].title).toLowerCase());
            }
            if (((elem[i].name == 'billcPass') && (elem[i].value.length != 0))) {
                validBillCPassword = validatePassword(elem[i]);
                if (validBillCPassword != '') validBillCPassword = validBillCPassword.replace("password", (elem[i].title).toLowerCase());
            }
        }
        if ((elem[i].name == 'billState' || elem[i].name == 'shipState') && (elem[i].value == 0)) {
            reason += elem[i].title + " cannot be empty.\n";
        }
        if (elem[i].name == 'billState' && (elem[i].value != 0)) {
            elem[i].style.background = 'none';
        }
        if (elem[i].name == 'shipState' && (elem[i].value != 0)) {
            elem[i].style.background = 'none';
        }
    }
    validBillPhone = validateCheckoutPhoneSections('billPhone', 'Bill Phone');
    validShipPhone = validateCheckoutPhoneSections('shipPhone', 'Ship Phone');
    if (document.getElementById('billCell1').value.length != 0 || document.getElementById('billCell2').value.length != 0 || document.getElementById('billCell3').value.length != 0) validBillCell = validateCheckoutPhoneSections("billCell", 'Bill Cell Phone');
    reason += validZip + validBillPhone + validBillCell + validBillEmail + validBillCEmail + validBillPassword + validBillCPassword + validShipPhone;
    if (emailFlag) {
        if (reason == "" && (document.getElementById('billEmail').value != document.getElementById('billcEmail').value)) {
            reason = "Email addresses does not match."
        }
        if (reason == "" && (document.getElementById('billPass').value != document.getElementById('billcPass').value)) {
            reason = "Passwords does not match."
        }
    }
    if (reason != "") {
        str += reason;
        alert(str);
        return false;
    }
    if (jQuery('#termsAndCond').attr("checked")) {
        disableAddToBag(buttonId);
        return true;
    } else {
        jQuery('#termsId').removeClass('isChecked');
        jQuery('#termsId').addClass('isNotChecked');
        alert(jQuery('#termsAndCond').attr("title") + " has not been selected");
        return false;
    }
}

function checkoutStep2Validate(frm, buttonId) {
    var flag = document.getElementById('hidCCType').value;
    var profileId = '';
    var cardType = "";
    var cardError = "";
    var existCardType = "";
    var cvvValue = '';
    if (flag == "") {
        var elem = document.getElementById(frm).elements;
        var count = document.getElementsByName('PayMethodGroup1').length;
        for (var i = 0; i < count; i++) {
            if (document.getElementsByName('PayMethodGroup1')[i].checked) var cardType = document.getElementsByName('PayMethodGroup1')[i];
        }
        var paymentDetailsGroup = document.getElementsByName('paymentDetailsGroup');
        for (i = 0; i < paymentDetailsGroup.length; i++) {
            if (paymentDetailsGroup[i].checked && paymentDetailsGroup[i].value != 'new') {
                profileId = paymentDetailsGroup[i].value;
            }
        }
        for (var i = 0; i < elem.length; i++) {
            if ((elem[i].type == 'password') && (elem[i].alt == 'cvvText')) {
                elem[i].style.background = 'none';
            }
        }
        document.getElementById('creditCartId').value = profileId;
        var str = "";
        var validCVV = "";
        var existValidCVV = "";
        var validCCN = "";
        var validED = "";
        if (profileId == '') {
            if (cardType != "") {
                for (var i = 0; i < elem.length; i++) {
                    if (((elem[i].type == 'text') || (elem[i].type == 'password')) && elem[i].alt != 'cvvText') {
                        if (elem[i].name != 'PayMethodGroup1') {
                            if (trim(elem[i].value).length == 0) {
                                elem[i].style.background = 'Yellow';
                                str += elem[i].title + ' cannot be empty \n';
                            } else {
                                elem[i].style.background = 'none';
                            }
                        }
                        if ((elem[i].name == 'ccId') && (elem[i].value.length != 0)) {
                            validCVV = validateCvvCode(cardType, elem[i]);
                            if (validCVV != "") elem[i].style.background = 'Yellow';
                        }
                        if ((elem[i].name == 'ccNum') && (elem[i].value.length != 0)) {
                            validCCN = validateCreditCardNumber(cardType, elem[i]);
                            if (validCCN != "") elem[i].style.background = 'Yellow';
                        }
                    }
                }
                validED += validateExpDate(document.getElementById('ccExpMonth').value, document.getElementById('ccExpYear').value)
                if (validED != "") {
                    document.getElementById('ccExpMonth').style.background = 'Yellow';
                    document.getElementById('ccExpYear').style.background = 'Yellow';
                } else {
                    document.getElementById('ccExpMonth').style.background = 'none';
                    document.getElementById('ccExpYear').style.background = 'none';
                }
            } else cardError = "Please select the credit card type.";
        }
        if (profileId != '') {
            cvvValue = document.getElementById(profileId).value;
            existCardType = document.getElementById('cardType' + profileId).value;
            if (cvvValue != '') {
                existValidCVV = validateCvvCodeforExistCard(existCardType, cvvValue);
                if (existValidCVV != '') document.getElementById(profileId).style.background = 'Yellow';
                else document.getElementById('ccId').value = cvvValue;
            } else {
                str = 'The required field has not been filled in.\n';
                document.getElementById(profileId).style.background = 'Yellow';
            }
        }
        str += validCCN + validED + validCVV + existValidCVV + cardError;
        if (str != "") {
            alert(str);
            return false;
        }
        disableAddToBag(buttonId);
        return true;
    }
}

function _checkoutStep2Validate(frm, buttonId) {
    var flag = document.getElementById('hidCCType').value;
    var profileId = '';
    var cardType = "";
    var cardError = "";
    var existCardType = "";
    var cvvValue = '';
    if (flag == "") {
        var elem = document.getElementById(frm).elements;
        var count = document.getElementsByName('PayMethodGroup1').length;
        for (var i = 0; i < count; i++) {
            if (document.getElementsByName('PayMethodGroup1')[i].checked) var cardType = document.getElementsByName('PayMethodGroup1')[i];
        }
        var paymentDetailsGroup = document.getElementsByName('paymentDetailsGroup');
        for (i = 0; i < paymentDetailsGroup.length; i++) {
            if (paymentDetailsGroup[i].checked && paymentDetailsGroup[i].value != 'new') {
                profileId = paymentDetailsGroup[i].value;
            }
        }
        for (var i = 0; i < elem.length; i++) {
            if ((elem[i].type == 'password') && (elem[i].alt == 'cvvText')) {
                elem[i].style.background = 'none';
            }
        }
        document.getElementById('creditCartId').value = profileId;
        var str = "";
        var validCVV = "";
        var existValidCVV = "";
        var validCCN = "";
        var validED = "";
        if (profileId == '') {
            if (cardType != "") {
                for (var i = 0; i < elem.length; i++) {
                    if (((elem[i].type == 'text') || (elem[i].type == 'password')) && elem[i].alt != 'cvvText') {
                        if (elem[i].name != 'PayMethodGroup1') {
                            if (trim(elem[i].value).length == 0) {
                                elem[i].style.background = 'Yellow';
                                str = 'The required field has not been filled in.\n';
                            } else {
                                elem[i].style.background = 'none';
                            }
                        }
                        if ((elem[i].name == 'ccId') && (elem[i].value.length != 0)) {
                            validCVV = validateCvvCode(cardType, elem[i]);
                            if (validCVV != "") elem[i].style.background = 'Yellow';
                        }
                        if ((elem[i].name == 'ccNum') && (elem[i].value.length != 0)) {
                            validCCN = validateCreditCardNumber(cardType, elem[i]);
                            if (validCCN != "") elem[i].style.background = 'Yellow';
                        }
                    }
                }
                validED += validateExpDate(document.getElementById('ccExpMonth').value, document.getElementById('ccExpYear').value)
                if (validED != "") {
                    document.getElementById('ccExpMonth').style.background = 'Yellow';
                    document.getElementById('ccExpYear').style.background = 'Yellow';
                } else {
                    document.getElementById('ccExpMonth').style.background = 'none';
                    document.getElementById('ccExpYear').style.background = 'none';
                }
            } else cardError = "Please select the credit card type.";
        }
        if (profileId != '') {
            cvvValue = document.getElementById(profileId).value;
            existCardType = document.getElementById('cardType' + profileId).value;
            alert(existCardType);
            if (cvvValue != '') {
                existValidCVV = validateCvvCodeforExistCard(existCardType, cvvValue);
                alert(existValidCVV);
                if (existValidCVV != '') document.getElementById(profileId).style.background = 'Yellow';
                else document.getElementById('ccId').value = cvvValue;
            } else {
                str = 'The required field has not been filled in.\n';
                document.getElementById(profileId).style.background = 'Yellow';
            }
        }
        str += validCCN + validED + validCVV + existValidCVV + cardError;
        if (str != "") {
            alert(str);
            return false;
        }
        disableAddToBag(buttonId);
        return true;
    }
}
$(function () {
    $("select#billExistAddr").change(function () {
        var id = $(this).val();
        if (id == "") {
            jQuery("input#billFirstName").val("");
            jQuery("input#billMidInit").val("");
            jQuery("input#billLastName").val("");
            jQuery("input#billCompany").val("");
            jQuery("input#billAddress1").val("");
            jQuery("input#billAddress2").val("");
            jQuery("input#billCity").val("");
            jQuery("select#billState").val(0);
            jQuery("input#billZip").val("");
            jQuery("input#billPhone1").val("");
            jQuery("input#billPhone2").val("");
            jQuery("input#billPhone3").val("");
            jQuery("input#billCell1").val("");
            jQuery("input#billCell2").val("");
            jQuery("input#billCell3").val("");
            jQuery("input#billingAddressId").val("");
            $("input#billFirstName").attr("readonly", false);
            $("input#billMidInit").attr("readonly", false);
            $("input#billLastName").attr("readonly", false);
            $("input#billCompany").attr("readonly", false);
            $("input#billAddress1").attr("readonly", false);
            $("input#billAddress2").attr("readonly", false);
            $("input#billCity").attr("readonly", false);
            $("select#billState").attr("readonly", false);
            $("input#billZip").attr("readonly", false);
            $("input#billPhone1").attr("readonly", false);
            $("input#billPhone2").attr("readonly", false);
            $("input#billPhone3").attr("readonly", false);
            $("input#billCell1").attr("readonly", false);
            $("input#billCell2").attr("readonly", false);
            $("input#billCell3").attr("readonly", false);
        }
        var aId = 'selectBilling_' + id;
        var content = document.getElementById(aId).innerHTML;
        var mySplitResult = content.split("||");
        var fName = mySplitResult[0];
        var mName = mySplitResult[1];
        var lName = mySplitResult[2];
        var company = mySplitResult[3];
        var address1 = mySplitResult[4];
        var address2 = mySplitResult[5];
        var city = mySplitResult[6];
        var state = mySplitResult[7];
        var zip = mySplitResult[8];
        var country = mySplitResult[9];
        var phone1 = mySplitResult[10];
        var phone2 = mySplitResult[11];
        var phone3 = mySplitResult[12];
        var mobphone1 = mySplitResult[13];
        var mobphone2 = mySplitResult[14];
        var mobphone3 = mySplitResult[15];
        var addressId = mySplitResult[16];
        jQuery("input#billFirstName").val(fName);
        jQuery("input#billMidInit").val(mName);
        jQuery("input#billLastName").val(lName);
        jQuery("input#billCompany").val(company);
        jQuery("input#billAddress1").val(address1);
        jQuery("input#billAddress2").val(address2);
        jQuery("input#billCity").val(city);
        jQuery("select#billState").val(state);
        jQuery("input#billZip").val(zip);
        jQuery("input#billPhone1").val(phone1);
        jQuery("input#billPhone2").val(phone2);
        jQuery("input#billPhone3").val(phone3);
        jQuery("input#billCell1").val(mobphone1);
        jQuery("input#billCell2").val(mobphone2);
        jQuery("input#billCell3").val(mobphone3);
        jQuery("input#billingAddressId").val(addressId);
        $("input#billFirstName").attr("readonly", true);
        $("input#billMidInit").attr("readonly", true);
        $("input#billLastName").attr("readonly", true);
        $("input#billCompany").attr("readonly", true);
        $("input#billAddress1").attr("readonly", true);
        $("input#billAddress2").attr("readonly", true);
        $("input#billCity").attr("readonly", true);
        $("select#billState").attr("readonly", true);
        $("input#billZip").attr("readonly", true);
        $("input#billPhone1").attr("readonly", true);
        $("input#billPhone2").attr("readonly", true);
        $("input#billPhone3").attr("readonly", true);
        $("input#billCell1").attr("readonly", true);
        $("input#billCell2").attr("readonly", true);
        $("input#billCell3").attr("readonly", true);
    })
})
$(function () {
    $("select#shipExistAddr").change(function () {
        var id = $(this).val();
        if (id == "") {
            jQuery("input#shipFirstName").val("");
            jQuery("input#shipLastName").val("");
            jQuery("input#shipCompany").val("");
            jQuery("input#shipAddress1").val("");
            jQuery("input#shipAddress2").val("");
            jQuery("input#shipCity").val("");
            jQuery("select#shipState").val(0);
            jQuery("input#shipZip").val("");
            jQuery("input#shipPhone1").val("");
            jQuery("input#shipPhone2").val("");
            jQuery("input#shipPhone3").val("");
            jQuery("input#shippingAddressId").val("");
            jQuery("input#shippingContactId").val("");
            $("input#shipFirstName").attr("readonly", false);
            $("input#shipLastName").attr("readonly", false);
            $("input#shipCompany").attr("readonly", false);
            $("input#shipAddress1").attr("readonly", false);
            $("input#shipAddress2").attr("readonly", false);
            $("input#shipCity").attr("readonly", false);
            $("select#shipState").attr("readonly", false);
            $("input#shipZip").attr("readonly", false);
            $("input#shipPhone1").attr("readonly", false);
            $("input#shipPhone2").attr("readonly", false);
            $("input#shipPhone3").attr("readonly", false);
        }
        var aId = 'selectShipping_' + id;
        var content = document.getElementById(aId).innerHTML;
        content = content.replace(/&quot;/g, '"');
        content = content.replace(/&amp;/g, "&");
        content = content.replace(/&lt;/g, "<");
        content = content.replace(/&gt;/g, ">");
        content = content.replace(/&#039;/g, "'");
        var mySplitResult = content.split("||");
        var fName = mySplitResult[0];
        var lName = mySplitResult[1];
        var company = mySplitResult[2];
        var address1 = mySplitResult[3];
        var address2 = mySplitResult[4];
        var city = mySplitResult[5];
        var state = mySplitResult[6];
        var zip = mySplitResult[7];
        var country = mySplitResult[8];
        var phone1 = mySplitResult[9];
        var phone2 = mySplitResult[10];
        var phone3 = mySplitResult[11];
        var addressId = mySplitResult[12];
        var emailId = mySplitResult[13];
        var contactId = mySplitResult[14];
        jQuery("input#shipFirstName").val(fName);
        jQuery("input#shipLastName").val(lName);
        jQuery("input#shipCompany").val(company);
        jQuery("input#shipAddress1").val(address1);
        jQuery("input#shipAddress2").val(address2);
        jQuery("input#shipCity").val(city);
        jQuery("select#shipState").val(state);
        jQuery("input#shipZip").val(zip);
        jQuery("input#shipPhone1").val(phone1);
        jQuery("input#shipPhone2").val(phone2);
        jQuery("input#shipPhone3").val(phone3);
        jQuery("input#shippingAddressId").val(addressId);
        jQuery("input#shippingContactId").val(contactId);
        $("input#shipFirstName").attr("readonly", true);
        $("input#shipLastName").attr("readonly", true);
        $("input#shipCompany").attr("readonly", true);
        $("input#shipAddress1").attr("readonly", true);
        $("input#shipAddress2").attr("readonly", true);
        $("input#shipCity").attr("readonly", true);
        $("select#shipState").attr("readonly", true);
        $("input#shipZip").attr("readonly", true);
        $("input#shipPhone1").attr("readonly", true);
        $("input#shipPhone2").attr("readonly", true);
        $("input#shipPhone3").attr("readonly", true);
    })
})
$(function () {
    $("select#shipExistAddrpaypal").change(function () {
        var id = $(this).val();
        if (id == "") {
            jQuery("input#shipExistAddrpaypal").val("");
            jQuery("input#shipFName").val("");
            jQuery("input#shipLName").val("");
            jQuery("input#shipCompany").val("");
            jQuery("input#shipAddress1").val("");
            jQuery("input#shipAddress2").val("");
            jQuery("input#shipcity").val("");
            jQuery("select#shipstate").val(0);
            jQuery("input#shipzip").val("");
            jQuery("input#shipphone1").val("");
            jQuery("input#shipphone2").val("");
            jQuery("input#shipphone3").val("");
            jQuery("input#shippingAddressId").val("");
            jQuery("input#shippingContactId").val("");
            jQuery("input#ShipExistAccountId").val("");
            $("input#shipFName").attr("readonly", false);
            $("input#shipLName").attr("readonly", false);
            $("input#shipCompany").attr("readonly", false);
            $("input#shipAddress1").attr("readonly", false);
            $("input#shipAddress2").attr("readonly", false);
            $("input#shipcity").attr("readonly", false);
            $("input#shipstate").attr("readonly", false);
            $("input#shipzip").attr("readonly", false);
            $("input#shipphone1").attr("readonly", false);
            $("input#shipphone2").attr("readonly", false);
            $("input#shipphone3").attr("readonly", false);
        }
        var aId = 'selectShipping_' + id;
        var accountId = 'shipaccid' + id;
        var AccId = document.getElementById(accountId).value;
        jQuery("input#ShipExistAccountId").val(AccId);
        var content = document.getElementById(aId).innerHTML;
        var mySplitResult = content.split("||");
        var fName = mySplitResult[0];
        var lName = mySplitResult[1];
        var company = mySplitResult[2];
        var address1 = mySplitResult[3];
        var address2 = mySplitResult[4];
        var city = mySplitResult[5];
        var state = mySplitResult[6];
        var zip = mySplitResult[7];
        var country = mySplitResult[8];
        var phone1 = mySplitResult[9];
        var phone2 = mySplitResult[10];
        var phone3 = mySplitResult[11];
        var addressId = mySplitResult[12];
        var emailId = mySplitResult[13];
        var contactId = mySplitResult[14];
        jQuery("input#shipFName").val(fName);
        jQuery("input#shipLName").val(lName);
        jQuery("input#shipcompany").val(company);
        jQuery("input#shipAddress1").val(address1);
        jQuery("input#shipAddress2").val(address2);
        jQuery("input#shipcity").val(city);
        jQuery("select#shipstate").val(state);
        jQuery("input#shipzip").val(zip);
        jQuery("input#shipphone1").val(phone1);
        jQuery("input#shipphone2").val(phone2);
        jQuery("input#shipphone3").val(phone3);
        jQuery("input#shippingAddressId").val(addressId);
        jQuery("input#shippingContactId").val(contactId);
    })
})

function shipaddress_value() {
    var id = "";
    $("select#shipExistAddrpaypal option:selected").each(function () {
        id = $(this).val();
    });
    if (id == "") {
        jQuery("input#shipExistAddrpaypal").val("");
        jQuery("input#shipFName").val("");
        jQuery("input#shipLName").val("");
        jQuery("input#shipCompany").val("");
        jQuery("input#shipAddress1").val("");
        jQuery("input#shipAddress2").val("");
        jQuery("input#shipcity").val("");
        jQuery("select#shipstate").val(0);
        jQuery("input#shipzip").val("");
        jQuery("input#shipphone1").val("");
        jQuery("input#shipphone2").val("");
        jQuery("input#shipphone3").val("");
        jQuery("input#shippingAddressId").val("");
        jQuery("input#shippingContactId").val("");
        jQuery("input#ShipExistAccountId").val("");
        $("input#shipFName").attr("readonly", false);
        $("input#shipLName").attr("readonly", false);
        $("input#shipCompany").attr("readonly", false);
        $("input#shipAddress1").attr("readonly", false);
        $("input#shipAddress2").attr("readonly", false);
        $("input#shipcity").attr("readonly", false);
        $("input#shipstate").attr("readonly", false);
        $("input#shipzip").attr("readonly", false);
        $("input#shipphone1").attr("readonly", false);
        $("input#shipphone2").attr("readonly", false);
        $("input#shipphone3").attr("readonly", false);
    }
    var aId = 'selectShipping_' + id;
    var accountId = 'shipaccid' + id;
    var AccId = document.getElementById(accountId).value;
    jQuery("input#ShipExistAccountId").val(AccId);
    var content = document.getElementById(aId).innerHTML;
    var mySplitResult = content.split("||");
    var fName = mySplitResult[0];
    var lName = mySplitResult[1];
    var company = mySplitResult[2];
    var address1 = mySplitResult[3];
    var address2 = mySplitResult[4];
    var city = mySplitResult[5];
    var state = mySplitResult[6];
    var zip = mySplitResult[7];
    var country = mySplitResult[8];
    var phone1 = mySplitResult[9];
    var phone2 = mySplitResult[10];
    var phone3 = mySplitResult[11];
    var addressId = mySplitResult[12];
    var emailId = mySplitResult[13];
    var contactId = mySplitResult[14];
    jQuery("input#shipFName").val(fName);
    jQuery("input#shipLName").val(lName);
    jQuery("input#shipcompany").val(company);
    jQuery("input#shipAddress1").val(address1);
    jQuery("input#shipAddress2").val(address2);
    jQuery("input#shipcity").val(city);
    jQuery("select#shipstate").val(state);
    jQuery("input#shipzip").val(zip);
    jQuery("input#shipphone1").val(phone1);
    jQuery("input#shipphone2").val(phone2);
    jQuery("input#shipphone3").val(phone3);
    jQuery("input#shippingAddressId").val(addressId);
    jQuery("input#shippingContactId").val(contactId);
}

function validateFormOnSubmitFrd() {
    var reason = "";
    var yourEmail = "";
    var friendEmail = "";
    reason += validateEmpty(document.getElementById('yourname'));
    if (reason != '') reason = reason.replace("The required field", "Your Name");
    yourEmail = validateEmail(document.getElementById('youremail'));
    if (yourEmail != '') yourEmail = yourEmail.replace("email", "your email");
    reason += validateEmpty(document.getElementById('friendname'));
    if (reason != '') reason = reason.replace("The required field", "Friend Name");
    friendEmail += validateEmail(document.getElementById('friendemail'));
    if (friendEmail != '') friendEmail = friendEmail.replace("email", "friend email");
    reason += yourEmail + friendEmail;
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }
    return true;
}

function sortBy(sortBy) {
    document.getElementById('so').value = sortBy;
    document.frmsortby.submit();
}

function sortByPrice(sortBy) {
    document.getElementById('so').value = sortBy;
    document.frmsortby.submit();
}

function disableAddToBag(itemId) {
    var str = "";
    var itemqty = jQuery("#itemQty").val();
    var regExp = new RegExp('^[0-9]*$');
    if (trim(itemqty).length == 0) {
        str = "The required field has not been filled in.";
    } else if (!(regExp.test(itemqty))) {
        str += "Item's quantity is not valid.";
    }
    if (str != '') {
        alert(str);
        return false;
    }
    return true;
}

function validateQuantity(frm) {
    var elem = document.getElementById(frm).elements;
    var str = "";
    var validNo = "";
    for (var i = 0; i < elem.length; i++) {
        if ((elem[i].type == 'text')) {
            if (elem[i].name == 'hidItemQty[]') {
                var regExp = new RegExp('^[0-9]*$');
                if (trim(elem[i].value).length == 0) {
                    elem[i].style.background = 'Yellow';
                    str = "The required field has not been filled in.";
                } else if (!(regExp.test(elem[i].value) && parseInt(elem[i].value, 10) > 0)) {
                    elem[i].style.background = 'Yellow';
                    validNo = "Highlighted item's quantity is not valid.";
                } else {
                    elem[i].style.background = 'none';
                }
            }
        }
    }
    str += validNo;
    if (str != '') {
        alert(str);
        return false;
    }
    return true;
}

function calculateShipping(element, value) {
    var zip = document.getElementById('zip').value;
    var str = "";
    var validZip = "";
    var regExp = new RegExp('^[0-9]*$');
    if (trim(zip).length == 0) {
        document.getElementById('zip').style.background = 'Yellow';
        str = "The required field has not been filled in.\n";
    } else if (!(regExp.test(zip))) {
        document.getElementById('zip').style.background = 'Yellow';
        validZip = "Zip code is not valid.\n";
    } else if (trim(zip).length < 5) {
        document.getElementById('zip').style.background = 'Yellow';
        str = "Zip code is not valid...\n";
    } else {
        document.getElementById('zip').style.background = 'none';
    }
    str += validZip;
    if (str != '') {
        alert(str);
        return false;
    } else {
        $("#" + element).val(value);
        return true;
    }
}

function changeShippingOption(shipMethod, postalCode, status) {
    var temp = shipMethod;
    $("#shipMethod").val(temp);
    if (jQuery('#willCallRadio').attr("checked")) {
        document.getElementById("zip").value = "";
        jQuery("#zip").attr("readonly", true).val('').css({
            'background-color': '#D4D4D4'
        });
        jQuery("#gobtn").attr("disabled", "disabled");
        var shippingAmount = '0.00';
        var result = (parseFloat(shippingAmount) + parseFloat($("#hiddensubtotal").val()) + parseFloat($("#hiddensubandtax").val())) - (parseFloat($("#hiddenpromodiscount").val()));
        $("#hiddentotal").val(result);
        $("#hiddenshipmethod").val(temp);
        $("#hiddenshipping").val(shippingAmount);
        jQuery('#shippmentDiv').hide();
        jQuery('#callbutton').attr("disabled", "disabled");
        if (shippingAmount == 0) {
            $('#shippingdiv').hide();
        } else {
            $('#shippingdiv').show();
        }
        $("#hiddentotal").hide();
        $("#hiddenshipping").hide();
    } else {
        jQuery('#callbutton').removeAttr("disabled");
        jQuery("#zip").attr("readonly", false).val(postalCode).css({
            'background-color': ''
        });
        jQuery("#gobtn").removeAttr("disabled");
        jQuery('#shippmentDiv').show();
        if (status == 'Yes') jQuery("#shipMethod").removeAttr("disabled");
        updateTotalValue();
    }
}

function updateTotalValue() {
    var temp = $("#shipMethod").val();
    var shippingAmount = parseFloat($("#shipcode" + temp).val());
    var result = (parseFloat($("#shipcode" + temp).val()) + parseFloat($("#hiddensubtotal").val()) + parseFloat($("#hiddensubandtax").val())) - (parseFloat($("#hiddenpromodiscount").val()));
    $("#hiddentotal").val(result);
    $("#hiddenshipmethod").val(temp);
    $("#hiddenshipping").val(shippingAmount);
    if (shippingAmount == 0) $('#shippingdiv').hide();
    else $('#shippingdiv').show();
    $("#hiddentotal").hide();
    $("#hiddenshipping").hide();
    var sales = parseFloat(document.getElementById('salestaxamount').value);
    sales = isNaN(sales) ? 0 : sales;
    var a = parseFloat(document.getElementById('hiddensubtotal').value);
    a = isNaN(a) ? 0 : a;
    var b = parseFloat(document.getElementById('hiddenshipping').value);
    b = isNaN(b) ? 0 : b;
    var c = a + b + sales;
    var d = parseFloat(document.getElementById('hiddenpromodiscount').value);
    var total = c - d;
    var tot = total.toFixed(2);
    shippingAmount = isNaN(shippingAmount) ? 0 : shippingAmount;
    document.getElementById('shipping').innerHTML = "$" + shippingAmount.toFixed(2);
    document.getElementById('total').innerHTML = "$" + tot;
}

function updateTotalValues() {
    var temp = $("#shipMethod").val();
    var shippingAmount = parseFloat($("#shipcode" + temp).val());
    var result = (parseFloat($("#shipcode" + temp).val()) + parseFloat($("#hiddensubtotal").val()) + parseFloat($("#hiddensubandtax").val())) - (parseFloat($("#hiddenpromodiscount").val()));
    $("#hiddentotal").val(result);
    $("#hiddenshipmethod").val(temp);
    $("#hiddenshipping").val(shippingAmount);
    $('#hiddentotal').formatCurrency('#total');
    $('#hiddenshipping').formatCurrency('#shipping');
    if (shippingAmount == 0) $('#shippingdiv').hide();
    else $('#shippingdiv').show();
    $("#hiddentotal").hide();
    $("#hiddenshipping").hide();
    var sales = parseFloat(document.getElementById('salestaxamount').value);
    var a = parseFloat(document.getElementById('hiddensubtotal').value);
    var b = parseFloat(document.getElementById('hiddenshipping').value);
    var c = a + b + sales;
    var d = parseFloat(document.getElementById('hiddenpromodiscount').value);
    var total = c - d;
    var tot = total.toFixed(2);
    document.getElementById('total').innerHTML = "$" + tot.toFixed(2);
}

function updateTotalValuegoogle() {
    var temp = $("#shipMethod").val();
    var shippingAmount = parseFloat($("#shipcode" + temp).val());
    var result = (parseFloat($("#shipcode" + temp).val()) + parseFloat($("#hiddensubtotal").val()) + parseFloat($("#hiddensubandtax").val())) - (parseFloat($("#hiddenpromodiscount").val()));
    $("#hiddentotal").val(result);
    $("#hiddenshipmethod").val(temp);
    $("#hiddenshipping").val(shippingAmount);
    $('#hiddentotal').formatCurrency('#total');
    $('#hiddenshipping').formatCurrency('#shipping');
    if (shippingAmount == 0) $('#shippingdiv').hide();
    else $('#shippingdiv').show();
    $("#hiddentotal").hide();
    $("#hiddenshipping").hide();
    var sales = parseFloat(document.getElementById('salestaxamount').value);
    var a = parseFloat(document.getElementById('hiddensubtotal').value);
    var b = parseFloat(document.getElementById('hiddenshipping').value);
    var c = a + b + sales;
    var d = parseFloat(document.getElementById('hiddenpromodiscount').value);
    var total = c - d;
    var tot = total.toFixed(2);
    document.getElementById('totalgoogle').innerHTML = "$" + tot.toFixed(2);
}

function wayToCheckout(ele) {
    if (ele == 'securecheckout') {
        document.getElementById('checkout_action').value = "secureCheckout";
        return true;
    }
    if (ele == 'directpaypal') {
        document.getElementById('checkout_action').value = "directpaypal";
        return true;
    } else if (ele == 'paypalcheckout') {
        document.getElementById('checkout_action').value = "paypalcheckout";
        for (var i = 0; i < document.cartfrm.willCallRadio.length; i++) {
            if (document.cartfrm.willCallRadio[i].checked) {
                var ship_status = document.cartfrm.willCallRadio[i].value;
            }
        }
        document.getElementById('shippingstatus').value = ship_status;
        return true;
    } else {
        document.getElementById('checkout_action').value = "googleCheckout";
        return true;
    }
}

function wayTogoogleCheckout(ele) {
    document.getElementById('checkout_action').value = "googleCheckout";
    return false;
    return true;
}

function googleChecktoutValidate(frm) {
    var elem = document.getElementById(frm).elements;
    var reason = "";
    var validZip = "";
    var validShipPhone = "";
    var str = 'Following required field has not been filled in.\n';
    for (var i = 0; i < elem.length; i++) {
        if ((elem[i].type == 'text')) {
            if ((elem[i].id != 'shipcompany') && (elem[i].id != 'shipphone1') && (elem[i].id != 'shipAddress2') && (elem[i].id != 'shipphone2') && (elem[i].id != 'shipphone3')) {
                reason += validategoogleEmpty(document.getElementById(elem[i].id));
                if (reason != "") reason = reason.replace("The required field", elem[i].title);
            }
            if ((elem[i].name == 'shipzip') && (elem[i].value.length != 0)) {
                validZip = validateZipCodess(elem[i]);
            }
        }
        if (elem[i].name == 'shipstate' && (elem[i].value == 0)) {
            reason += elem[i].title + " cannot be empty.\n";
        } else if (elem[i].name == 'shipstate' && (elem[i].value != 0)) {
            elem[i].style.background = 'none';
        }
    }
    validShipPhone = validatePhoneFields('shipphone');
    reason += validZip + validShipPhone;
    if (reason != "") {
        str += reason;
        alert(str);
        return false;
    }
    var shipmethodval = document.getElementById('shipMethod').value;
    if (shipmethodval == '') {
        alert("Please Select Shipping Method");
        document.getElementById('shipMethod').style.background = 'Yellow';
        return false;
    }
    return true;
}

function trimchk(s) {
    return s.replace(/^\s+|\s+$/, '');
}

function toggleShipping() {
    jQuery("input#shipFirstName").val(jQuery("input#billFirstName").val());
    jQuery("input#shipLastName").val(jQuery("input#billLastName").val());
    jQuery("input#shipCompany").val(jQuery("input#billCompany").val());
    jQuery("input#shipAddress1").val(jQuery("input#billAddress1").val());
    jQuery("input#shipAddress2").val(jQuery("input#billAddress2").val());
    jQuery("input#shipCity").val(jQuery("input#billCity").val());
    jQuery("select#shipState").val(jQuery("select#billState").val());
    jQuery("input#shipZip").val(jQuery("input#billZip").val());
    jQuery("select#shipCountry").val(jQuery("select#billCountry").val());
    jQuery("input#shipPhone1").val(jQuery("input#billPhone1").val());
    jQuery("input#shipPhone2").val(jQuery("input#billPhone2").val());
    jQuery("input#shipPhone3").val(jQuery("input#billPhone3").val());
    jQuery("select#shipExistAddr").val();
}

function AddNewShipTo() {
    jQuery("input#shipFirstName").val('');
    jQuery("input#shipLastName").val('');
    jQuery("input#shipCompany").val('');
    jQuery("input#shipAddress1").val('');
    jQuery("input#shipAddress2").val('');
    jQuery("input#shipCity").val('');
    jQuery("select#shipState").val(0);
    jQuery("input#shipZip").val('');
    jQuery("select#shipCountry").val(0);
    jQuery("input#shipPhone1").val('');
    jQuery("input#shipPhone2").val('');
    jQuery("input#shipPhone3").val('');
    jQuery("select#shipExistAddr").val();
    $("input#shipFirstName").attr("readonly", false);
    $("input#shipLastName").attr("readonly", false);
    $("input#shipCompany").attr("readonly", false);
    $("input#shipAddress1").attr("readonly", false);
    $("input#shipAddress2").attr("readonly", false);
    $("input#shipCity").attr("readonly", false);
    $("input#shipState").attr("readonly", false);
    $("input#shipZip").attr("readonly", false);
    $("input#shipCountry").attr("readonly", false);
    $("input#shipPhone1").attr("readonly", false);
    $("input#shipPhone2").attr("readonly", false);
    $("input#shipPhone3").attr("readonly", false);
}

function displayCVVContent(cardType) {
    if (cardType == "amex") {
        jQuery("#amextxtCCID").show();
        jQuery("#deftxtCCID").hide();
    } else {
        jQuery("#amextxtCCID").hide();
        jQuery("#deftxtCCID").show();
    }
}

function giftNote() {
    if (jQuery('#addgiftcheck').attr("checked")) {
        jQuery("#addgiftsub").hide();
        jQuery("#addgiftrow").show();
    } else {
        jQuery("#addgiftrow").hide();
        jQuery("#addgiftsub").show();
        jQuery("#giftnotes").val('');
    }
}

function image1(value) {
    var paymentDetailsGroup = document.getElementsByName('paymentDetailsGroup');
    if (value == "new") {
        document.getElementById('rowNewCard').style.display = "block";
        for (i = 0; i < paymentDetailsGroup.length; i++) {
            jQuery("input#" + paymentDetailsGroup[i].value).val('');
            jQuery("input#" + paymentDetailsGroup[i].value).css({
                'background-color': '#ebe8de'
            });
            jQuery("input#" + paymentDetailsGroup[i].value).attr("readonly", true);
        }
    } else {
        document.getElementById('rowNewCard').style.display = "none";
        document.getElementById('new_card').checked = false;
        jQuery("input#ccId").val('');
        for (i = 0; i < paymentDetailsGroup.length; i++) {
            if (paymentDetailsGroup[i].checked && paymentDetailsGroup[i].value != 'new') {
                jQuery("input#" + paymentDetailsGroup[i].value).val('');
                jQuery("input#" + paymentDetailsGroup[i].value).css({
                    'background-color': '#fff'
                });
                jQuery("input#" + paymentDetailsGroup[i].value).attr("readonly", false);
            } else {
                jQuery("input#" + paymentDetailsGroup[i].value).val('');
                jQuery("input#" + paymentDetailsGroup[i].value).css({
                    'background-color': '#ebe8de'
                });
                jQuery("input#" + paymentDetailsGroup[i].value).attr("readonly", true);
            }
        }
    }
}

function validateLoginFormOnSubmit(theForm) {
    var reason = "";
    var reasons = "";
    reasons = validateEmptys(theForm.loginemail, theForm.loginpasswd);
    reason += validateEmails(theForm.loginemail);
    reason += validatePassword(theForm.loginpasswd);
    if (reasons == "" && reason == "") {
        return true;
    } else if (reasons != "") {
        alert("The required field has not been filled in:\n\n" + reason);
        return false;
    } else if (reason != "") {
        alert("Some fields need correction: \n" + reason);
        return false;
    }
}

function validateEmptys(fld, fld1) {
    var error = "";
    if (fld.value.length == 0 && fld1.value.length == 0) {
        error = "The required field has not been filled in. \n"
    } else {
        fld.style.background = 'none';
    }
    if (fld.type == 'select-one') {
        if (fld.value == 0) {
            error = "The required field has not been filled in. \n"
        } else {
            fld.style.background = 'none';
        }
    }
    return error;
}

function validateLoginPassForm(theForm) {
    var reason = "";
    var pass;
    reason += validateEmpty(theForm.txtNewFirstName, "First Name");
    if (reason != "") reason = reason.replace("The required field", "First Name")
    reason += validateEmpty(theForm.txtNewLastName, "Last Name");
    if (reason != "") reason = reason.replace("The required field", "Last Name")
    reason += validateOldPassword(theForm.txtOldPassword);
    if (reason != "") pass = reason.replace("The required field", "Old Password")
    reason += validateNewPassword(theForm.txtNewPassword);
    if (reason != "") pass = reason.replace("The required field", "New Password")
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }
    document.frmchangepass.submit();
}

function emptyCheck(fld) {
    var error = "";
    var tfld = trim(fld.val());
    if (tfld == "") {
        error = "You didn't enter " + fld.attr("title") + ".\n";
    }
    return error;
}

function trim(s) {
    return s.replace(/^\s+|\s+$/, '');
}

function validateEmpty(fld) {
    var error = "";
    if (fld.value.length == 0) {
        error = "The required field has not been filled in.\n"
    } else {
        fld.style.background = 'none';
    }
    if (fld.type == 'select-one') {
        if (fld.value == 0) {
            error = "The required field has not been filled in.\n"
        } else {
            fld.style.background = 'none';
        }
    }
    return error;
}

function validategoogleEmpty(fld) {
    var error = "";
    var elem = trimchk(fld.value);
    if (elem.length == 0) {
        error = "The required field cannot be empty.\n"
    } else {
        fld.style.background = 'none';
    }
    if (fld.type == 'select-one') {
        if (fld.value == 0) {
            error = "The required field cannot be empty.\n"
        } else {
            fld.style.background = 'none';
        }
    }
    return error;
}

function validatetextfields(fld) {
    var error = "";
    if (fld.name == "schoolname") {
        var i;
        var marketexist;
        var ajaxids = document.getElementById('schooljs').value;
        var marketname = ajaxids.split(',');
        for (i = 0; i < marketname.length; i++) {
            if (document.getElementById("schoolname").value == marketname[i]) {
                marketexist = 1;
            }
        }
    }
    var illegalChars = /^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$/;
    if (fld.value == "") {
        error = " cannot be empty\n";
    } else if (fld.name != "schoolname" && fld.name != "firsstname" && fld.name != "lasstname" && illegalChars.test(fld.value) == false) {
        var error = "";
        error = " :The Text Field contains illegal characters\n";
    } else if (fld.name == "schoolname" && marketexist != 1) {
        error = " : Not Avaiable.\n";
    } else {
        fld.style.background = 'none';
    }
    if (error == "") {
        return error;
    } else {
        if (fld.name == "firstname") {
            names = "First name";
        } else if (fld.name == "lastname") {
            names = "Last name";
        } else if (fld.name == "schoolname") {
            names = "School name";
        } else if (fld.name == "captcha[input]") {
            names = "Captcha[input]";
        } else {
            names = fld.name;
        }
        error = names + error;
    }
    return error;
}

function validateEmail(fld) {
    var error = "";
    var tfld = trimchk(fld.value);
    var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
    if (tfld == "") {
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfld)) {
        error = "Please enter a valid email address.\n";
    } else if (fld.value.match(illegalChars)) {
        error = "The email address contains illegal characters.\n";
    } else {
        var st;
        fld.style.background = 'none';
    }
    return error;
}

function contacttrim(s) {
    return s.replace(/^\s+|\s+$/, '');
}

function validateContactEmail(fld) {
    var error = "";
    var tfld = contacttrim(fld.val());
    var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
    if (tfld == "") {
        error = "You didn't enter " + fld.attr("title") + ".\n";
    } else if (!emailFilter.test(tfld)) {
        error = "Please enter a valid " + fld.attr("title") + ".\n";
    } else if (tfld.match(illegalChars)) {
        error = "The " + fld.attr("title") + " contains illegal characters.\n";
    }
    return error;
}

function validateConfirmEmail(fld) {
    var error = "";
    var tfld = trimchk(fld.value);
    var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
    if (tfld == "") {
        error = "Confirm email address cannot be empty\n";
    } else if (!emailFilter.test(tfld)) {
        error = "Please enter a valid confirm email address\n";
    } else if (fld.value.match(illegalChars)) {
        error = "The confirm email address contains illegal characters\n";
    } else {
        var st;
        fld.style.background = 'none';
    }
    return error;
}

function validatePassword(fld) {
    var error = "";
    var illegalChars = /[\W_]/;
    if (fld.value == "") {
        error = "Password cannot be empty\n";
    } else if (fld.value.length < 8) {
        error = "The password length should be 8 characters minimum \n";
    } else if (fld.value.length > 14) {
        error = "The password length should be 14 characters maximum \n";
    } else {
        fld.style.background = 'none';
    }
    return error;
}

function validateOldPassword(fld) {
    var error = "";
    var illegalChars = /[\W_]/;
    if (fld.value == "") {
        error = "Old Password cannot be empty\n";
    } else if (fld.value.length < 8) {
        error = "The Old Password length should be 8 characters minimum \n";
    } else if (fld.value.length > 14) {
        error = "The Old Password length should be 14 characters maximum \n";
    } else {
        fld.style.background = 'none';
    }
    return error;
}

function validateNewPassword(fld) {
    var error = "";
    var illegalChars = /[\W_]/;
    if (fld.value == "") {
        error = "New Password cannot be empty\n";
    } else if (fld.value.length < 8) {
        error = "The New Password length should be 8 characters minimum. \n";
    } else if (fld.value.length > 14) {
        error = "The New Password length should be 14 characters maximum. \n";
    } else {
        fld.style.background = 'none';
    }
    return error;
}

function validateConfirmPassword(fld) {
    var error = "";
    var illegalChars = /[\W_]/;
    if (fld.value == "") {
        error = "Confirm password cannot be empty\n";
    } else if (fld.value.length < 8) {
        error = "The confirm password length should be 8 characters minimum. \n";
    } else if (fld.value.length > 15) {
        error = "The confirm password length should be 14 characters maximum. \n";
    } else {
        fld.style.background = 'none';
    }
    return error;
}

function compareEmail(fld, fld1) {
    var error = "";
    if (fld1.value != "") fld1.style.background = 'none';
    if (fld.value != fld1.value) {
        error = "Email and Confirmation Email did not match.\n";
    }
    return error;
}

function comparePassword(fld, fld1) {
    var error = "";
    if (fld1.value != "") fld1.style.background = 'none';
    if (fld.value != fld1.value) {
        error = "Password and Confirmation Password did not match.";
    }
    return error;
}

function validatePhoneFields(fldname) {
    var error = "";
    var s1 = document.getElementById(fldname + '1')
    var s2 = document.getElementById(fldname + '2')
    var s3 = document.getElementById(fldname + '3')
    fld = s1.value + s2.value + s3.value;
    if (fld == "") {
        error = "Phone number cannot be empty\n";
    } else if (isNaN(fld)) {
        error = "The phone number contains illegal characters\n";
    } else if (fld.length < 10) {
        error = "The phone number is the wrong length\n";
    } else {
        s1.style.background = 'none';
        s2.style.background = 'none';
        s3.style.background = 'none';
    }
    return error;
}

function validateCheckoutPhoneSections(fldname, title) {
    var error = "";
    var s1 = document.getElementById(fldname + '1')
    var s2 = document.getElementById(fldname + '2')
    var s3 = document.getElementById(fldname + '3')
    fld = s1.value + s2.value + s3.value;
    if (fld == "") {
        error = title + " cannot be empty.\n";
    } else if (isNaN(parseInt(fld))) {
        error = title + " contains illegal characters.\n";
    } else if (fld.length < 10) {
        error = title + " is the wrong length.\n";
    } else {
        s1.style.background = 'none';
        s2.style.background = 'none';
        s3.style.background = 'none';
    }
    return error;
}

function validateselectfields(fld) {
    var error = "";
    var error = fld.name;
    var error1 = fld.selectedIndex;
    if ((fld.selectedIndex) == "") {
        if (error == "country") {
            error = "Country";
        } else if (error == "state2") {
            error = "State";
        } else if (error == "schoolname") {
            error = "Schoolname";
        }
        error = "Please select a " + error + "\n";
    } else {
        error = "";
    }
    return error;
}

function vvvalidatephone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');
    if (fld.value == "") {
        error = "You didn't enter a phone number.\n";
    } else if (isNaN(parseInt(stripped))) {
        error = "The phone number contains illegal characters.\n";
    } else if (!(stripped.length == 10)) {
        error = "The phone number is the wrong length. Make sure you included an area code.\n";
    }
    return error;
}

function validateRadio(fld) {
    var error = "";
    var radio_choice = false;
    var count;
    for (count = 0; count < fld.length; count++) {
        if (fld[count].checked) radio_choice = true;
    }
    if (!radio_choice) {
        error = "Please select a Title.\n"
    }
    return error;
}

function validateZipCode(fld) {
    var error = "";
    var regExp = new RegExp('^[0-9]*$');
    if (fld.value.length != 5) {
        error += "Please enter your 5 digit or 5 digit+4 zip code.\n";
    } else if (!(regExp.test(fld.value))) {
        error += "Not a valid Zip Code.\n";
    } else fld.style.background = 'none';
    return error;
}

function validateCreditCardNumber(optName, fldId) {
    var error = "";
    var cardType = optName.value;
    var ccnNumber = fldId.value;
    var ccnDigits = 0;
    switch (cardType.toUpperCase()) {
    case '002':
    case '001':
    case '004':
        ccnDigits = 16;
        break;
    case '003':
        ccnDigits = 15;
        break;
    default:
        return false;
    }
    var regExp = new RegExp('[0-9]{' + ccnDigits + '}');
    if (!(ccnNumber.length == ccnDigits && regExp.test(ccnNumber))) {
        error = "Invalid Credit Card Number.\n";
    }
    return error;
}

function validateExpDate(expmo, expyr) {
    var error = "";
    var ccExpYear = expyr;
    var ccExpMonth = expmo;
    var expDate = new Date();
    expDate.setFullYear(ccExpYear, ccExpMonth, 1);
    var today = new Date();
    if (expDate < today) {
        error = "Credit Card is expired.\n";
    }
    return error;
}

function validateCvvCode(optName, fldId) {
    var error = "";
    var cardType = optName.value;
    var cvvCode = fldId.value;
    var cvvDigits = 0;
    switch (cardType.toUpperCase()) {
    case '002':
    case '001':
    case '004':
        cvvDigits = 3;
        break;
    case '003':
        cvvDigits = 4;
        break;
    default:
        return false;
    }
    var regExp = new RegExp('[0-9]{' + cvvDigits + '}');
    if (!(cvvCode.length == cvvDigits && regExp.test(cvvCode))) {
        error = "Invalid CVV Code.\n";
    }
    return error;
}

function validateCvvCodeforExistCard(cardType, cvvCode) {
    var error = "";
    var cvvDigits = 0;
    switch (cardType.toUpperCase()) {
    case 'VISA':
    case 'MASTER':
    case 'DISCOVER':
        cvvDigits = 3;
        break;
    case 'AMERICAN EXPRESS':
        cvvDigits = 4;
        break;
    default:
        return false;
    }
    var regExp = new RegExp('[0-9]{' + cvvDigits + '}');
    if (!(cvvCode.length == cvvDigits && regExp.test(cvvCode))) {
        error = "Invalid CVV Code.\n";
    }
    return error;
}

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 switchtab(el, id) {
    tabs = document.getElementById('tabs').getElementsByTagName('a');
    for (i = 0; i < tabs.length; i++) tabs[i].className = '';
    tabs = document.getElementById('content').getElementsByTagName('div');
    for (i = 0; i < tabs.length; i++) tabs[i].style.display = 'none';
    el.className = 'sel';
    document.getElementById(id).style.display = 'block';
    return false;
}
var xmlSaleInvHttp;

function switchtab(id) {
    vartabs = document.getElementById('tabs').getElementsByTagName('a');
    for (i = 0; i < vartabs.length; i++) vartabs[i].className = '';
    vartabs = document.getElementById('content').getElementsByTagName('div');
    for (i = 0; i < vartabs.length; i++) vartabs[i].style.display = 'none';
    document.getElementById('tablink' + id).className = 'sel';
    document.getElementById('tab' + id).style.display = 'block';
    return false;
}

function paginationByPage(pageno) {
    document.getElementById('pageno').value = pageno;
    document.frmsortby.submit();
}

function validateQuantityAtItem(frm, itemId) {
    var elem = document.getElementById(frm).elements;
    var str = "";
    var validNo = "";
    var bulkOrder = "";
    var maxQty = document.getElementById('maximumOrderQuantity').value;
    for (var i = 0; i < elem.length; i++) {
        if ((elem[i].type == 'text')) {
            if (elem[i].name == 'itemQty') {
                var regExp = new RegExp('^[0-9]*$');
                if (trim(elem[i].value).length == 0) {
                    elem[i].style.background = 'Yellow';
                    str = "The required field has not been filled in.";
                } else if (!(regExp.test(elem[i].value) && parseInt(elem[i].value, 10) > 0)) {
                    elem[i].style.background = 'Yellow';
                    validNo = "Highlighted item's quantity is not valid.";
                } else if (parseInt(elem[i].value, 10) > parseInt(maxQty, 10)) {
                    elem[i].style.background = 'Yellow';
                    bulkOrder = "Please contact us for quantity orders.";
                } else {
                    elem[i].style.background = 'none';
                }
            }
        }
    }
    str += validNo + bulkOrder;
    if (str != '') {
        alert(str);
        return false;
    }
    disableAddToBag(itemId);
    return true;
}

function validateZipCodes(fld) {
    var error = "";
    var regExp = /^([0-9]{5})+\-([0-9]{4})$/;
    if (fld.value.length < 5) {
        error += "Please enter your 5 digit or 5 digit+4 zip code.\n";
    } else if (!(regExp.test(fld.value))) {
        error += "Not a valid Zip Code.\n";
    } else fld.style.background = 'none';
    return error;
}

function validateZipCodess(fld) {
    var error = "";
    var valid = "0123456789-";
    var hyphencount = 0;
    var field = fld.value;
    if (field.length != 5 && field.length != 10) {
        error = " Zip Code cannot be empty\n";
    }
    if (field.length != 5 && field.length != 10) {
        error = "Please enter your 5 digit or 5 digit+4 zip code\n";
    }
    for (var i = 0; i < field.length; i++) {
        temp = "" + field.substring(i, i + 1);
        if (temp == "-") hyphencount++;
        if (valid.indexOf(temp) == "-1") {
            error = "Invalid characters in your zip code.  Please try again.\n";
        }
        if ((hyphencount > 1) || ((field.length == 10) && "" + field.charAt(5) != "-")) {
            error = "The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'. Please try again.\n";
        }
    }
    if (field == '00000-0000') {
        error = "Invalid zip code.\n";
    } else if (field == '00000') {
        error = "Invalid zip code.\n";
    }
    if (error.length > 0) {} else {
        fld.style.background = 'none';
    }
    return error;
}

function enlarge(el) {
    alternates = el.parentNode.parentNode.getElementsByTagName('div');
    for (i = 0; i < alternates.length; i++) alternates[i].className = 'alternate';
    el.parentNode.className = 'alternate enlarged';
    document.getElementById('largeimg').src = el.getAttribute('largefiles');
    document.getElementById('largeimg').srcdd = el.getAttribute('largefiles');
    document.getElementById('txt_img').value = "";
}

function myPopup2() {
    var hid = document.getElementById('txt_img').value;
    OpenWindow = window.open("", "newwin", "toolbar=no,scrollbars=1 ,menubar=no,resizable = 1,width=1024,height=800");
    OpenWindow.moveTo(0, 0);
    var htmla = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">';
    OpenWindow.document.write(htmla)
    OpenWindow.document.write("<BODY style='overflow:scroll;'>")
    if (hid == "") {
        OpenWindow.document.write("<table><tr><td><img src='" + document.getElementById('largeimg').srcdd + "' /></td></tr>")
    } else {
        OpenWindow.document.write("<div><img src='" + document.getElementById('txt_imgs').value + "' /></div>")
    }
    OpenWindow.document.write("</BODY>")
    OpenWindow.document.write("</HTML>")
    OpenWindow.document.close()
    self.name = "main"
}

function suc() {
    window.close();
}

function phone_focus() {
    if (document.getElementById('billPhone1').value.length == 3) {
        document.getElementById('billPhone2').focus();
    }
}

function phone_focus1() {
    if (document.getElementById('billPhone2').value.length == 3) {
        document.getElementById('billPhone3').focus();
    }
}

function google_phone() {
    if (document.getElementById('shipphone1').value.length == 3) {
        document.getElementById('shipphone2').focus();
    }
}

function google_phone1() {
    if (document.getElementById('shipphone2').value.length == 3) {
        document.getElementById('shipphone3').focus();
    }
}

function popup_terms(url) {
    newwindow = window.open(url, 'name', 'height=200,width=250,scrollbars=yes');
    if (window.focus) {
        newwindow.focus()
    }
    return false;
}

function numberchk(phnos) {
    var phno = phnos.value;
    var ls = phno.substr(phno.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = phno.substr(0, phno.length - 1)
        document.getElementById('shipPhone1').value = newval;
    } else if (document.getElementById('shipPhone1').value.length == 3) {
        document.getElementById('shipPhone2').focus();
    }
}

function numberchk1(phnos) {
    var phno = phnos.value;
    var ls = phno.substr(phno.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = phno.substr(0, phno.length - 1)
        document.getElementById('shipPhone2').value = newval;
    } else if (document.getElementById('shipPhone2').value.length == 3) {
        document.getElementById('shipPhone3').focus();
    }
}

function numberchk2(phnos) {
    var phno = phnos.value;
    var ls = phno.substr(phno.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = phno.substr(0, phno.length - 1)
        document.getElementById('shipPhone3').value = newval;
    }
}

function numberchkCD1(phnos) {
    var phno = phnos.value;
    var ls = phno.substr(phno.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = phno.substr(0, phno.length - 1)
        document.getElementById('billPhone1').value = newval;
    } else if (document.getElementById('billPhone1').value.length == 3) {
        document.getElementById('billPhone2').focus();
    }
}

function numberchkCD2(phnos) {
    var phno = phnos.value;
    var ls = phno.substr(phno.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = phno.substr(0, phno.length - 1)
        document.getElementById('billPhone2').value = newval;
    } else if (document.getElementById('billPhone2').value.length == 3) {
        document.getElementById('billPhone3').focus();
    }
}

function numberchkCD3(phnos) {
    var phno = phnos.value;
    var ls = phno.substr(phno.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = phno.substr(0, phno.length - 1)
        document.getElementById('billPhone3').value = newval;
    }
}

function numberchkRG1(phnos) {
    var phno = phnos.value;
    if (document.getElementById('phone1').value.length == 3) {
        document.getElementById('phone1').value = phno;
        document.getElementById('phone2').focus();
    }
}

function numberchkRG2(phnos) {
    var phno = phnos.value;
    if (document.getElementById('phone2').value.length == 3) {
        document.getElementById('phone2').value = phno;
        document.getElementById('phone3').focus();
    }
}

function numberchkRG3(phnos) {
    var phno = phnos.value;
    if (document.getElementById('phone3').value.length == 4) {
        document.getElementById('phone3').value = phno;
    }
}

function numberchkpaypal1(phnos) {
    var phno = phnos.value;
    if (document.getElementById('shipphone1').value.length == 3) {
        document.getElementById('shipphone1').value = phno;
        document.getElementById('shipphone2').focus();
    }
}

function numberchkpaypal2(phnos) {
    var phno = phnos.value;
    if (document.getElementById('shipphone2').value.length == 3) {
        document.getElementById('shipphone2').value = phno;
        document.getElementById('shipphone3').focus();
    }
}

function numberchkpaypal3(phnos) {
    var phno = phnos.value;
    if (document.getElementById('shipphone3').value.length == 4) {
        document.getElementById('shipphone3').value = phno;
    }
}

function paynumberchk(phnos) {
    var phno = phnos.value;
    var ls = phno.substr(phno.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = phno.substr(0, phno.length - 1)
        document.getElementById('billPhone1').value = newval;
    } else if (document.getElementById('billPhone1').value.length == 3) {
        document.getElementById('billPhone2').focus();
    }
}

function paynumberchk1(phnos) {
    var phno = phnos.value;
    var ls = phno.substr(phno.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = phno.substr(0, phno.length - 1)
        document.getElementById('billPhone2').value = newval;
    } else if (document.getElementById('billPhone2').value.length == 3) {
        document.getElementById('billPhone3').focus();
    }
}

function paynumberchk2(phnos) {
    var phno = phnos.value;
    var ls = phno.substr(phno.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = phno.substr(0, phno.length - 1)
        document.getElementById('billPhone3').value = newval;
    }
}

function numberchk3(phnos) {
    var phno = phnos.value;
    var ls = phno.substr(phno.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = phno.substr(0, phno.length - 1)
        document.getElementById('shipphone1').value = newval;
    }
}

function numberchk4(phnos) {
    var phno = phnos.value;
    var ls = phno.substr(phno.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = phno.substr(0, phno.length - 1)
        document.getElementById('shipphone2').value = newval;
    }
}

function numberchk5(phnos) {
    var phno = phnos.value;
    var ls = phno.substr(phno.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = phno.substr(0, phno.length - 1)
        document.getElementById('shipphone3').value = newval;
    }
}

function paypalChecktoutValidate(frm) {
    var elem = document.getElementById(frm).elements;
    var shipmethodval = document.getElementById('shipMethod').value;
    var reason = "";
    var validZip = "";
    var validShipPhone = "";
    var str = 'Following required field has not been filled in.\n\n';
    for (var i = 0; i < elem.length; i++) {
        if ((elem[i].type == 'text')) {
            if ((elem[i].id != 'shipCompany') && (elem[i].id != 'shipphone1') && (elem[i].id != 'shipAddress2') && (elem[i].id != 'shipphone2') && (elem[i].id != 'shipphone3')) {
                reason += validategoogleEmpty(document.getElementById(elem[i].id));
                if (reason != "") reason = reason.replace("The required field", elem[i].title);
            }
            if ((elem[i].name == 'shipzip') && (elem[i].value.length != 0)) {
                validZip = validateZipCodess(elem[i]);
            }
        }
        if (elem[i].name == 'shipstate' && (elem[i].value == 0)) {
            reason += "Please select a " + elem[i].title + "\n";
        } else if (elem[i].name == 'shipstate' && (elem[i].value != 0)) {
            elem[i].style.background = 'none';
        }
    }
    validShipPhone = validatePhoneFields('shipphone');
    reason += validZip + validShipPhone;
    if (reason != "") {
        str += reason;
        alert(str);
        return false;
    }
    if (shipmethodval == '') {
        alert("Please Select Shipping Method");
        document.getElementById('shipMethod').style.background = 'Yellow';
        return false;
    }
    return true;
}

function updateGoogleShippingCharge() {
    var limit = parseInt('5');
    var text = $('input#shipzip').val();
    var chars = text.length;
    if (chars >= limit) {
        $("#updateShippingCharge").load('/loadshipmethod', {
            zipCode: $('input#shipzip').val(),
            shipMethod: $('input#hiddenshipmethod').val()
        });
    }
}

function updateGoogleShippingCharge1() {
    var limit = parseInt('5');
    var text = $('input#shipzip').val();
    var chars = text.length;
    if (chars >= limit) {
        $("#updateShippingCharge").load('/loadshipmethod', {
            zipCode: $('input#shipzip').val(),
            paypalloadship: $('input#paypalloadship').val(),
            shipMethod: $('input#hiddenshipmethod').val(),
            cart_session_id: $('input#cart_session_id').val()
        });
    }
}

function updateGoogleShippingChargeload(shipid) {
    var limit = parseInt('5');
    var text = $('input#shipzip').val();
    var chars = text.length;
    if (chars >= limit) {
        $("#updateShippingCharge").load('/loadshipmethod', {
            zipCode: $('input#shipzip').val(),
            paypalloadship: $('input#paypalloadship').val(),
            cart_session_id: $('input#cart_session_id').val(),
            shipMethod: shipid
        });
    }
}

function doPrintReceipt(orderNo, size_post) {
    jQuery(document).ready(function () {
        newWindow = window.open("/printreceipt?orderno=" + orderNo + "&" + size_post, "OrderedInformation", "menubar=1, resizable=1, width=920, height=900, scrollbars=yes");
        newWindow.moveTo(0, 0);
        newWindow.focus();
    });
}

function zooming(adiv, id, i) {
    document.getElementById('samples' + i).src = id;
    document.getElementById('sample' + i).style.visibility = "visible";
}

function zoomout(adiv, i) {
    document.getElementById('sample' + i).style.visibility = "hidden";
}

function newsletter() {
    var reason = "";
    reason += validatetextfieldsnews($("#firstname").val(), 'First Name');
    reason += validatetextfieldsnews($("#lastname").val(), 'Last Name');
    reason += validatenewsEmail($("#Email").val(), 'Email')
    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
        return false;
    }
    $.post("/newsletter", {
        firstname: $('#firstname').val(),
        lastname: $('#lastname').val(),
        Email: $('#Email').val()
    }, function (data) {
        if (document.getElementById("newsletteremail")) {
            document.getElementById("newsletteremail").innerHTML = data;
            document.getElementById("firstname").value = "";
            document.getElementById("lastname").value = "";
            document.getElementById("Email").value = "";
        }
    });
    return true;
}

function validatetextfieldsnews(fld, fldname) {
    var error = "";
    var illegalChars = /[\W_]/;
    if (fld == "") {
        error = " : You didn't enter any text.\n";
    } else if (illegalChars.test(fld)) {
        var error = "";
        error = " :The Text Field contains illegal characters.\n";
    }
    if (error == "") {
        return error;
    } else {
        names = fldname;
        error = names + error;
    }
    return error;
}

function validatenewsEmail(fld, fldname) {
    var error = "";
    var tfld = trimchk(fld);
    var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
    if (tfld == "") {
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfld)) {
        error = "Please enter a valid email address.\n";
    } else if (fld.match(illegalChars)) {
        error = "The email address contains illegal characters.\n";
    }
    return error;
}

function showdiv() {
    document.getElementById("sign_info").style.visibility = "visible";
    document.getElementById("sign_info").style.position = "static";
}

function hidediv() {
    document.getElementById("sign_info").style.visibility = "hidden";
    document.getElementById("sign_info").style.position = "absolute";
}

function clearform() {}

function showdiv1() {
    document.getElementById("shipping_add").style.visibility = "visible";
    document.getElementById("shipping_add").style.position = "static";
}

function hidediv1() {
    document.getElementById("shipping_add").style.visibility = "hidden";
    document.getElementById("shipping_add").style.position = "absolute";
}

function showdiv2() {
    document.getElementById("payment_info").style.visibility = "visible";
    document.getElementById("payment_info").style.position = "static";
}

function hidediv2() {
    document.getElementById("payment_info").style.visibility = "hidden";
    document.getElementById("payment_info").style.position = "absolute";
}

function showdiv3() {
    document.getElementById("ship_edit").style.visibility = "visible";
    document.getElementById("ship_edit").style.position = "static";
    document.getElementById("name_dtl").style.visibility = "hidden";
    document.getElementById("name_dtl").style.position = "absolute";
}

function hidediv3() {
    document.getElementById("ship_edit").style.visibility = "hidden";
    document.getElementById("ship_edit").style.position = "absolute";
    document.getElementById("name_dtl").style.visibility = "visible";
    document.getElementById("name_dtl").style.position = "static";
}

function auto(marketname, marketid) {
    document.getElementById("schoolname").value = marketname;
    document.getElementById("marketid").value = marketid;
    document.getElementById("autosuggest").style.display = "none";
}

function Autosuggestsearch() {
    $.post("/autosuggestsearch", {
        searchval: $('#schoolname').val()
    }, function (data) {
        if (data == 1) {
            document.getElementById("fail").innerHTML = "Please contact info@swathijewelleries.com to add school.";
        } else if (data == 2) {
            document.getElementById("fail").innerHTML = "";
        } else {
            document.getElementById("autosuggest").innerHTML = data;
            document.getElementById("autosuggest").style.display = "block";
            document.getElementById("fail").innerHTML = "";
        }
        setInterval('updatedivnone()', 40000);
    });
}

function updatedivnone() {
    document.getElementById("autosuggest").style.display = "none";
}

function chgst() {
    document.getElementById('selExpMonth').focus();
}

function chgst2() {
    document.getElementById('selExpYear').focus();
}

function chgst3() {
    document.getElementById('txtCardVerificationValue').focus();
}

function searchAction() {
    var q = document.getElementById('search-text').value;
    if (q == '') {
        alert('Please enter valid data');
        document.getElementById('search-text').style.background = 'Yellow';
        document.getElementById('search-text').focus();
        return false;
    }
    document.search.submit();
    return true;
}

function validateEmails(fld) {
    var error = "";
    var tfld = trimchk(fld.value);
    var emailFilter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
    if (tfld == "") {
        error = "Email address cannot be empty \n";
    } else if (!emailFilter.test(tfld)) {
        error = "Please enter a valid email address \n";
    } else if (fld.value.match(illegalChars)) {
        error = "The email address contains illegal characters \n";
    } else {
        var st;
        fld.style.background = 'none';
    }
    return error;
}

function NumberKey(evt, id) {
    var str = evt
    var charCode = "";
    for (i = 0; i < str.length; i++) {
        charCode = parseInt(str.charCodeAt(i));
        if (!((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122))) {
            alert("Password should not contain special characters");
            document.getElementById(id).value = '';
            break;
        }
    }
}

function validateforgetpasswdFormOnSubmit(theForm) {
    var reason = "";
    reason += validateEmails(theForm.loginemail);
    if (reason != "") {
        alert("Before submitting, please correct the following:\n\n" + reason);
        return false;
    }
    return true;
}

function validateEmpty(tfld, flds) {
    var error = "";
    var fld = trimchk(tfld.value);
    if (fld.length == 0) {
        error = flds + " cannot be empty\n"
    }
    if (tfld.type == 'select-one') {
        if (tfld == 0) {
            error = "The required field has not been filled in\n"
        }
    }
    return error;
}

function phoneCheck(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) return false;
    return true;
}

function numberchkSP1(ph) {
    var id = ph.id;
    var len = id.length;
    var phno = ph.value;
    var phid = id.substring(0, len - 1);
    var index = parseInt(id.substring(len - 1, len));
    if (document.getElementById(phid + index).value.length == 3) {
        document.getElementById(phid + index).value = phno;
        if (index != 3) document.getElementById(phid + (index + 1)).focus();
    }
}

function cellphone1() {
    var cphno1 = document.getElementById('phone1').value;
    var ls = cphno1.substr(cphno1.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = cphno1.substr(0, cphno1.length - 1)
        document.getElementById('phone1').value = newval;
    } else if (document.getElementById('phone1').value.length == 3) {
        document.getElementById('phone2').focus();
    }
}

function cellphone2() {
    var cphno2 = document.getElementById('phone2').value;
    var ls = cphno2.substr(cphno2.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = cphno2.substr(0, cphno2.length - 1)
        document.getElementById('phone2').value = newval;
    } else if (document.getElementById('phone2').value.length == 3) {
        document.getElementById('phone3').focus();
    }
}

function cellphone3() {
    var cphno3 = document.getElementById('phone3').value;
    var ls = cphno3.substr(cphno3.length - 1, 1);
    var chk = ls.charCodeAt(0);
    if (!(chk >= 48 && chk <= 57) || (chk == 32)) {
        var newval = cphno3.substr(0, cphno3.length - 1)
        document.getElementById('phone3').value = newval;
    }
}

function NumberKey(evt, id) {
    var str = evt
    var charCode = "";
    for (i = 0; i < str.length; i++) {
        charCode = parseInt(str.charCodeAt(i));
        if (!((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122))) {
            alert("Password should not contain special characters");
            document.getElementById(id).value = '';
            break;
        }
    }
}
