﻿/// <reference path="jquery-vsdoc.js" />
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };

$(document).ready(function() {
    if (window.location.href.toString().toLowerCase().indexOf("https://") > -1 ||
    window.location.href.toString().toLowerCase().indexOf("localhost") > -1 ||
    window.location.href.toString().toLowerCase().indexOf("/abc/") > -1) {
        if (window.location.href.toString().toLowerCase().indexOf("slogin=true") > -1) {
            modalLogin();
        } else if (window.location.href.toString().toLowerCase().indexOf("orderhistory.aspx") > -1) {
            if ($('#ctl00_divUserName').text().trim() == "") {
                modalAuthentication();
            }
        }
    }
    populatePersonalInfo();
    $.get("ajxGetLoginInfo.aspx", { "dts": (new Date()).toString() }, function(data) {
        if (data.split("(;|;)")[0] == "") {
            $('#ctl00_ancLogin').text("Login").bind("click", modalLogin);
            if (window.location.href.indexOf("accountEdit.aspx") > -1)
                window.location.href = "accountCreate.aspx";
            if (window.location.href.indexOf("groupCarts.aspx") > -1)
                window.location.href = "Default.aspx";
            if (window.location.href.indexOf("deptCarts.aspx") > -1)
                window.location.href = "Default.aspx";
        } else {
            $('#ctl00_ancLogin').text("Logout").bind("click", abcLogout);
            if (window.location.href.indexOf("accountCreate.aspx") > -1)
                window.location.href = "accountEdit.aspx";
        }
    });

    if (window.location.href.toString().toLowerCase().indexOf("orderhistory.aspx") > -1) {
    }
});

var dlgLogin = null;
function modalLogin() {
    var slocation = window.location.href.toString().toLowerCase();
    if (slocation.indexOf("http://") > -1 && slocation.indexOf('slogin=') == -1) {
        if (slocation.indexOf("localhost") == -1 && slocation.indexOf("/abc/") == -1) {
            var slocation = slocation.replace("http://", "https://");
        }
        slocation = slocation.replace("#", "");
        slocation = slocation.replace("default.aspx", "Default.aspx");   // don't ask
        if (slocation.indexOf(".aspx") == -1) {
            if (slocation.substr(slocation.length - 1) != "/") {
                slocation = slocation + "/";
            }
            slocation = slocation + "Default.aspx";
        }
        if (slocation.indexOf("slogin=true") == -1) {
            if (slocation.indexOf("?") > -1) {
                slocation += "&slogin=true";
            } else {
                slocation += "?slogin=true";
            }
        }
        window.location.href = slocation;
        return;
    }
    $("#dlgLogin").keypress(processLogin);
    $("#divLogout").css("display", "none").css("height", "100px")
    $("#tdLoginid").text("Login ID:");
    $("#tdPassword").text("Password:");
    var dlg = $('#dlgLogin').dialog({ modal: true, minHeight: 200 });   // creating then closing the dialog box is a fix for the initial load
    dlg.dialog('close');                                                // of the dialog box that appears with a reaaly big height
    dlg.dialog('option', 'buttons', {
        "Cancel": function() {
            $(this).dialog("destroy");
            var slocation = window.location.href.toString().toLowerCase().replace("https://", "http://").replace("slogin=true", "slogin=false");
            window.location.href = slocation;
        },
        "OK": function() {
            abcLogin();
            $(this).dialog("destroy");
        }
    });
    dlgLogin = dlg;
    dlg.dialog('option', 'title', 'Log in');
    dlg.dialog('open');
}

function modalAuthentication() {
    if (window.location.href.toString().toLowerCase().indexOf("http://") > -1 && (window.location.href.toString().toLowerCase().indexOf("localhost")) == -1) {
        var slocation = window.location.href.toString().toLowerCase().replace("http://", "https://");
        slocation = slocation.replace("#", "");
        if (slocation.indexOf(".aspx") == -1) {
            if (slocation.substr(slocation.length - 1) != "/") {
                slocation = slocation + "/";
            }
            slocation = slocation + "Default.aspx";
        }
        window.location.href = slocation;
        return;
    }
    $("#dlgLogin").keypress(processLogin);
    $("#divLogout").css("display", "none").css("height", "100px")
    $("#tdLoginid").text("Account:");
    $("#tdPassword").text("Email:");
    var dlg = $('#dlgLogin').dialog({ modal: true, bgiframe: true, resizeable: true, width: 330, minHeight: 200 });
    dlg.dialog('close');  // creating then closing the dialog box is a fix for the initial load of the dialog box that appears with a height that is too big
    dlg.dialog('option', 'buttons', {
        "Cancel": function() { cancelAuthenticationDialog(this); },
        "OK": function() {
            abcLogin();
            $(this).dialog("destroy");
        }
    });
    dlg.bind('dialogclose', function() { cancelLoginDialog(this); });
    dlgLogin = dlg;
    dlg.dialog('option', 'title', 'School Authentication');
    dlg.dialog('open');
}

function cancelAuthenticationDialog(obj) {
    $(obj).dialog("destroy");
    window.location = (window.location.href.toString().indexOf("adamsbook.com") == -1 ? "/adamsbook" : "") + "/Default.aspx";
}

function abcLogin() {
    var dataPulled;
    var loggedIn = false;
    $.get("ajxLogin.aspx", { "loginid": $("#ctl00_txtLoginid").val(), "loginname": $("#ctl00_txtLoginid").val(), "password": $("#ctl00_txtPassword").val(), 'dts': (new Date()).toString() }, function(data) {
        dataPulled = data.split(',');
        loggedIn = (dataPulled[1].trim() != "")
        updatePersonalInfo(dataPulled[0], dataPulled[1]);

        if (dataPulled[3].indexOf("g") > -1) {
            $("#ctl00_liGroupCarts").css("display", "");
        } else if (dataPulled[3].indexOf("d") > -1) {
            $("#ctl00_liDeptCarts").css("display", "");
        }

        if (loggedIn) {
            $('#ctl00_ancLogin').text("Logout").unbind("click", modalLogin).bind("click", abcLogout);
            if (window.location.href.indexOf("cart.aspx") > -1)
                window.location.reload();
            if (window.location.href.indexOf("accountCreate.aspx") > -1)
                window.location.href = "accountEdit.aspx";
        } else {
            $("#ctl00_divUserName").css("color", "#AA0000").text("Login Failed...")
            .fadeOut(80).fadeIn(80)
            .fadeOut(80).fadeIn(80)
            .fadeOut(80).fadeIn(80)
            .fadeOut(80).fadeIn(80)
            .fadeOut(80).fadeIn(80)
            .fadeOut(80).fadeIn(80)
            .fadeOut(80).fadeIn(80)
            .fadeOut(80).fadeIn(80)
            .fadeOut(80).fadeIn(80)
            .fadeOut(80).fadeIn(80)
            .fadeOut(80).fadeIn(80)
            .fadeOut(80).fadeIn(80)
            .fadeOut(80).fadeIn(80)
            .fadeOut(1500);
            abcLogout();
        }
    });
    if (!(window.location.href.indexOf("accountcreate.aspx") > -1 ||
		  window.location.href.indexOf("accountedit.aspx") > -1 ||
		  window.location.href.indexOf("accountupdate.aspx") > -1 ||
		  window.location.href.indexOf("checkoutprofile.aspx") > -1 ||
		  window.location.href.indexOf("orderconfirmation.aspx") > -1 ||
		  window.location.href.indexOf("printerpage.aspx") > -1 ||
		  window.location.href.indexOf("orderhistory.aspx") > -1)
        ) {

        $().ajaxStop(function() {
            var slocation = window.location.href.toString().toLowerCase().replace("https://", "http://").replace("slogin=true", "slogin=false");
            slocation = slocation.replace("default.aspx", "Default.aspx");
            window.location.href = slocation;
        });
    }
}

function updatePersonalInfo(accountid, ticket) {
    $.get('ajxGetLoginInfo.aspx', { 'accountid': accountid, 'ticket': ticket, 'dts': (new Date()).toString() }, function(data) { // data = <fullname>, <cart total>, <item count>
        var dvUsrNm = $('#ctl00_divUserName');
        if (dvUsrNm.text() != "Login Failed..." || data.split('(;|;)')[0].trim() != "") {
            dvUsrNm.fadeIn(100).css("color", "#000000").html(data.split('(;|;)')[0]);
            dvUsrNm.fadeIn(100).css("color", "#000000").html(data.split('(;|;)')[0]); // this is repeated because the username sometimes does not get populated, forcing it like this seems to work
        }
        $('#ctl00_divCartInfo').html('<a href="javascript:goToPage(\'cart.aspx\');">Shopping Cart</a>&nbsp;|&nbsp;Total: $' + data.split('(;|;)')[1].trim() + '&nbsp;|&nbsp;Items: ' + data.split('(;|;)')[2].trim());
    });
}

function abcLogout() {
    $.get('ajxLogout.aspx', { 'dts': (new Date()).toString() }, function(data) {
        if (data.toLowerCase() == "true") {
            if ($('#ctl00_divUserName').text() != "Login Failed...")
                $('#ctl00_divUserName').html("");
            $('#ctl00_divCartInfo').html('<a href="cart.aspx">Shopping Cart</a>&nbsp;|&nbsp;Total: $0.00&nbsp;|&nbsp;Items: 0');
            $('#ctl00_ancLogin').text("Login").unbind('click', abcLogout).bind('click', modalLogin);
            if (window.location.href.indexOf("cart.aspx") > -1)
                window.location.reload();
            if (window.location.href.indexOf("accountEdit.aspx") > -1)
                window.location.href = "accountCreate.aspx";
        } else {
            var dvUsrNm = $('#ctl00_divUserName');
            var repopulateCode = '$("#ctl00_divUserName").css("color", "#000000").html("' + dvUsrNm.text() + '").fadeIn(1);';
            dvUsrNm.css("color", "#AA0000")
                   .html("Logout failed.  Please try again.")
                   .fadeOut(80).fadeIn(80)
                   .fadeOut(80).fadeIn(80)
                   .fadeOut(80).fadeIn(80)
                   .fadeOut(80).fadeIn(80)
                   .fadeOut(80).fadeIn(80)
                   .fadeOut(80).fadeIn(80)
                   .fadeOut(80).fadeIn(80)
                   .fadeOut(80).fadeIn(80)
                   .fadeOut(80).fadeIn(80)
                   .fadeOut(80).fadeIn(80)
                   .fadeOut(80).fadeIn(80)
                   .fadeOut(80).fadeIn(80)
                   .fadeOut(80).fadeIn(80)
                   .fadeOut(500);
            setTimeout(repopulateCode, 3600);
        }
        if (dlgLogin !== null) {
            dlgLogin.dialog('destroy');
            dlgLogin = null;
        }
    });
    $().ajaxStop(function() {
        if (window.location.href.toString().toLowerCase().indexOf("accountedit.aspx") > -1)
            window.location.href = "https://www.adamsbook.com/accountCreate.aspx";
            
        if (window.location.href.toString().toLowerCase().indexOf("groupcarts.aspx") > -1)
            window.location.href = "http://www.adamsbook.com/Default.aspx";
            
        if (window.location.href.toString().toLowerCase().indexOf("deptcarts.aspx") > -1)
            window.location.href = "http://www.adamsbook.com/Default.aspx";

        if ($("#ctl00_divUserName").text().toString().trim() == "") {
            $("#ctl00_anchAccountCreate").attr("href", "accountCreate.aspx").css("color", "#f5f5f5");
            $("#ctl00_anchAccountEdit").attr("href", "#").css("color", "#999999");
            $("#ctl00_liGroupCarts").css("display", "none");
            $("#ctl00_liDeptCarts").css("display", "none");
        } else {
            $("#ctl00_anchAccountCreate").attr("href", "#").css("color", "#999999");
            $("#ctl00_anchAccountEdit").attr("href", "accountEdit.aspx").css("color", "#f5f5f5");
        }
    });
}

function populatePersonalInfo() {
    $.get('ajxGetLoginInfo.aspx', { 'dts': (new Date()).toString() }, function(data) {        // data = <fullname>, <cart total>, <item count>
        $('#ctl00_divUserName').css("color", "#000000").html(data.split('(;|;)')[0]);
        $('#ctl00_divCartInfo').html('<a href="javascript:goToPage(\'cart.aspx\');">Shopping Cart</a>&nbsp;|&nbsp;Total: $' + data.split('(;|;)')[1].trim() + '&nbsp;|&nbsp;Items: ' + data.split('(;|;)')[2].trim());
    });
}

function processLogin(evt) {
    var characterCode;
    if (evt && evt.which) { //if which property of event object is supported (NN4)
        evt = evt;
        characterCode = evt.which; //character code is contained in NN4's which property
    } else {
        evt = event;
        characterCode = evt.keyCode; //character code is contained in IE's keyCode property
    }
    if (characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
        if (dlgLogin != null) {
            abcLogin();
            dlgLogin.dialog("destroy");
            dlgLogin = null;
        }
    }
}

function refresh() {
    var xhr = createXhr();
    xhr.onreadystatechange = processCheckLoginStatusResponse;
    var fname = document.getElementById("fullname").innerText;
    xhr.open("GET", "accountGetItems.aspx?action=checkLoginStatus&fieldvalue=" + fname + '&dts=' + new Date().toString());
    xhr.send(null);

    function processCheckLoginStatusResponse() {
        if (xhr.readyState == 4) {
            var answer = xhr.responseText;
            xhr.close;
            if (answer === "reload") {
                window.location.reload();
            }
        }
    }
}

function setupRefresh() {
    document.getElementById('mainBody').setAttribute('onunload', "setTimeout('refresh()', 500);");
}

function isDigitKeyPress(e) {
    var key = window.event ? e.keyCode : e.which;
    var keychar = String.fromCharCode(key);
    reg = /\d/;
    return reg.test(keychar);
}

function isZipKeyPress(e) {
    var key = window.event ? e.keyCode : e.which;
    var keychar = String.fromCharCode(key);
    reg = /\d|-/;
    return reg.test(keychar);
}

function setPageFocus(objName) {
    var obj = document.getElementById(objName);
    if (obj.getAttribute("disabled") == null)
        setTimeout(obj.focus(), 1);
}

function createXhr() {
    var xhr;
    try {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e1) {
        try {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e2) {
            xhr = false;
        }
    }
    if (!xhr && typeof XMLHttpRequest != "undefined") {
        xhr = new XMLHttpRequest()
    }
    return xhr;
}

function login(msg) {
    var winW = 630, winH = 460;

    if (parseInt(navigator.appVersion) > 3) {
        if (navigator.appName == "Netscape") {
            winW = window.innerWidth;
            winH = window.innerHeight;
        }
        if (navigator.appName.indexOf("Microsoft") != -1) {
            winW = document.body.offsetWidth;
            winH = document.body.offsetHeight;
            if (winH === 0)
                winH = 460;
        }
    }

    loginPrompt(msg, winW / 3, winH / 3, false);
}

function logout() {
    window.location = "accountLogout.aspx?page=" + document.location;
}

function cancelLogin() {
    document.getElementById("popupDiv").parentNode.removeChild(document.getElementById("popupDiv"));
    if (goBack) history.back();
    var fullUrl = window.location.href;
    var urlParams = window.location.search;
    var noParamUrl = fullUrl.replace(urlParams, "");
    window.location.replace(noParamUrl);
}

function doAction() {
    if (window.location.toString().indexOf("login=failed") > -1) {
        login("Incorrect login and/or password");
    }
}

function createAccount(evt) {
    if (validateAccountInfo(evt, true))
        document.getElementById("aspnetForm").submit();
}

function saveAccountEdits(evt) {

    var clickX;
    var clickY;
    if (navigator.appName == "Microsoft Internet Explorer") {
        clickX = window.event.clientX + document.documentElement.scrollLeft;
        clickY = window.event.clientY + document.documentElement.scrollTop;
    } else {
        clickX = evt.pageX;
        clickY = evt.pageY;
    }

    if (validateAccountInfo(evt, true)) {
        document.getElementById("mainForm").submit();
    }
}

function validateAccountInfo(evt, validate_Email) {
    var clickX;
    var clickY;
    if (navigator.appName == "Microsoft Internet Explorer") {
        clickX = window.event.clientX + document.documentElement.scrollLeft;
        clickY = window.event.clientY + document.documentElement.scrollTop;
    } else {
        clickX = evt.pageX;
        clickY = evt.pageY;
    }

    var errorStr = "";
    errorStr += validateFirstName(document.getElementById("ctl00_cphBody_txtFirstName").value);
    errorStr += validateLastName(document.getElementById("ctl00_cphBody_txtLastName").value);
    errorStr += validateOrgType(document.getElementById("ctl00_cphBody_lstOrgType").value);
    if (window.location.toString().indexOf("accountCreate.aspx") > -1)
        errorStr += validateLoginName(document.getElementById("ctl00_cphBody_txtLoginName").value);
    if (document.getElementById("ctl00_cphBody_txtPassword") !== null)
        errorStr += validatePassword(document.getElementById("ctl00_cphBody_txtPassword").value);
    if (validate_Email)
        errorStr += validateEmail(document.getElementById("ctl00_cphBody_txtEmail").value);
    errorStr += validatePhoneNumber(document.getElementById("ctl00_cphBody_txtPhone").value);
    errorStr += validateFax(document.getElementById("ctl00_cphBody_txtFax").value);
    errorStr += validateBillAddress1(document.getElementById("ctl00_cphBody_txtBillAddress1").value);
    errorStr += validateBillCity(document.getElementById("ctl00_cphBody_txtBillCity").value);
    errorStr += validateBillState(document.getElementById("ctl00_cphBody_lstBillState").value);
    errorStr += validateBillZip(document.getElementById("ctl00_cphBody_txtBillZip").value);
    errorStr += validateShipAddress1(document.getElementById("ctl00_cphBody_txtShipAddress1").value);
    errorStr += validateShipCity(document.getElementById("ctl00_cphBody_txtShipCity").value);
    errorStr += validateShipState(document.getElementById("ctl00_cphBody_lstShipState").value);
    errorStr += validateShipZip(document.getElementById("ctl00_cphBody_txtShipZip").value);

    if (errorStr.length > 0) {
        msgBox(errorStr, clickX, clickY);
        return false;
    }
    return true;
}

function validateFirstName(value) {
    if (value.trim() === "")
        return "\"First Name\" is required<br/>";
    else
        return "";
}

function validateLastName(value) {
    if (value.trim() === "")
        return "\"Last Name\" is required<br/>";
    else
        return "";
}

function validateOrgType(value) {
    if (value.trim() === "") {
        return "\"Type\" is required<br/>";
    } else {
        if (value.toLowerCase() !== "individual" && value.toLowerCase() !== "other...") {
            var retval = "";
            retval += validateOrganization(document.getElementById("ctl00_cphBody_txtOrg").value);
            return retval;
        } else
            return "";
    }
}

function validateOrganization(value) {
    if (value.trim() === "")
        return "\"Organization/School\" is required<br/>";
    else
        return "";
}

function validateEnrollment(value) {
    if (value == 0)
        return "\"Enrollment\" cannot be zero (0)<br/>";
    else
        return "";
}

function validateLowestGrade(value) {
    if (value.trim() === "")
        return "\"Lowest Grade\" is required<br/>";
    else {
        var lstLowestGrade = document.getElementById("ctl00_cphBody_lstLowestGrade");
        var grades = "";
        for (var i = 0; i < lstLowestGrade.options.length; i++)
            grades += "|" + lstLowestGrade.options[i].text + "|";
        if (grades.indexOf(value) == -1)
            return "\"Lowest Grade\" is invalid<br/>";
        else
            return "";
    }
}

function validateHighestGrade(value) {
    if (value.trim() === "")
        return "\"Highest Grade\" is required<br/>";
    else {
        var lstHighestGrade = document.getElementById("ctl00_cphBody_lstHighestGrade");
        var grades = "";
        for (var i = 0; i < lstHighestGrade.options.length; i++)
            grades += "|" + lstHighestGrade.options[i].text + "|";
        if (grades.indexOf(value) == -1)
            return "\"Highest Grade\" is invalid<br/>";
        else
            return "";
    }
}

function validateLastName(value) {
    if (value.trim() === "")
        return "\"Last Name\" is required<br/>";
    else
        return "";
}

function validateLoginName(value) {
    if (value.trim() === "")
        return "\"Login Name\" is required<br/>";
    else {
        $.get("accountGetItems.aspx", { "action": "checkLoginDupes", "fieldvalue": value, "dts": (new Date()).toString() }, function(data) {
            if (data.length > 0)
                return "\"Login Name\" already exists<br/>&nbsp;&nbsp;&nbsp;&nbsp;Please select a different \"Login Name\"<br/>";
        });
        return "";
    }
}

function validatePassword(value) {
    if (value.trim() === "") {
        return "\"Password\" is required<br/>";
    } else {
        if (value !== document.getElementById("ctl00_cphBody_txtConfirmPassword").value) {
            return "Password and its confirmation do not match<br/>";
        }
        return "";
    }
}

function validateEmail(value) {
    if (value.trim() !== "") {
        var regx = /^([\w]+)(([-\.][\w]+)?)*@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        if (!regx.test(value))
            return "Invalid Email address<br/>";
        else {
            $.get("accountGetItems.aspx", { "action": "checkEmailDupes", "fieldvalue": value, "dts": (new Date()).toString() }, function(data) {
                if (data.length > 0)
                    return "\"Email Address\" already exists<br/>&nbsp;&nbsp;&nbsp;&nbsp;Please select a different \"Login Name\"<br/>";
            });
            return "";
        }
    } else
        return "\"Email address\" is required<br/>";
}

function validatePhoneNumber(value) {
    if (value.trim() === "") {
        return "\"Phone Number\" is required<br/>";
    } else {
        var regx = /^((\+\d{1,3}(-| |\.)?\(?\d\)?(-| |\.)?\d{1,5})|(\(?\d{2,6}\)?))(-| |\.)?(\d{3,4})(-| |\.)?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
        if (!regx.test(value))
            return "Invalid Phone Number<br/>";
        else
            return "";
    }
}

function validateFax(value) {
    if (value.trim() !== "") {
        var regx = /^((\+\d{1,3}(-| |\.)?\(?\d\)?(-| |\.)?\d{1,5})|(\(?\d{2,6}\)?))(-| |\.)?(\d{3,4})(-| |\.)?(\d{4})$/;
        if (!regx.test(value))
            return "Invalid Fax Number<br/>";
        else
            return "";
    } else
        return "";
}

function validateBillAddress1(value) {
    var errStr = validateAddress1(value);
    if (errStr.trim() === "empty")
        return "\"Billing Address 1\" is required<br/>";
    else
        return "";
}

function validateBillCity(value) {
    var errStr = validateCity(value);
    if (errStr.trim() === "empty")
        return "\"Billing City\" is required<br/>";
    else
        return "";
}

function validateBillState(value) {
    var errStr = validateState(value);
    if (errStr.trim() === "empty")
        return "\"Billing State\" is required<br/>";
    else
        return "";
}

function validateBillZip(value) {
    var errStr = validateZip(value);
    if (errStr.trim() === "empty") {
        return "\"Billing Zip\" is required<br/>";
    } else {
        if (errStr.trim() === "invalid")
            return "\"Billing Zip\" is invalid<br/>";
        else
            return "";
    }
}

function validateBillCountry(value) {
    var errStr = validateCountry(value);
    if (errStr.trim() === "empty") {
        return "\"Billing Country\" is required<br/>";
    } else {
        if (errStr.trim() === "invalid")
            return "\"Billing Country\" is invalid<br/>";
        else
            return "";
    }
}

function validateShipAddress1(value) {
    var errStr = validateAddress1(value);
    if (errStr.trim() === "empty") {
        var shipSameAsBill = document.getElementById("ctl00_cphBody_chkSameAsBillingInfo").checked;
        var billAddress1 = document.getElementById("ctl00_cphBody_txtBillAddress1").value;
        if (shipSameAsBill) {
            if (validateAddress1(billAddress1).trim() === "empty")
                return "\"Shipping Address 1\" is required<br/>";
            else
                return "";
        } else
            return "\"Shipping Address 1\" is required<br/>";
    } else
        return "";
}

function validateShipCity(value) {
    var errStr = validateCity(value);
    if (errStr.trim() === "empty") {
        var shipSameAsBill = document.getElementById("ctl00_cphBody_chkSameAsBillingInfo").checked;
        var billCity = document.getElementById("ctl00_cphBody_txtBillCity").value;
        if (shipSameAsBill) {
            if (validateCity(billCity).trim() === "empty")
                return "\"Shipping City\" is required<br/>";
            else
                return "";
        } else
            return "\"Shipping City\" is required<br/>";
    } else
        return "";
}

function validateShipState(value) {
    var errStr = validateState(document.getElementById("ctl00_cphBody_lstBillState").value);
    if (errStr.trim() === "empty") {
        var shipSameAsBill = document.getElementById("ctl00_cphBody_chkSameAsBillingInfo").checked;
        var billState = document.getElementById("ctl00_cphBody_lstBillState").value;
        if (shipSameAsBill) {
            if (validateBillState(billState).trim() === "empty")
                return "\"Shipping State\" is required<br/>";
            else
                return "";
        } else
            return "\"Shipping State\" is required<br/>";
    } else {
        if (errStr.trim() === "invalid")
            return "\"Shipping State\" is invalid<br/>";
        else
            return "";
    }
}

function validateShipZip(value) {
    var errStr = validateZip(value);
    if (errStr.trim() === "empty") {
        var shipSameAsBill = document.getElementById("ctl00_cphBody_chkSameAsBillingInfo").checked;
        var billZip = document.getElementById("ctl00_cphBody_txtBillZip").value;
        if (shipSameAsBill) {
            if (validateBillZip(billZip).trim() === "empty")
                return "\"Shipping Zip\" is required<br/>";
            else
                return "";
        } else
            return "\"Shipping Zip\" is required<br/>";
    } else {
        if (errStr.trim() === "invalid")
            return "\"Shipping Zip\" is invalid<br/>";
        else
            return "";
    }
}

function validateShipCountry(value) {
    var errStr = validateCountry(value);
    if (errStr.trim() === "empty") {
        var shipSameAsBill = document.getElementById("ctl00_cphBody_chkSameAsBillingInfo").checked;
        var billCountry = document.getElementById("ctl00_cphBody_txtBillCountry").value;
        if (shipSameAsBill) {
            if (validateBillCountry(billCountry).trim() === "empty")
                return "\"Shipping Country\" is required<br/>";
            else
                return "";
        } else
            return "\"Shipping Country\" is required<br/>";
    } else {
        if (errStr.trim() === "invalid")
            return "\"Shipping Country\" is invalid<br/>";
        else
            return "";
    }
}

function validateAddress1(value) {
    if (value.trim() === "")
        return "empty";
    else
        return "";
}

function validateCity(value) {
    if (value.trim() === "")
        return "empty";
    else
        return "";
}

function validateState(value) {
    if (value.trim() === "")
        return "empty";

    var states = "";
    var lstStates = document.getElementById("ctl00_cphBody_lstBillState");

    for (var i = 0; i < lstStates.options.length; i++)
        states += "|" + lstStates.options[i].text + "|";

    if (states.indexOf("|" + value + "|") == -1)
        return "invalid";
    else
        return "";
}

function validateZip(value) {
    if (value.trim() === "")
        return "empty";
    else {
        var regx = /^(\d{5})(-\d{4})?$/;
        if (!regx.test(value))
            return "invalid";
        else
            return "";
    }
}

function validateCountry(value) {
    if (value.trim() === "empty") {
        return "empty";
    } else {
        value = value.toLowerCase();
        if (value !== "usa" && value !== "us" && value !== "u.s.a." && value !== "u.s." && value !== "u.s.a" && value !== "canada" && value !== "united states" && value !== "united states of america")
            return "invalid";
        else
            return "";
    }
}

function msgBox(msg, x, y) {
    $("#ctl00_cphBody_divErrors").html(msg).dialog({ modal: true }).dialog('option', 'buttons', {
        "OK": function() {
            $(this).dialog("close");
        }
    }).dialog('option', 'title', 'Attention Required').dialog('open');
}
