﻿$(document).ready(function() {

    if ($('#slider').length > 0) {
        $('#slider').nivoSlider({
        pauseTime: 5000,
        effect: 'sliceDown,sliceDownLeft,fold,fade,slideInRight,slideInLeft,boxRandom,boxRain,boxRainReverse,boxRainGrow,boxRainGrowReverse',
        afterLoad: function() {
            $('#slider div[class="nivo-controlNav"]').css("z-index", "9");
            $('#slider div[class="nivo-playPauseNav"]').css("z-index", "9");
        }
        });

        var numberOfSlides = $('#slider img').length;
        if (numberOfSlides == 1) {
            $('#slider').data('nivoslider').stop();
            $('#slider div[class="nivo-controlNav"]').css("display", "none");
            $('#slider div[class="nivo-playPauseNav"]').css("display", "none");
        }
        else {
            $('#slider').data('nivoslider').directionNav(true);
        }
    }

    if ($('#productUpSell') != undefined) {
        $('#productUpSell').click(addCartUpsell);
    }

    function addCartUpsell() {
        if ($('#cu_productId') != undefined) {
            var productId = $('#cu_productId').html();
            productId = productId.substring(productId.indexOf(':') + 1);
            __doPostBack('CartUpsell', productId);
        }
    }

    function ModalCloseMethods() {
        var backgroundElement = $get('MPEAddToCartConfirmBehavior_backgroundElement');
        if (backgroundElement) {
            $addHandler(backgroundElement, 'click', hideModalPopupViaClick);
            $addHandler(document, "keydown", hideModalPopupViaEsc);
        }
    }
    function hideModalPopupViaEsc(e) {
        if (e && e.keyCode == Sys.UI.Key.esc) {
            $find('MPEAddToCartConfirmBehavior').hide();
        }
    }
    function hideModalPopupViaClick() {
        $find('MPEAddToCartConfirmBehavior').hide();
    }
    Sys.Application.add_load(ModalCloseMethods);

    $('[id$="_AddToCartPopupError"] div.AddToCartDisabledImage').each(function() {
        $(this).qtip(
      {
          content: "<div id='AddToCartErrorPopupContent' style='font-weight:bold;text-align:center;'></div>",
          position: {
              corner: {
                  target: 'leftMiddle',
                  tooltip: 'rightMiddle'
              }
          },
          hide: {
              fixed: false
          },
          style: {
              width: 250,
              padding: 10,
              background: '#EAE8E5',
              color: '#ED1C24',
              border: {
                  width: 4,
                  radius: 3,
                  color: '#B0B0B0'
              },
              tip: true,
              name: 'blue' // Inherit the rest of the attributes from the preset dark style
          }
      });
    });

    // Use the each() method to gain access to each of the elements attributes
    $('#continuityContent img').each(function() {
        $(this).qtip(
      {
          content: '<div class="continuityToolTipHeader">Save Time and Money!</div><div class="continuityToolTip">Receive your refill at a designated frequency - <strong>Automatically</strong> and receive <strong>$2.00 shipping</strong>  on all Renew 2 You orders after your initial order</div>',
          position: {
              corner: {
                  target: 'rightMiddle',
                  tooltip: 'leftMiddle'
              }
          },
          hide: {
              fixed: true // Make it fixed so it can be hovered over
          },
          style: {
              width: 250,
              padding: 10,
              background: '#fff',
              color: 'black',
              border: {
                  width: 4,
                  radius: 3,
                  color: '#7B7462'
              },
              tip: 'leftMiddle',
              name: 'dark' // Inherit the rest of the attributes from the preset dark style
          }
      });
    });


    /// Created by:     Justin C Miller
    /// Created on:     2010-02-24
    /// Description:    Creates jquery popup window for Processing Fee 'whats this' on the Order Totals control
    ///  
    /// Updates:
    ///     Modified by:    
    ///     Modified on:    
    ///     Description:    
    $('#processingFeeWhatsThisDiv a').each(function() {
        $(this).qtip(
      {
          //content: '<div class="processingFeeWhatsThisToolTip">' + $('<div/>').html($("#ProcessingFeeWhatsThisPopupTextHiddenValue").val()).text() + ' <a href="' + $("#ProcessingFeeWhatsThisPopupTextMoreInfoLinkHiddenValue").val() + '">' + $("#ProcessingFeeWhatsThisPopupTextMoreInfoLinkTextHiddenValue").val() + '</a></div>',
          content: '<div class="processingFeeWhatsThisToolTip">' + $('<div/>').html($("#ProcessingFeeWhatsThisPopupTextHiddenValue").val()).text() + ' </div>',
          position: {
              corner: {
                  target: 'rightMiddle',
                  tooltip: 'leftMiddle'
              }
          },
          hide: {
              fixed: true // Make it fixed so it can be hovered over
          },
          style: {
              width: 180,
              padding: 5,
              background: '#fff',
              color: 'black',
              border: {
                  width: 3,
                  radius: 3,
                  color: '#7B7462'
              },
              tip: 'leftMiddle',
              name: 'dark' // Inherit the rest of the attributes from the preset dark style
          }
      });
    });

    /// Created by:     Justin C Miller
    /// Created on:     2010-02-25
    /// Description:    Creates jquery popup window for Shipping Total View Details on the Order Totals control
    ///  
    /// Updates:
    ///     Modified by:    
    ///     Modified on:    
    ///     Description:    
    $('#shippingTotalViewDetailsDiv a').each(function() {
        $(this).qtip(
      {
          //content: '<div class="shippingTotalViewDetailsToolTip">' + $('<div/>').html($("#shippingTotalViewDetailsPopupTextHiddenValue").val()).text() + ' <a href="' + $("#shippingTotalViewDetailsPopupTextMoreInfoLinkHiddenValue").val() + '">' + $("#shippingTotalViewDetailsPopupTextMoreInfoLinkTextHiddenValue").val() + '</a></div>',
          content: '<div class="shippingTotalViewDetailsToolTip">' + $('<div/>').html($("#shippingTotalViewDetailsPopupTextHiddenValue").val()).text() + ' </div>',
          position: {
              corner: {
                  target: 'rightMiddle',
                  tooltip: 'leftMiddle'
              }
          },
          hide: {
              fixed: true // Make it fixed so it can be hovered over
          },
          style: {
              width: 180,
              padding: 5,
              background: '#fff',
              color: 'black',
              border: {
                  width: 3,
                  radius: 3,
                  color: '#7B7462'
              },
              tip: 'leftMiddle',
              name: 'dark' // Inherit the rest of the attributes from the preset dark style
          }
      });
    });

    /// Created by:     Jason Umbreit
    /// Created on:     2010-12-02
    /// Description:    Creates a re-usable jquery popup window
    /// Reason:         Created for Work Order#3913 - EXP - Line Item Discount - Popup formatting
    ///                 but did not use
    /// 
    /// Updates:
    ///     Modified by:    
    ///     Modified on:    
    ///     Description:    
    $('.jQueryQtipPopupDiv a').each(function() {

        //value is the unique identifier for the id
        var name = this.nextSibling.name;

        $(this).qtip(
      {
          content: '<div class="jQueryQtipPopupToolTip">' + $('<div/>').html($("#jQueryQtipPopupValue_" + name).val()).text() + '</a></div>',
          position: {
              corner: {
                  target: 'rightMiddle',
                  tooltip: 'leftMiddle'
              }
          },
          hide: {
              fixed: true // Make it fixed so it can be hovered over
          },
          style: {
              width: 250,
              padding: 10,
              background: '#fff',
              color: 'black',
              border: {
                  width: 4,
                  radius: 3,
                  color: '#555'
              },
              tip: 'leftMiddle',
              name: 'dark' // Inherit the rest of the attributes from the preset dark style
          }
      });
    });

    function GetCurrentPageName() {
        var sPath = window.location.pathname;
        var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
        return sPage.toLowerCase()
    }

    if (GetCurrentPageName() == "specialoffers.aspx") {
        ProductValidation("SpecialOffersRepeater");
        if (GetCurrentPageName() == "specialoffers.aspx") {
            if ($("#SpecialOffersRepeater").length > 0) {
                var offersRepeater = document.getElementById('SpecialOffersRepeater');
                if (offersRepeater != null) {
                    var numOfDivs = offersRepeater.getElementsByTagName('div');
                    if (numOfDivs.length > 0) {
                        for (var i = 0; i < numOfDivs.length; i++) {
                            if (numOfDivs[i].id == 'AddToCartButtonContainer') {
                                numOfDivs[i].style.display = "none";
                            }
                        }
                    }
                }
            }
        }
    }
    else {
        ProductValidation("ProductItemContainer");
    }

    function ProductValidation(productContainer) {
        if ($(".AddToCartButton").length > 0) {
            var lastItemIndex;
            var productItemContainer = document.getElementById(productContainer);
            if (productItemContainer != null) {
                var numOfHorizontalRules = productItemContainer.getElementsByTagName('hr');

                if (numOfHorizontalRules.length > 0) {
                    for (var i = 0; i < numOfHorizontalRules.length; i++) {
                        if (numOfHorizontalRules[i].className == 'ProductDetailBreaks') {
                            lastItemIndex = i;
                        }
                    }
                    if (lastItemIndex != null) {
                        numOfHorizontalRules[lastItemIndex].className = 'noDisplay';
                    }
                }
            }
        }

        if ($('[id$="_CFG"]').length > 0) {
            var productItemContainer = document.getElementById(productContainer);
            if (productItemContainer != null) {
                var selectArray = productItemContainer.getElementsByTagName('select');
                for (var i = 0; i < selectArray.length; i++) {
                    if (selectArray[i].id.indexOf("CFG") != -1) {
                        $(selectArray[i]).change(function() {
                            enableDisableProductDetailItems(this);
                        });
                    }
                }
            }
        }

        if ($('[id$="_Size"]').length > 0) {
            var productItemContainer = document.getElementById(productContainer);
            if (productItemContainer != null) {
                var selectArray = productItemContainer.getElementsByTagName('select');
                for (var i = 0; i < selectArray.length; i++) {
                    if (selectArray[i].id.indexOf("Size") != -1) {
                        $(selectArray[i]).change(function() {
                            enableDisableProductDetailItems(this);
                        });
                    }
                }
            }
        }

        if ($('[id$="_Style"]').length > 0) {
            var productItemContainer = document.getElementById(productContainer);
            if (productItemContainer != null) {
                var selectArray = productItemContainer.getElementsByTagName('select');
                for (var i = 0; i < selectArray.length; i++) {
                    if (selectArray[i].id.indexOf("Style") != -1) {
                        var ddlCFG = $(selectArray[i]).closest("div.productDetailRepeaterItem").find('select[id$="_CFG"]');
                        var ddlSize = $(selectArray[i]).closest("div.productDetailRepeaterItem").find('select[id$="_Size"]');
                        if (ddlSize.length > 0 && ddlSize.get(0).selectedIndex == 0) {
                            $(selectArray[i]).attr("disabled", "disabled");
                        }
                        else if (ddlCFG.length > 0 && ddlCFG.get(0).selectedIndex == 0) {
                            $(selectArray[i]).attr("disabled", "disabled");
                        }
                        $(selectArray[i]).change(function() {
                            enableDisableProductDetailItems(this);
                        });
                    }
                }
            }
        }

        if ($('[id$="_ProductQtyTextBox"]').length > 0) {
            var productItemContainer = document.getElementById(productContainer);
            if (productItemContainer != null) {
                var inputArray = productItemContainer.getElementsByTagName('input');
                for (var i = 0; i < inputArray.length; i++) {
                    if (inputArray[i].type == "text" && inputArray[i].id.indexOf("ProductQtyTextBox") != -1) {
                        $(inputArray[i]).keyup(function() {
                            enableDisableProductDetailItems(this);
                        });
                        ValidateOnlyQuantityBox(inputArray[i]);
                    }
                }
            }
        }
    }

    function enableDisableProductDetailItems(changedItem) {
        var ddlCFG = $(changedItem).closest("div.productDetailRepeaterItem").find('select[id$="_CFG"]');
        var ddlSize = $(changedItem).closest("div.productDetailRepeaterItem").find('select[id$="_Size"]');
        var ddlStyle = $(changedItem).closest("div.productDetailRepeaterItem").find('select[id$="_Style"]');
        var qtyBox = $(changedItem).closest("div.productDetailRepeaterItem").find('input[id$="_ProductQtyTextBox"]');
        
        if (changedItem.type != "text") {
            if (changedItem.selectedIndex != 0) { // isValidItem
                if (changedItem.id.indexOf("CFG") != -1) { //Item is CFG                    
                    if (ddlSize.length > 0 && ddlStyle.length > 0) { // Size and Style Exist
                        ddlSize.attr("disabled", false);
                    }
                    else if (ddlSize.length > 0 && !(ddlStyle.length > 0)) { //Just Size Exists
                        ddlSize.attr("disabled", false);
                    }
                    else if (!(ddlSize.length > 0) && ddlStyle.length > 0) { //Just Style Exists
                        ddlStyle.attr("disabled", false);
                    }
                    else if (qtyBox.val() > 0 && qtyBox.val() != null) { //Just Quantity Box Exists
                        enableAddToCartButton(changedItem);
                    }
                }
                else if (changedItem.id.indexOf("Size") != -1) { //Item is Size
                    if (ddlStyle.length > 0) { //Style Exists
                        ddlStyle.attr("disabled", false);
                        var ddl = document.getElementById(ddlStyle.attr('id'));
                        var length = ddl.options.length;
                        for (var i = 0; i < length; i++) {
                            ddl.remove(0);
                        }
                        var styles = new Array();
                        styles = changedItem.value.substring(changedItem.value.indexOf(":") + 1, changedItem.value.length).split("|");
                        var optnTitle = document.createElement("option");
                        optnTitle.value = "Select Style";
                        optnTitle.text = "Select Style";
                        ddl.options.add(optnTitle);
                        $.each(styles, function(index, value) {
                            var optnValue = document.createElement("option");
                            optnValue.value = value;
                            optnValue.text = value;
                            ddl.options.add(optnValue);
                        });
                    }
                    else {                        
                        if (qtyBox.attr("disabled") == false &&
                    qtyBox.val() > 0 &&
                    qtyBox.val() != null) { // IF ITS TRUE!
                            enableAddToCartButton(changedItem);
                        }
                        else {
                            disableAddToCartButton(changedItem);
                        }
                    }
                }
                else if (changedItem.id.indexOf("Style") != -1) { //Item is Style
                    qtyBox = $(changedItem).closest("div.productDetailRepeaterItem").find('input[id$="_ProductQtyTextBox"]');
                    if (qtyBox.attr("disabled") == false &&
                    qtyBox.val() > 0 &&
                    qtyBox.val() != null) { // IF ITS TRUE!
                        enableAddToCartButton(changedItem);
                    }
                    else {
                        disableAddToCartButton(changedItem);
                    }
                }
            }
            else {
                if (changedItem.id.indexOf("CFG") != -1) { //Item is CFG
                    if (ddlSize.length > 0 && ddlStyle.length > 0) { // Size and Style Exist
                        ddlSize.attr("disabled", "disabled");
                        ddlStyle.attr("disabled", "disabled");
                    }
                    else if (ddlSize.length > 0 && !(ddlStyle.length > 0)) { //Just Size Exists
                        ddlSize.attr("disabled", "disabled");
                    }
                    else if (!(ddlSize.length > 0) && ddlStyle.length > 0) { //Just Style Exists
                        ddlStyle.attr("disabled", "disabled");
                    }
                }
                else if (changedItem.id.indexOf("Size") != -1) { //Item is Size
                    if (ddlStyle.length > 0) { //Style Exists
                        ddlStyle.attr("disabled", "disabled");
                    }
                }
                disableAddToCartButton(changedItem);
            }
        }
        else {
            ValidateOnlyQuantityBox(changedItem);
        }
    }

    function ValidateOnlyQuantityBox(quantityBox) {
        var ddlCFG = $(quantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_CFG"]');
        var ddlSize = $(quantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_Size"]');
        var ddlStyle = $(quantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_Style"]');
        var isValidItem = true;

        if (quantityBox.value > 0 && quantityBox.value != null) {
            isValidItem = true;
        }
        else {
            isValidItem = false;
        }

        if (ddlCFG.length > 0 && ddlCFG.get(0).selectedIndex == 0) {
            isValidItem = false;
        }
        else if (ddlSize.length > 0 && ddlSize.get(0).selectedIndex == 0) {
            isValidItem = false;
        }
        else if (ddlStyle.length > 0 && ddlStyle.get(0).selectedIndex == 0) {
            isValidItem = false;
        }

        if (isValidItem) {
            enableAddToCartButton(quantityBox);
        }
        else {
            disableAddToCartButton(quantityBox);
        }
    }    

    function findClosestAddToCartButtonForEachItem(comparisonElement) {
        return $(comparisonElement).closest("div.productDetailRepeaterItem").find('input[id$="_btnAddToCart"]');
    }

    function findClosestDisableImageForEachItem(comparisonElement) {
        return $(comparisonElement).closest("div.productDetailRepeaterItem").find('div[id$="_imgAddToCardDisabled"]');
    }

    function disableAddToCartButton(elementToReference) {
        findClosestAddToCartButtonForEachItem(elementToReference).attr("class", "noDisplay");
        findClosestDisableImageForEachItem(elementToReference).attr("class", "AddToCartDisabledImage");
    }

    function enableAddToCartButton(elementToReference) {
        findClosestAddToCartButtonForEachItem(elementToReference).attr("class", "AddToCartButtonImage");
        findClosestDisableImageForEachItem(elementToReference).attr("class", "noDisplay");
    }

    function DisplaySelectionError(addToCartButton) {
        var quantityBox = $(addToCartButton).closest("div.productDetailRepeaterItem").find('input[id$="_ProductQtyTextBox"]');
        var isAlreadyFailed = false;
        var qtipContainer = "#qtip-" + $('[id$="_imgAddToCardDisabled"]').index(addToCartButton);

        if ($(quantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_CFG"]').length > 0) {
            if (!isAlreadyFailed) {
                var ddlCFG = $(quantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_CFG"]');
                if (ddlCFG.get(0).selectedIndex != 0) {
                    $(qtipContainer).qtip("disable");
                }
                else {
                    ddlCFG.addClass("SelectionError");
                    if (GetInternetExplorerVersion() == 7 || document.documentMode == 7) { //if IE7 browser or docmode
                        CreateBorderForDropdownsIE(ddlCFG);
                    }
                    $(qtipContainer).qtip("enable");
                    $(qtipContainer).find('#AddToCartErrorPopupContent').html('Please Make Selection');
                    determineQtipContainerSize(qtipContainer);
                    isAlreadyFailed = true;
                }
            }
        }
        if ($(quantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_Size"]').length > 0) {
            var ddlSize = $(quantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_Size"]');
            if (ddlSize.get(0).selectedIndex != 0) {
                $(qtipContainer).qtip("disable");
            }
            else {
                ddlSize.addClass("SelectionError");
                if (GetInternetExplorerVersion() == 7 || document.documentMode == 7) { //if IE7
                    CreateBorderForDropdownsIE(ddlSize);
                }
                $(qtipContainer).qtip("enable");
                $(qtipContainer).find('#AddToCartErrorPopupContent').html('Please Select a Size');
                determineQtipContainerSize(qtipContainer);
                isAlreadyFailed = true;
            }
        }
        if ($(quantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_Style"]').length > 0) {
            if (!isAlreadyFailed) {
                var ddlStyle = $(quantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_Style"]');
                if (ddlStyle.get(0).selectedIndex != 0) {
                    $(qtipContainer).qtip("disable");
                }
                else {
                    ddlStyle.addClass("SelectionError");
                    if (GetInternetExplorerVersion() == 7 || document.documentMode == 7) { //if IE7
                        CreateBorderForDropdownsIE(ddlStyle);
                    }
                    $(qtipContainer).qtip("enable");
                    $(qtipContainer).find('#AddToCartErrorPopupContent').html('Please Select a Style');
                    determineQtipContainerSize(qtipContainer);
                    isAlreadyFailed = true;
                }
            }
        }
        if (!isAlreadyFailed) {
            if ((quantityBox.attr("value") > 0)) {
                $(qtipContainer).qtip("disable");
            }
            else {
                quantityBox.addClass("SelectionError");
                $(qtipContainer).qtip("enable");
                $(qtipContainer).find('#AddToCartErrorPopupContent').html('Please Select a Valid Quantity');
                determineQtipContainerSize(qtipContainer);
            }
        }
    }

    function RemoveSelectionError(addToCartButton) {
        var ddlCFG = $(addToCartButton).closest("div.productDetailRepeaterItem").find('select[id$="_CFG"]');
        var ddlSize = $(addToCartButton).closest("div.productDetailRepeaterItem").find('select[id$="_Size"]');
        var ddlStyle = $(addToCartButton).closest("div.productDetailRepeaterItem").find('select[id$="_Style"]');
        var quantityBox = $(addToCartButton).closest("div.productDetailRepeaterItem").find('input[id$="_ProductQtyTextBox"]');

        if (ddlCFG.length > 0 && ddlCFG.hasClass("SelectionError")) {
            ddlCFG.removeClass("SelectionError");
            if (ddlCFG.parent().is("div.DropdownContainer")) {
                ddlCFG.closest("div.DropdownContainer").removeClass("SelectionError");
            }
        }
        else if (ddlSize.length > 0 && ddlSize.hasClass("SelectionError")) {
            ddlSize.removeClass("SelectionError");
            if (ddlSize.parent().is("div.DropdownContainer")) {
                ddlSize.closest("div.DropdownContainer").removeClass("SelectionError");
            }
        }
        else if (ddlStyle.length > 0 && ddlStyle.hasClass("SelectionError")) {
            ddlStyle.removeClass("SelectionError");
            if (ddlStyle.parent().is("div.DropdownContainer")) {
                ddlStyle.closest("div.DropdownContainer").removeClass("SelectionError");
            }
        }
        else if (quantityBox.length > 0 && quantityBox.hasClass("SelectionError")) {
            quantityBox.removeClass("SelectionError");
        }
    }

    function GetInternetExplorerVersion() {
        var versionNumber = -1;
        if (navigator.appName == 'Microsoft Internet Explorer') {
            var userAgent = navigator.userAgent;
            var regex = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
            if (regex.exec(userAgent) != null)
                versionNumber = parseFloat(RegExp.$1);
        }
        return versionNumber;
    }

    function CreateBorderForDropdownsIE(ddlDropdown) {
        if (!ddlDropdown.parent().is("div.DropdownContainer")) {
            ddlDropdown.wrap('<div class="DropdownContainer" />');
        }
        ddlDropdown.closest("div.DropdownContainer").width(ddlDropdown.width() + 4).height(ddlDropdown.height() + 4).addClass("SelectionError");
    }

    $('[id$="_imgAddToCardDisabled"]').hover(
        function() { DisplaySelectionError(this); }, function() { RemoveSelectionError(this); }
    );

    $('[id$="_ProductQtyTextBox"]').focus(function() {
        this.select();
    });

    $('[id$="_AddToCartButton"]').click(function() { //"Add Checked Item to Cart" button for Wishlist
        var productItemContainer = document.getElementById('ProductItemWrapper');
        var inputArray = productItemContainer.getElementsByTagName('input');
        var hasCheckedItem = 0;
        var checkboxCount = 0;
        for (var i = 0; i < inputArray.length; i++) {
            if (inputArray[i].type == "checkbox") {
                if (!$("#ProdItemSelect").is(':hidden')) {
                    checkboxCount++;
                }
                if (inputArray[i].checked == true) {
                    hasCheckedItem++;
                }
            }
        }
        if (checkboxCount > 0) {
            if (hasCheckedItem > 0) {
                $("#validationError").html("");
                return true;
            }
            else {
                $("#validationError").html("Please check the Add to Bag on the item(s) you would like to add to the bag.");
                return false;
            }
        }
    });

    $('[id$="_btnAddToCart"]').click(function() {
        ValidateAddToCart();
    });

    $('[id$="_btnAddToWishList"]').click(function() {
        ValidateAddToCart();
    });

    function ValidateAddToCart() {
        var canAddToCart;
        var addToCartErrorMessage;
        var hasQuantity = 0;
        var indexOfQuantityBoxArray = [];
        var productItemContainer = document.getElementById('ProductItemContainer');
        var inputArray = productItemContainer.getElementsByTagName('input');

        for (var i = 0; i < inputArray.length; i++) {
            if (inputArray[i].type == "text") {
                if (inputArray[i].value > 0 && inputArray[i].value != null) {
                    indexOfQuantityBoxArray[i] = i;
                    hasQuantity++;
                }
                else {
                    indexOfQuantityBoxArray[i] = -1;
                }
            }
        }
        if (hasQuantity > 0) {
            if ($('[id$="_Size"]').length > 0 && $('[id$="_Style"]').length > 0) { //both style and size exist
                for (var j = 0; j < indexOfQuantityBoxArray.length; j++) {
                    if (indexOfQuantityBoxArray[j] != -1 && indexOfQuantityBoxArray[j] != undefined) {
                        var idOfQuantityBox = '#' + inputArray[indexOfQuantityBoxArray[j]].id;
                        var ddlSize = $(idOfQuantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_Size"]');
                        var ddlStyle = $(idOfQuantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_Style"]');
                        canAddToCart = validateStyleAndSize(ddlSize, ddlStyle);
                    }
                }
            }
            else if ($('[id$="_Size"]').length > 0 && !($('[id$="_Style"]').length > 0)) { //just size exists
                for (var j = 0; j < indexOfQuantityBoxArray.length; j++) {
                    if (indexOfQuantityBoxArray[j] != -1 && indexOfQuantityBoxArray[j] != undefined) {
                        var idOfQuantityBox = '#' + inputArray[indexOfQuantityBoxArray[j]].id;
                        var ddlSize = $(idOfQuantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_Size"]');
                        if (ddlSize.id != undefined) {
                            canAddToCart = validateStyleOrSize(ddlSize);
                        }
                    }
                }
            }
            else if (!($('[id$="_Size"]').length > 0) && $('[id$="_Style"]').length > 0) { //just style exits
                for (var j = 0; j < indexOfQuantityBoxArray.length; j++) {
                    if (indexOfQuantityBoxArray[j] != -1 && indexOfQuantityBoxArray[j] != undefined) {
                        var idOfQuantityBox = '#' + inputArray[indexOfQuantityBoxArray[j]].id;
                        var ddlStyle = $(idOfQuantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_Style"]');
                        if (ddlStyle.id != undefined) {
                            canAddToCart = validateStyleOrSize(ddlStyle);
                        }
                    }
                }
            }
            if ($('[id$="_CFG"]').length > 0) {
                for (var j = 0; j < indexOfQuantityBoxArray.length; j++) {
                    if (indexOfQuantityBoxArray[j] != -1 && indexOfQuantityBoxArray[j] != undefined) {
                        var idOfQuantityBox = '#' + inputArray[indexOfQuantityBoxArray[j]].id;
                        var ddlCFG = $(idOfQuantityBox).closest("div.productDetailRepeaterItem").find('select[id$="_CFG"]');
                        canAddToCart = validateCFG(ddlCFG);
                    }
                }
            }
        }
        else {
            addToCartFail("Quantity");
            canAddToCart = false;
        }

        return canAddToCart;
    }

    function addToCartFail(whatYouDidWrong) {
        $('#ValidationErrorContainer').addClass("ValidationErrorContainer");
        addToCartErrorMessage = "Please select a valid " + whatYouDidWrong + ".";
        $("#validationError").html(addToCartErrorMessage);
    }

    function addToCartCFGFail(whatYouDidWrong) {
        $('#ValidationErrorContainer').addClass("ValidationErrorContainer");
        addToCartErrorMessage = whatYouDidWrong + ".";
        $("#validationError").html(addToCartErrorMessage);
    }

    function validateStyleAndSize(ddlFirstToValidate, ddlSecondToValidate) {
        if (ddlFirstToValidate.length > 0 && ddlSecondToValidate.length > 0) {
            if (ddlFirstToValidate.get(0).selectedIndex != 0) {
                if (ddlSecondToValidate.get(0).selectedIndex != 0) {
                    return true;
                }
                else {
                    addToCartFail(ddlSecondToValidate[0].value);
                    return false;
                }
            }
            else {
                addToCartFail(ddlFirstToValidate[0].value);
                return false;
            }
        }
        else if (ddlFirstToValidate.length <= 0) {
            return validateStyleOrSize(ddlSecondToValidate);
        }
        else if (ddlSecondToValidate.length <= 0) {
            return validateStyleOrSize(ddlFirstToValidate);
        }
    }

    function validateStyleOrSize(ddlToValidate) {
        if (ddlToValidate.get(0).selectedIndex != 0) {
            return true;
        }
        else {
            addToCartFail(ddlToValidate[0].value);
            return false;
        }
    }

    function validateCFG(ddlToValidate) {
        if (ddlToValidate.get(0).selectedIndex != 0) {
            return true;
        }
        else {
            addToCartCFGFail("Please Make Selection");
            return false;
        }
    }

    $('[id$="_CreateAccountCheckBox"]').click(function() {
        if ($('[id$="_CreateAccountCheckBox"]').attr('checked')) {
            $(".CreateAccountShowHidePanel").show();
            ValidateCreateAccountInformation(true);
        }
        else {
            $(".CreateAccountShowHidePanel").hide();
            removeErrorClasses();
            $('[id$="_BAEmailErrorLabel"]').text('');
        }
    });


    $(".BAEmailTextBox").blur(function() {
        if ($('[id$="_CreateAccountCheckBox"]').attr('checked')) {
            ValidateCreateAccountInformation(true);
        }
    });

    if ($('[id$="_CreateAccountCheckBox"]').attr('checked', false)) {
        $(".CreateAccountShowHidePanel").hide();
    }

    $('.SHAlsoShippingAddressRBText').click(function() {
        $('[id$="_SHAlsoShippingAddressRadioButton"]').click();
    });

    $('.SHDifferentAddressRBText').click(function() {
        $('[id$="_SHDifferentAddressRadioButton"]').click();
    });

    $('.SHMultipleAddressRBText').click(function() {
        $('[id$="_SHMultipleAddressRadioButton"]').click();
    });

    if ($('[id$="_SHAlsoShippingAddressRadioButton"]').attr('checked')) {
        $(".ShippingAddressFormFields").addClass('FormIsHidden');
        hideShippingAddressForm();
    }

    function hideShippingAddressForm() {
        $(".ShippingAddressFormFields").hide();
        $(".AddressBookContainer").hide();
        $(".RequiredPhoneText").hide();
    }

    $('[id$="_SHMultipleAddressRadioButton"]').click(function() {
        $('[id$="_SHAlsoShippingAddressRadioButton"]').attr('checked', false);
        $('[id$="_SHDifferentAddressRadioButton"]').attr('checked', false);
        $(".ShippingAddressFormFields").addClass('FormIsHidden');
        hideShippingAddressForm();
        isValidBA = true;
        isValidSH = true;

        removeErrorClasses();
        if (!validateBillingAddress()) {
            scroll(0, 0);
            $('[id$="_SHMultipleAddressRadioButton"]').attr('checked', false);
            $('[id$="_SHAlsoShippingAddressRadioButton"]').attr('checked', true);
            return false;
        }
        __doPostBack('_SHMultipleAddressRadioButton', 'CheckChanged');
    });

    $('[id$="_SHAlsoShippingAddressRadioButton"]').click(function() {
        $('[id$="_SHDifferentAddressRadioButton"]').attr('checked', false);
        $('[id$="_SHMultipleAddressRadioButton"]').attr('checked', false);
        if (!$(".ShippingAddressFormFields").hasClass("FormIsHidden")) {
            $(".ShippingAddressFormFields").addClass('FormIsHidden');
            hideShippingAddressForm();
            $(".SHErrorMessageLabel").html("");
        }
    });

    $(".ShippingAddressesRadioButtons").click(function() {
        if ($(".ShippingAddressesRadioButtons input:checked").val() == 'NewAddress' || $(".ShippingAddressesRadioButtons input").val() == undefined) {

            $(this).removeClass("ShippingAddressesRadioButtonsChecked");
            toggleShippingAddressForm(false, true);
        } else {
            $(this).addClass("ShippingAddressesRadioButtonsChecked");
            toggleShippingAddressForm(true, false);
            var str = $(".ShippingAddressesRadioButtons input:checked").val();
            var array = str.split("|");
            $(".SHFirstNameTextBox").val(array[1]);
            $(".SHLastNameTextBox").val(array[2]);
            $(".SHAddress1TextBox").val(array[3]);
            $(".SHAddress2TextBox").val(array[4]);
            $(".SHCityTextBox").val(array[5]);
            $(".SHStateDDL").val(array[6]);
            var zipsplit = array[7].split("-");
            $(".SHZipTextBox").val(zipsplit[0]);
            if (zipsplit[1] != undefined) {
                $(".SHZipExtTextBox").val(zipsplit[1]);
            }
        }
    });

    $('[id$="_SHDifferentAddressRadioButton"]').click(shippingBoxChecked);

    $('[id$="_PaymentReviewButton"]').click(function() {
        isValidBA = true;
        isValidSH = true;
        isValidNewAccInfo = true;

        /* we need to make sure we remove any error classes that my exist first, otherwise, they'll never be removed*/
        removeErrorClasses();

        isValidBA = validateBillingAddress();

        // validate the shipping address if we need to
        // if they are not shipping to their billing address, and they have not select an address from the radio button group, then we need to 
        // validate the shipping form.

        if ($('[id$="_SHDifferentAddressRadioButton"]').attr('checked')) {
            if ($(".ShippingAddressesRadioButtons input:checked").val() == 'NewAddress' || $(".ShippingAddressesRadioButtons input").val() == undefined) {
                isValidSH = validateShippingAddress();
            }
        }

        if (!isValidBA) {
            scroll(0, 0);
            return false;
        } else if (!isValidSH || !isValidNewAccInfo) {
            return false;
        }
        if ($('[id$="_CreateAccountCheckBox"]').attr('checked')) {
            isValidNewAccInfo = ValidateCreateAccountInformation(false);
            if (!isValidNewAccInfo) {
                return false;
            }
        }

    });



    //Redesign


    // Dynamic Dropdown
    $('.topNavSeparator').hoverIntent({
        sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
        interval: 200, // number = milliseconds for onMouseOver polling interval    
        over: windowSlideDown, // function = onMouseOver callback (REQUIRED)    
        timeout: 400, // number = milliseconds delay before onMouseOut    
        out: windowSlideUp // function = onMouseOut callback (REQUIRED)
    });

    $('.topNavSeparatorLast').hoverIntent({
        sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
        interval: 20, // number = milliseconds for onMouseOver polling interval    
        over: windowSlideDown, // function = onMouseOver callback (REQUIRED)    
        timeout: 400, // number = milliseconds delay before onMouseOut    
        out: windowSlideUp // function = onMouseOut callback (REQUIRED)
    });


    function windowSlideDown() {
        $(this).addClass('addBackground');
        $('div.topNavCategories', this).slideDown('slow');
    }
    function windowSlideUp() {
        $(this).removeClass('addBackground');
        $('div.topNavCategories', this).slideUp('slow');
    }

    $('.modal').modalpop({ speed: 700 });

    $('#BuyersClubClose').click(hideBuyersClubPopup);
    $('#BuyersClubAdd').click(function() {
        hideBuyersClubPopup();
        __doPostBack('btnBuyersClubJoin', 'Click');
    });

    if ($.cookie('buyersClub') == null) {
        $.cookie('buyersClub', 'open', { expires: 1, path: "/" });
        showBuyersClubPopup();
    }

    function hideBuyersClubPopup() {
        $('#BuyersClubPopup').stop().slideUp('normal');
        $('#modalMask').fadeOut('slow');
    }

    function showBuyersClubPopup() {

        $('#BuyersClubTrigger').click();
        var t = setTimeout("$('#BuyersClubPopup').stop().slideUp('normal');$('#modalMask').fadeOut('slow');", 30000);
    }


    if ($('#hiddenPersonalization').length) {
        var hiddenValue = $('#hiddenPersonalization').val();
        if (hiddenValue == 'true') {
            showPersonalizationPopup();
        }
        else {
            hidePersonalizationPopup();
        }
    }

    function showPersonalizationPopup() {
        $('#PersonalizationTrigger').click();
    }

    function hidePersonalizationPopup() {
        $('#PersonalizationPopup').stop().slideUp('normal');
        $('#modalMask').fadeOut('slow');
    }


    $('#BumpClose').click(hideBumpPopup);

    if ($.cookie('BumpCookie') != null) {
        if ($.cookie('BumpCookie') == 'Show') {
            $.cookie('BumpCookie', 'Hide', { path: '/' });
            showBumpPopup();
        }
    }

    function showBumpPopup() {
        $('#BumpTrigger').click();
    }

    function hideBumpPopup() {
        $('#BumpPopup').stop().slideUp('normal');
        $('#modalMask').fadeOut('slow');
    }

    $('#ViewDetailsPrint').click(function() {
        $('#ViewDetailsWrapper').printElement({
            printBodyOptions:
                {
                    styleToAdd: '',
                    classNameToAdd: 'ViewDetailsPrintCss'
                }
        });
    });


    $('#ViewDetailsClose').click(hideViewDetails);

    $('#LabelViewPrint').click(function() {
        $('#LabelWrapper').printElement({
            printBodyOptions:
                {
                    styleToAdd: '',
                    classNameToAdd: 'ReturnLabelPrintCss'
                }
        });
    });

    function hideViewDetails() {
        $('#ViewDetails').stop().slideUp('normal');
        $('#modalMask').fadeOut('slow');
    }

    //Weekly Special
    $('#weeklySpecial').click(showSpecial);
    $('#weeklySpecialClose').click(hideSpecial);

    if ($.cookie('weeklySpecial') == null) {
        $.cookie('weeklySpecial', 'open');
        showSpecial();
    }
    else {
        hideSpecial();
    }

    function showSpecial() {
        $('#weeklySpecialOpen').slideDown('normal', function() {
            $(this).fadeIn('slow').animate({ opacity: '1.0' }, 6000).slideUp('slow');
        });
    }
    function hideSpecial() {
        $('#weeklySpecialOpen').stop().slideUp('normal');
    }

    //Email Signup
    $('#emailSignup').click(showEmailSignup);
    $('#emailSignupClose').click(hideEmailSignup);

    function showEmailSignup() {
        $('#emailSignupOpen').slideDown('normal');
    }
    function hideEmailSignup() {
        $('#emailSignupOpen').slideUp('normal');
    }

    //Catalog QO
    $('#catalogQO').click(showQO);
    $('#catalogQuickOrderClose').click(hideQO);
    $('[id$="_GoButton"]').click(validateQO);

    function validateQO() {
        if ($('[id$="_txtQuickOrderItemId"]').val().length != 6) {
            alert("Item Number '" + $('[id$="_txtQuickOrderItemId"]').val() + "' is invalid.");
            showQO();
            return false;
        }
        else if (isNaN(($('[id$="_txtQuickOrderQuantity"]').val())) ||
            parseInt($('[id$="_txtQuickOrderQuantity"]').val()) <= 0) {
            alert("Quantity '" + $('[id$="_txtQuickOrderQuantity"]').val() + "' is invalid.");
            showQO();
            return false;
        }
        return true;
    }

    function showQO() {
        $('#catalogQuickOrderOpen').slideDown('normal');
    }
    function hideQO() {
        $('#catalogQuickOrderOpen').slideUp('normal');
    }


    // Tabs
    $("ul.css-tabs").tabs("> .css-panes");
    //Image Swap
    $('.altImagesStacked').click(swapImage);

    function swapImage() {
        var smallSource = $(this).children().attr('src');
        var smallWidth = $(this).children().attr('width');
        var smallHeight = $(this).height();
        var smallPath = $(this).children().attr('path');

        var largeSource = $('.zoomImage').children().attr('src');
        var largeWidth = $('.zoomImage').children().attr('width');
        var largeHeight = $('.zoomImage').height();
        var largeHref = $('.zoomImage').attr('href');
        var largePath = $('.zoomImage').attr('path');

        var width = smallSource.replace('235', '470');

        $('.zoomImage').children().attr('src', smallSource);
        $('.zoomImage').attr('path', smallPath);
        $('.zoomImage').attr('href', width.replace('350', '700'));

        $(this).children().attr('src', largeSource);
        $(this).children().attr('path', largePath);
    }

    //Zoom

    var options = {
        zoomWidth: 230,
        zoomHeight: 230,
        zoomType: 'reverse',
        title: false,
        xOffset: 10,
        yOffset: 20,
        showEffect: 'fadein',
        fadinSpeed: 'slow',
        hideEffect: 'fadeout',
        fadeoutSpeed: 'slow',
        lens: true,
        position: 'right'
    };

    var imgSize = $('.zoomImage').attr('orig');
    if (imgSize == 700) {
        $('.zoomImage').jqzoom(options);
        $('#zoomIcon').show();
    }
    else {
        $('#zoomIcon').hide();
    }

    $('.zoomImage').click(zoomClick);

    function zoomClick() {
        var path = $('.zoomImage').attr('path');
        window.open(path.replace('~', '../'), 'window', 'height=600, width=600, resizable=yes, scrollbars=yes');
        return false;
    }

    //Swap StickyFooter
    $('#hideBar').click(hideStickyFooter);
    $('#showBar').click(showStickyFooter);

    if ($.cookie('stickyFooter') == null) {
        showStickyFooter();
    }
    else {
        hideStickyFooter();
    }

    function hideStickyFooter() {
        $('#hideBar').hide();
        $('#stickyContent').hide();
        $('#showBar').show();
        $('.stickyFooter').addClass('shrinkStickyFooter');

        if (this.id == 'hideBar') {
            $.cookie('stickyFooter', 'hide');
        }
    }
    function showStickyFooter() {
        $('#showBar').hide();
        $('#stickyContent').show();
        $('#hideBar').show();
        $('.stickyFooter').removeClass('shrinkStickyFooter');

        if (this.id == 'showBar') {
            $.cookie('stickyFooter', null, { expires: -1 });
        }
    }

    //Trim email unsubscribe boxes. 3/26/10 TW
    $('#ctl00_cphBody_EmailUnsubscribe1_EmailAddressTextBox').blur(trimText);
    $('#ctl00_cphBody_EmailUnsubscribe1_ConfirmEmailAddressTextBox').blur(trimText);
    $('#ctl00_cphBody_EmailSignup1_EmailAddressTextBox').blur(trimText);
    $('#ctl00_cphBody_EmailSignup1_ConfirmEmailAddressTextBox').blur(trimText);

    function trimText() {
        var textValue = this.value;
        textValue.trim();
        this.value = textValue.trim();
    }


    //Browser Detect
    browserDetect();

});                                                                                   // Doc Ready End

///////////////////////////////
//// FUNCTIONS GO HERE  //////
///////////////////////////////
    

function openModal()
{
    //alert($('#test').attr('id'));
    
    //Get the A tag
		var id = $('#test').attr('href');
		
    //Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
	
		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		
		//transition effect		
		$('#mask').fadeIn(1000);	
		$('#mask').fadeTo("slow",0.8);	
	
		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();
              
		//Set the popup window to center
		$(id).css('top',  winH/2-$(id).height()/2);
		$(id).css('left', winW/2-$(id).width()/2);
	
		//transition effect
		$(id).fadeIn(2000);
}




//if close button is clicked
	$('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		
		$('#mask').hide();
		$('.window').hide();
	});		
	

//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.window').hide();
	});			
	
	
	$('#modalSubmit').click(closeModal);
	
function closeModal()
{
   $('.window').hide();
}


// Javascript pulled from Old Master Page 

function OpenVeriSign()
    {
        window.open('https://seal.verisign.com/splash?form_file=fdf/splash.fdf&dn=www.aswechange.com&lang=en');
    }
    
//function pageLoad(){
//                  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
//               }

function EndRequestHandler(sender, args) {
 var hiddenVal = document.getElementById('refreshDisplay');
 var checkoutTabName = document.getElementById('checkoutTabName');

 if (checkoutTabName.getAttribute('value') != "MISSING"){
    if (hiddenVal.getAttribute('value')=='true'){
       var divObj = document.getElementById(checkoutTabName.getAttribute('value'));
       var divHTML = document.getElementById('divHTMLValueExt');
       if (divHTML.getAttribute('value') != ''){
        $(".MiniCartItemCount").html(divHTML.getAttribute('value'));
       }
    }   
 }
}  

function GreyOut()
    {
        var cvr = document.getElementById("cover");
        cvr.style.display = "block";
        cvr.style.width = "200%";
        cvr.style.height = "200%";
        
        var prc = document.getElementById("processing");
        prc.style.display = "block";
        
        var BrowserWidth;
        var BrowserHeight;
 
         // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
         if (typeof window.innerWidth != 'undefined')
         {
              BrowserWidth = window.innerWidth,
              BrowserHeight = window.innerHeight
         }
         // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
         else if (typeof document.documentElement != 'undefined'
             && typeof document.documentElement.clientWidth !=
             'undefined' && document.documentElement.clientWidth != 0)
         {
               BrowserWidth = document.documentElement.clientWidth,
               BrowserHeight = document.documentElement.clientHeight
         }
         // older versions of IE
         else
         {
               BrowserWidth = document.getElementsByTagName('body')[0].clientWidth,
               BrowserHeight = document.getElementsByTagName('body')[0].clientHeight
         }

        prc.style.left = (BrowserWidth - 300) / 2;
        prc.style.top = (BrowserHeight - 200) / 2;
    }
    
     function ResetCheckOutTab(){
            var objPanelDynamic = document.getElementById('<%=pnlShoppingCartDynamic.ClientID.ToString()%>');	
            objPanelDynamic.style.visibility='hidden';
        }

function orderSubmitted()
{
    if (typeof(Page_ClientValidate) == 'function')
    {
        var CreditCardValidation = Page_ClientValidate('CreditCardValidationGroup');
        var AddressEntryValidation = Page_ClientValidate('AddressEntry');
        var EmailEntryValidation = Page_ClientValidate('EmailValidationGroup');
        
        if (CreditCardValidation == true && AddressEntryValidation == true && EmailEntryValidation == true)
        {
            //The GreyOut() function is in the header of the master page.
            //The GreyOut() function utilizes two divs which are located just under the body tag
            //called "cover" and "processing"
            GreyOut();
        }
        else
        {
            return false;
        }
    }
}

function ShowGreyout() {
    var modalPopupBehavior = $find('PanelCoverBh');
    if(Page_ClientValidate())
    {
        modalPopupBehavior.show();
    }
    return false;
    }
    function ShowGreyoutPayPal() {
    var modalPopupBehavior = $find('PanelCoverBh');
  
        modalPopupBehavior.show();
   
    return false;
    }
    function HideGreyout() {
        var modalPopupBehavior = $find('PanelCoverBh');
        modalPopupBehavior.hide();
        return false;
    }
    function ShowGreyoutShoppingCart() {
        var modalPopupBehavior = $find('PanelCoverBh');

        modalPopupBehavior.show();

        return false;
    }
/// Original JQueryFunctions taken out of document ready

function checkAddressCookie()
{
    if($.cookie('addChecked') == 'show'){
        shippingBoxCheckedHelper(false);
    }
}

function disableShippingFields() {
    var arrFields = ["FirstNameTextBox", "LastNameTextBox", "Address1TextBox", "Address2TextBox", "CityTextBox", "StateDDL", "ZipTextBox", "ZipExtTextBox", "DayTimeTextBox1", "DayTimeTextBox2", "DayTimeTextBox3", "EveningPhoneTextBox1", "EveningPhoneTextBox2", "EveningPhoneTextBox3"];

    $.each(arrFields, function() {
        $(".SH" + this).attr("disabled", "disabled");
    })
}

function shippingBoxChecked()
{
    shippingBoxCheckedHelper(true) ;
}	

/// Modified by:    Erica Mutsch
/// Modified on:    05/03/10
/// Description:    WO 2068 - fixed bug that caused the "use billing address for shipping" box to stay checked
///                           also disabled radio buttons when box is checked
function shippingBoxCheckedHelper(ValidateTheBillingAddress) {
    $('[id$="_SHAlsoShippingAddressRadioButton"]').attr('checked', false);
    $('[id$="_SHMultipleAddressRadioButton"]').attr('checked', false);
    $(this).addClass("DifferentAddressRadioButtonChecked");
    $(".ShippingAddressFormFields").show();
    $(".AddressBookContainer").show();
    $(".RequiredPhoneText").show();
    $(".ShippingAddressFormFields").removeClass('FormIsHidden');
    var isValidSH;
    removeErrorClasses();
}

    function toggleShippingAddressForm(enabled, autofill) {
        var arrFields = ["FirstNameTextBox","LastNameTextBox","Address1TextBox","Address2TextBox","CityTextBox","StateDDL","ZipTextBox","ZipExtTextBox","DayTimeTextBox1","DayTimeTextBox2","DayTimeTextBox3","EveningPhoneTextBox1","EveningPhoneTextBox2","EveningPhoneTextBox3"];

        if(enabled)
        {
            $.each(arrFields, function() {
                if(autofill)
                {
                    $(".SH" + this).val($(".BA" + this).val())
                }
                $(".SH" + this).attr("disabled", "disabled");
            })
        }
        else
        {
            $.each(arrFields, function() {
                if(autofill)
                {
                    $(".SH" + this).val('')
                }
                $(".SH" + this).removeAttr("disabled", "disabled");
            })
            $(".SHStateDDL").val("-1")
        }
    }
    
    function checkForBillingAddressChange(checkKeyUp) {
        var arrFields = ["BAFirstNameTextBox","BALastNameTextBox","BAAddress1TextBox","BAAddress2TextBox","BACityTextBox","BAZipTextBox","BAZipExtTextBox","BADayTimeTextBox1","BADayTimeTextBox2","BADayTimeTextBox3","BAEveningPhoneTextBox1","BAEveningPhoneTextBox2","BAEveningPhoneTextBox3"];
        if(checkKeyUp) {
            $.each(arrFields, function() {
                $("." + this).one("keyup", billingChanged);
                $('.BAStateDDL').change(billingChanged);
            })
        } else {
            $.each(arrFields, function() {
                $("." + this).unbind("keyup");
            })
        }
    }
    
    function billingChanged() {
        var arrFields = ["BAFirstNameTextBox","BALastNameTextBox","BAAddress1TextBox","BAAddress2TextBox","BACityTextBox","BAZipTextBox","BAZipExtTextBox","BADayTimeTextBox1","BADayTimeTextBox2","BADayTimeTextBox3","BAEveningPhoneTextBox1","BAEveningPhoneTextBox2","BAEveningPhoneTextBox3"];
        toggleShippingAddressForm(false, true);
        //$('.SHAlsoShippingAddressCheckBox input').removeAttr("checked");
        //$('.SHAlsoShippingAddressCheckBox').removeClass("SHAlsoShippingAddressCheckBoxChecked");
        
        $.each(arrFields, function() {
            $("." + this).unbind("keyup");
        })
    }
    
    function removeErrorClasses() {
    	$("label").removeClass("FormLabelError");
	    $(":input").removeClass("FormTextBoxError");
    }

    function validateBillingAddress() {
        var isValidBA;

        isValidBA = true;


        if ($(".BAFirstNameTextBox").val().length == 0) {
            $(".BAFirstNameTextBox").addClass("FormTextBoxError");
            $('[id$="_BAFirstNameErrorLabel"]').text('Please enter your first name.');

            isValidBA = false;
        }
        if ($(".BAFirstNameTextBox").val().length > 36) {
            $(".BAFirstNameTextBox").addClass("FormTextBoxError");
            $('[id$="_BAFirstNameErrorLabel"]').text('First name cannot exceed 36 characters.');

            isValidBA = false;
        }
        if ($(".BALastNameTextBox").val().length == 0) {
            $(".BALastNameTextBox").addClass("FormTextBoxError");
            $('[id$="_BALastNameErrorLabel"]').text('Please enter your last name.');

            isValidBA = false;
        }
        if ($(".BALastNameTextBox").val().length > 36) {
            $(".BALastNameTextBox").addClass("FormTextBoxError");
            $('[id$="_BALastNameErrorLabel"]').text('Last name cannot exceed 36 characters.');

            isValidBA = false;
        }
        if ($("DIV.PaypalIndicator > input").val() == "True") {
            if (($(".BALastNameTextBox").val().length + $(".BAFirstNameTextBox").val().length) > 30) {
                $(".BAFirstNameTextBox").addClass("FormTextBoxError");

                $(".BALastNameTextBox").addClass("FormTextBoxError");
	            if (billingErrorList.indexOf("<li>First name cannot exceed 36 characters.</li>") >= 0) {
	                billingErrorList = billingErrorList.replace("<li>First name cannot exceed 36 characters.</li>", "");
	            }
	            if (billingErrorList.indexOf("<li>Last name cannot exceed 36 characters.</li>") >= 0) {
	                billingErrorList = billingErrorList.replace("<li>Last name cannot exceed 36 characters.</li>", "");
	            } 
                $('[id$="_BALastNameErrorLabel"]').text('Paypal requires first name and last name combined length to be less than 31 characters.');

                isValidBA = false;
            }
        }
        if ($(".BAAddress1TextBox").val().length == 0) {
            $(".BAAddress1TextBox").addClass("FormTextBoxError");
            $('[id$="_BAAddress1ErrorLabel"]').text('Please enter your address.');

            isValidBA = false;
        }
        if ($(".BACityTextBox").val().length == 0) {
            $(".BACityTextBox").addClass("FormTextBoxError");
            $('[id$="_BACityErrorLabel"]').text('Please enter your city.');

            isValidBA = false;
        }
        if ($(".BAStateDDL").val() == -1) {
            $('[id$="_BAStateErrorLabel"]').text('Please enter your state.');


            isValidBA = false;
        }
        if (!$(".BAZipTextBox").val().match(/\d{5}/)) {
            $(".BAZipTextBox").addClass("FormTextBoxError");
            $('[id$="_BAZipErrorLabel"]').text('Please enter a valid zip code');

            isValidBA = false;
        }
        if ($(".BAZipExtTextBox").val().length > 0 && !$(".BAZipExtTextBox").val().match(/\d{4}/)) {
            $(".BAZipExtTextBox").addClass("FormTextBoxError");
            $('[id$="_BAZipErrorLabel"]').text('Please enter a valid zip code and extension.');

            isValidBA = false;
        }
        if (!$(".BADayTimeTextBox1").val().match(/\d{3}/)) {
            $(".BADayTimeTextBox1").addClass("FormTextBoxError");

            $(".BADayTimeTextBox2").addClass("FormTextBoxError");

            $(".BADayTimeTextBox3").addClass("FormTextBoxError");
            $('[id$="_BADayTimeErrorLabel"]').text('Please enter a valid day time phone number.');

            isValidBA = false;
        } else {
            if (!$(".BADayTimeTextBox2").val().match(/\d{3}/)) {
                $(".BADayTimeTextBox1").addClass("FormTextBoxError");

                $(".BADayTimeTextBox2").addClass("FormTextBoxError");

                $(".BADayTimeTextBox3").addClass("FormTextBoxError");
                $('[id$="_BADayTimeErrorLabel"]').text('Please enter a valid day time phone number.');

                isValidBA = false;
            } else {
                if (!$(".BADayTimeTextBox3").val().match(/\d{4}/)) {
                    $(".BADayTimeTextBox1").addClass("FormTextBoxError");

                    $(".BADayTimeTextBox2").addClass("FormTextBoxError");

                    $(".BADayTimeTextBox3").addClass("FormTextBoxError");
                    $('[id$="_BADayTimeErrorLabel"]').text('Please enter a valid day time phone number.');

                    isValidBA = false;
                }
            }
        }

        if (!$(".BAEmailTextBox").val().match(/^([A-Za-z0-9_\+\-\.])+\@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/)) {
            $(".BAEmailTextBox").addClass("FormTextBoxError");
            $('[id$="_BAEmailErrorLabel"]').text('Please enter a valid email address.');
            $('[id$="_BAConfirmEmailErrorLabel"]').text('');
            isValidBA = false;
        } else if ($(".BAEmailTextBox").val() != $(".BAConfirmEmailTextBox").val()) {
            $(".BAEmailTextBox").addClass("FormTextBoxError");
            $(".BAConfirmEmailTextBox").addClass("FormTextBoxError");
            $('[id$="_BAConfirmEmailErrorLabel"]').text('Email and Confirm Email do not match.');
            isValidBA = false;
        }	 
        
        return isValidBA;
    }

    function validateShippingAddress() {
        var isValidSH;


        isValidSH = true;

        if ($(".SHFirstNameTextBox").val().length == 0) {
            $(".SHFirstNameTextBox").addClass("FormTextBoxError");
            $('[id$="_SHFirstNameErrorLabel"]').text('Please enter your first name.');

            isValidSH = false;
        }
        if ($(".SHLastNameTextBox").val().length == 0) {
            $(".SHLastNameTextBox").addClass("FormTextBoxError");
            $('[id$="_SHLastNameErrorLabel"]').text('Please enter your last name.');

            isValidSH = false;
        }
        if ($(".SHAddress1TextBox").val().length == 0) {
            $(".SHAddress1TextBox").addClass("FormTextBoxError");
            $('[id$="_SHAddress1ErrorLabel"]').text('Please enter your address.');

            isValidSH = false;
        }
        if ($(".SHCityTextBox").val().length == 0) {
            $(".SHCityTextBox").addClass("FormTextBoxError");
            $('[id$="_SHCityErrorLabel"]').text('Please enter your city.');

            isValidSH = false;
        }
        if ($(".SHStateDDL").val() == "-1") {
            $('[id$="_SHStateErrorLabel"]').text('Please enter your state.');
            isValidSH = false;
        }
        if (!$(".SHZipTextBox").val().match(/\d{5}/)) {
            $(".SHZipTextBox").addClass("FormTextBoxError");
            $('[id$="_SHZipErrorLabel"]').text('Please enter your zip code.');
            isValidSH = false;
        }
        if ($(".SHZipExtTextBox").val().length > 0 && !$(".SHZipExtTextBox").val().match(/\d{4}/)) {
            $(".SHZipExtTextBox").addClass("FormTextBoxError");
            $('[id$="_SHZipErrorLabel"]').text('Please enter a valid zip code extension.');
            isValidSH = false;
        }
        return isValidSH;
    }
    
     function ValidateCreateAccountInformation(doOnlyEmailLookup) 
    {    
        var isValidNewAccInfo;
	    isValidNewAccInfo = true;
	    
	    if(doOnlyEmailLookup == false)
	    {
            if($(".CreateAcctPasswordTextBox").val().length != 0)
            {
                if(!$(".CreateAcctPasswordTextBox").val().match($(".CreateAcctConfirmPasswordTextBox").val()))
                {
                    $(".CreateAcctConfirmPasswordTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountConfirmPasswordErrorLabel"]').text('Password and Confirm Password do not match.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                $(".CreateAcctPasswordTextBox").addClass("FormTextBoxError");
                $('[id$="_CreateAccountPasswordErrorLabel"]').text('Please enter a password.');
                isValidNewAccInfo = false;
            }
            
            if($(".CreateAccountFormFieldsDropDownList").val() != "-1")
            {
                if($(".CreateAcctAnswerTextBox").val().length == 0)
                {
                    $(".CreateAcctAnswerTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountPasswordResetAnswerErrorLabel"]').text('Please answer the password reset question.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                //$("._CreateAccountPasswordResetQuestions").addClass("FormTextBoxError");
                $('[id$="CreateAccountPasswordResetQuestionsErrorLabel"]').text('Please select a password reset question.');
                isValidNewAccInfo = false;
            }
        }
        
        if(isValidNewAccInfo)
        {     httpresponse = $.get('../AjaxValidation/CheckoutStep1aEmail.aspx?email=' + $(".BAEmailTextBox").val(), function(response) {                                        
                    if(response=="BAD")
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('The email address you are trying to register with is already in use.');
                        return false ;
                    }
                    else
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('');
                        return true ;
                    }
              });
              
              if($('[id$="_BAEmailErrorLabel"]').text() != '')
                    {                        
                        isValidNewAccInfo = false;                                          
                    }                      
        }
                          
        return isValidNewAccInfo;
    }
    
     function ValidateCreateAccountInformation(doOnlyEmailLookup) 
    {    
        var isValidNewAccInfo;
	    isValidNewAccInfo = true;
	    
	    if(doOnlyEmailLookup == false)
	    {
            if($(".CreateAcctPasswordTextBox").val().length != 0)
            {
                if(!$(".CreateAcctPasswordTextBox").val().match($(".CreateAcctConfirmPasswordTextBox").val()))
                {
                    $(".CreateAcctConfirmPasswordTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountConfirmPasswordErrorLabel"]').text('Password and Confirm Password do not match.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                $(".CreateAcctPasswordTextBox").addClass("FormTextBoxError");
                $('[id$="_CreateAccountPasswordErrorLabel"]').text('Please enter a password.');
                isValidNewAccInfo = false;
            }
            
            if($(".CreateAccountFormFieldsDropDownList").val() != "-1")
            {
                if($(".CreateAcctAnswerTextBox").val().length == 0)
                {
                    $(".CreateAcctAnswerTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountPasswordResetAnswerErrorLabel"]').text('Please answer the password reset question.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                //$("._CreateAccountPasswordResetQuestions").addClass("FormTextBoxError");
                $('[id$="CreateAccountPasswordResetQuestionsErrorLabel"]').text('Please select a password reset question.');
                isValidNewAccInfo = false;
            }
        }
        
        if(isValidNewAccInfo)
        {     httpresponse = $.get('../AjaxValidation/CheckoutStep1aEmail.aspx?email=' + $(".BAEmailTextBox").val(), function(response) {                                        
                    if(response=="BAD")
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('The email address you are trying to register with is already in use.');
                        return false ;
                    }
                    else
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('');
                        return true ;
                    }
              });
              
              if($('[id$="_BAEmailErrorLabel"]').text() != '')
                    {                        
                        isValidNewAccInfo = false;                                          
                    }                      
        }
                          
        return isValidNewAccInfo;
    }
    
     function ValidateCreateAccountInformation(doOnlyEmailLookup) 
    {    
        var isValidNewAccInfo;
	    isValidNewAccInfo = true;
	    
	    if(doOnlyEmailLookup == false)
	    {
            if($(".CreateAcctPasswordTextBox").val().length != 0)
            {
                if(!$(".CreateAcctPasswordTextBox").val().match($(".CreateAcctConfirmPasswordTextBox").val()))
                {
                    $(".CreateAcctConfirmPasswordTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountConfirmPasswordErrorLabel"]').text('Password and Confirm Password do not match.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                $(".CreateAcctPasswordTextBox").addClass("FormTextBoxError");
                $('[id$="_CreateAccountPasswordErrorLabel"]').text('Please enter a password.');
                isValidNewAccInfo = false;
            }
            
            if($(".CreateAccountFormFieldsDropDownList").val() != "-1")
            {
                if($(".CreateAcctAnswerTextBox").val().length == 0)
                {
                    $(".CreateAcctAnswerTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountPasswordResetAnswerErrorLabel"]').text('Please answer the password reset question.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                //$("._CreateAccountPasswordResetQuestions").addClass("FormTextBoxError");
                $('[id$="CreateAccountPasswordResetQuestionsErrorLabel"]').text('Please select a password reset question.');
                isValidNewAccInfo = false;
            }
        }
        
        if(isValidNewAccInfo)
        {     httpresponse = $.get('../AjaxValidation/CheckoutStep1aEmail.aspx?email=' + $(".BAEmailTextBox").val(), function(response) {                                        
                    if(response=="BAD")
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('The email address you are trying to register with is already in use.');
                        return false ;
                    }
                    else
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('');
                        return true ;
                    }
              });
              
              if($('[id$="_BAEmailErrorLabel"]').text() != '')
                    {                        
                        isValidNewAccInfo = false;                                          
                    }                      
        }
                          
        return isValidNewAccInfo;
    }
    
     function ValidateCreateAccountInformation(doOnlyEmailLookup) 
    {    
        var isValidNewAccInfo;
	    isValidNewAccInfo = true;
	    
	    if(doOnlyEmailLookup == false)
	    {
            if($(".CreateAcctPasswordTextBox").val().length != 0)
            {
                if(!$(".CreateAcctPasswordTextBox").val().match($(".CreateAcctConfirmPasswordTextBox").val()))
                {
                    $(".CreateAcctConfirmPasswordTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountConfirmPasswordErrorLabel"]').text('Password and Confirm Password do not match.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                $(".CreateAcctPasswordTextBox").addClass("FormTextBoxError");
                $('[id$="_CreateAccountPasswordErrorLabel"]').text('Please enter a password.');
                isValidNewAccInfo = false;
            }
            
            if($(".CreateAccountFormFieldsDropDownList").val() != "-1")
            {
                if($(".CreateAcctAnswerTextBox").val().length == 0)
                {
                    $(".CreateAcctAnswerTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountPasswordResetAnswerErrorLabel"]').text('Please answer the password reset question.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                //$("._CreateAccountPasswordResetQuestions").addClass("FormTextBoxError");
                $('[id$="CreateAccountPasswordResetQuestionsErrorLabel"]').text('Please select a password reset question.');
                isValidNewAccInfo = false;
            }
        }
        
        if(isValidNewAccInfo)
        {     httpresponse = $.get('../AjaxValidation/CheckoutStep1aEmail.aspx?email=' + $(".BAEmailTextBox").val(), function(response) {                                        
                    if(response=="BAD")
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('The email address you are trying to register with is already in use.');
                        return false ;
                    }
                    else
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('');
                        return true ;
                    }
              });
              
              if($('[id$="_BAEmailErrorLabel"]').text() != '')
                    {                        
                        isValidNewAccInfo = false;                                          
                    }                      
        }
                          
        return isValidNewAccInfo;
    }
    
     function ValidateCreateAccountInformation(doOnlyEmailLookup) 
    {    
        var isValidNewAccInfo;
	    isValidNewAccInfo = true;
	    
	    if(doOnlyEmailLookup == false)
	    {
            if($(".CreateAcctPasswordTextBox").val().length != 0)
            {
                if(!$(".CreateAcctPasswordTextBox").val().match($(".CreateAcctConfirmPasswordTextBox").val()))
                {
                    $(".CreateAcctConfirmPasswordTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountConfirmPasswordErrorLabel"]').text('Password and Confirm Password do not match.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                $(".CreateAcctPasswordTextBox").addClass("FormTextBoxError");
                $('[id$="_CreateAccountPasswordErrorLabel"]').text('Please enter a password.');
                isValidNewAccInfo = false;
            }
            
            if($(".CreateAccountFormFieldsDropDownList").val() != "-1")
            {
                if($(".CreateAcctAnswerTextBox").val().length == 0)
                {
                    $(".CreateAcctAnswerTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountPasswordResetAnswerErrorLabel"]').text('Please answer the password reset question.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                //$("._CreateAccountPasswordResetQuestions").addClass("FormTextBoxError");
                $('[id$="CreateAccountPasswordResetQuestionsErrorLabel"]').text('Please select a password reset question.');
                isValidNewAccInfo = false;
            }
        }
        
        if(isValidNewAccInfo)
        {     httpresponse = $.get('../AjaxValidation/CheckoutStep1aEmail.aspx?email=' + $(".BAEmailTextBox").val(), function(response) {                                        
                    if(response=="BAD")
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('The email address you are trying to register with is already in use.');
                        return false ;
                    }
                    else
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('');
                        return true ;
                    }
              });
              
              if($('[id$="_BAEmailErrorLabel"]').text() != '')
                    {                        
                        isValidNewAccInfo = false;                                          
                    }                      
        }
                          
        return isValidNewAccInfo;
    }
    
     function ValidateCreateAccountInformation(doOnlyEmailLookup) 
    {    
        var isValidNewAccInfo;
	    isValidNewAccInfo = true;
	    
	    if(doOnlyEmailLookup == false)
	    {
            if($(".CreateAcctPasswordTextBox").val().length != 0)
            {
                if(!$(".CreateAcctPasswordTextBox").val().match($(".CreateAcctConfirmPasswordTextBox").val()))
                {
                    $(".CreateAcctConfirmPasswordTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountConfirmPasswordErrorLabel"]').text('Password and Confirm Password do not match.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                $(".CreateAcctPasswordTextBox").addClass("FormTextBoxError");
                $('[id$="_CreateAccountPasswordErrorLabel"]').text('Please enter a password.');
                isValidNewAccInfo = false;
            }
            
            if($(".CreateAccountFormFieldsDropDownList").val() != "-1")
            {
                if($(".CreateAcctAnswerTextBox").val().length == 0)
                {
                    $(".CreateAcctAnswerTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountPasswordResetAnswerErrorLabel"]').text('Please answer the password reset question.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                //$("._CreateAccountPasswordResetQuestions").addClass("FormTextBoxError");
                $('[id$="CreateAccountPasswordResetQuestionsErrorLabel"]').text('Please select a password reset question.');
                isValidNewAccInfo = false;
            }
        }
        
        if(isValidNewAccInfo)
        {     httpresponse = $.get('../AjaxValidation/CheckoutStep1aEmail.aspx?email=' + $(".BAEmailTextBox").val(), function(response) {                                        
                    if(response=="BAD")
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('The email address you are trying to register with is already in use.');
                        return false ;
                    }
                    else
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('');
                        return true ;
                    }
              });
              
              if($('[id$="_BAEmailErrorLabel"]').text() != '')
                    {                        
                        isValidNewAccInfo = false;                                          
                    }                      
        }
                          
        return isValidNewAccInfo;
    }
    
     function ValidateCreateAccountInformation(doOnlyEmailLookup) 
    {    
        var isValidNewAccInfo;
	    isValidNewAccInfo = true;
	    
	    if(doOnlyEmailLookup == false)
	    {
            if($(".CreateAcctPasswordTextBox").val().length != 0)
            {
                if(!$(".CreateAcctPasswordTextBox").val().match($(".CreateAcctConfirmPasswordTextBox").val()))
                {
                    $(".CreateAcctConfirmPasswordTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountConfirmPasswordErrorLabel"]').text('Password and Confirm Password do not match.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                $(".CreateAcctPasswordTextBox").addClass("FormTextBoxError");
                $('[id$="_CreateAccountPasswordErrorLabel"]').text('Please enter a password.');
                isValidNewAccInfo = false;
            }
            
            if($(".CreateAccountFormFieldsDropDownList").val() != "-1")
            {
                if($(".CreateAcctAnswerTextBox").val().length == 0)
                {
                    $(".CreateAcctAnswerTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountPasswordResetAnswerErrorLabel"]').text('Please answer the password reset question.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                //$("._CreateAccountPasswordResetQuestions").addClass("FormTextBoxError");
                $('[id$="CreateAccountPasswordResetQuestionsErrorLabel"]').text('Please select a password reset question.');
                isValidNewAccInfo = false;
            }
        }
        
        if(isValidNewAccInfo)
        {     httpresponse = $.get('../AjaxValidation/CheckoutStep1aEmail.aspx?email=' + $(".BAEmailTextBox").val(), function(response) {                                        
                    if(response=="BAD")
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('The email address you are trying to register with is already in use.');
                        return false ;
                    }
                    else
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('');
                        return true ;
                    }
              });
              
              if($('[id$="_BAEmailErrorLabel"]').text() != '')
                    {                        
                        isValidNewAccInfo = false;                                          
                    }                      
        }
                          
        return isValidNewAccInfo;
    }
    
     function ValidateCreateAccountInformation(doOnlyEmailLookup) 
    {    
        var isValidNewAccInfo;
	    isValidNewAccInfo = true;
	    
	    if(doOnlyEmailLookup == false)
	    {
            if($(".CreateAcctPasswordTextBox").val().length != 0)
            {
                if(!$(".CreateAcctPasswordTextBox").val().match($(".CreateAcctConfirmPasswordTextBox").val()))
                {
                    $(".CreateAcctConfirmPasswordTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountConfirmPasswordErrorLabel"]').text('Password and Confirm Password do not match.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                $(".CreateAcctPasswordTextBox").addClass("FormTextBoxError");
                $('[id$="_CreateAccountPasswordErrorLabel"]').text('Please enter a password.');
                isValidNewAccInfo = false;
            }
            
            if($(".CreateAccountFormFieldsDropDownList").val() != "-1")
            {
                if($(".CreateAcctAnswerTextBox").val().length == 0)
                {
                    $(".CreateAcctAnswerTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountPasswordResetAnswerErrorLabel"]').text('Please answer the password reset question.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                //$("._CreateAccountPasswordResetQuestions").addClass("FormTextBoxError");
                $('[id$="CreateAccountPasswordResetQuestionsErrorLabel"]').text('Please select a password reset question.');
                isValidNewAccInfo = false;
            }
        }
        
        if(isValidNewAccInfo)
        {     httpresponse = $.get('../AjaxValidation/CheckoutStep1aEmail.aspx?email=' + $(".BAEmailTextBox").val(), function(response) {                                        
                    if(response=="BAD")
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('The email address you are trying to register with is already in use.');
                        return false ;
                    }
                    else
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('');
                        return true ;
                    }
              });
              
              if($('[id$="_BAEmailErrorLabel"]').text() != '')
                    {                        
                        isValidNewAccInfo = false;                                          
                    }                      
        }
                          
        return isValidNewAccInfo;
    }
    
     function ValidateCreateAccountInformation(doOnlyEmailLookup) 
    {    
        var isValidNewAccInfo;
	    isValidNewAccInfo = true;
	    
	    if(doOnlyEmailLookup == false)
	    {
            if($(".CreateAcctPasswordTextBox").val().length != 0)
            {
                if(!$(".CreateAcctPasswordTextBox").val().match($(".CreateAcctConfirmPasswordTextBox").val()))
                {
                    $(".CreateAcctConfirmPasswordTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountConfirmPasswordErrorLabel"]').text('Password and Confirm Password do not match.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                $(".CreateAcctPasswordTextBox").addClass("FormTextBoxError");
                $('[id$="_CreateAccountPasswordErrorLabel"]').text('Please enter a password.');
                isValidNewAccInfo = false;
            }
            
            if($(".CreateAccountFormFieldsDropDownList").val() != "-1")
            {
                if($(".CreateAcctAnswerTextBox").val().length == 0)
                {
                    $(".CreateAcctAnswerTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountPasswordResetAnswerErrorLabel"]').text('Please answer the password reset question.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                //$("._CreateAccountPasswordResetQuestions").addClass("FormTextBoxError");
                $('[id$="CreateAccountPasswordResetQuestionsErrorLabel"]').text('Please select a password reset question.');
                isValidNewAccInfo = false;
            }
        }
        
        if(isValidNewAccInfo)
        {     httpresponse = $.get('../AjaxValidation/CheckoutStep1aEmail.aspx?email=' + $(".BAEmailTextBox").val(), function(response) {                                        
                    if(response=="BAD")
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('The email address you are trying to register with is already in use.');
                        return false ;
                    }
                    else
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('');
                        return true ;
                    }
              });
              
              if($('[id$="_BAEmailErrorLabel"]').text() != '')
                    {                        
                        isValidNewAccInfo = false;                                          
                    }                      
        }
                          
        return isValidNewAccInfo;
    }
    
     function ValidateCreateAccountInformation(doOnlyEmailLookup) 
    {    
        var isValidNewAccInfo;
	    isValidNewAccInfo = true;
	    
	    if(doOnlyEmailLookup == false)
	    {
            if($(".CreateAcctPasswordTextBox").val().length != 0)
            {
                if(!$(".CreateAcctPasswordTextBox").val().match($(".CreateAcctConfirmPasswordTextBox").val()))
                {
                    $(".CreateAcctConfirmPasswordTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountConfirmPasswordErrorLabel"]').text('Password and Confirm Password do not match.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                $(".CreateAcctPasswordTextBox").addClass("FormTextBoxError");
                $('[id$="_CreateAccountPasswordErrorLabel"]').text('Please enter a password.');
                isValidNewAccInfo = false;
            }
            
            if($(".CreateAccountFormFieldsDropDownList").val() != "-1")
            {
                if($(".CreateAcctAnswerTextBox").val().length == 0)
                {
                    $(".CreateAcctAnswerTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountPasswordResetAnswerErrorLabel"]').text('Please answer the password reset question.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                //$("._CreateAccountPasswordResetQuestions").addClass("FormTextBoxError");
                $('[id$="CreateAccountPasswordResetQuestionsErrorLabel"]').text('Please select a password reset question.');
                isValidNewAccInfo = false;
            }
        }
        
        if(isValidNewAccInfo)
        {     httpresponse = $.get('../AjaxValidation/CheckoutStep1aEmail.aspx?email=' + $(".BAEmailTextBox").val(), function(response) {                                        
                    if(response=="BAD")
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('The email address you are trying to register with is already in use.');
                        return false ;
                    }
                    else
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('');
                        return true ;
                    }
              });
              
              if($('[id$="_BAEmailErrorLabel"]').text() != '')
                    {                        
                        isValidNewAccInfo = false;                                          
                    }                      
        }
                          
        return isValidNewAccInfo;
    }
    
     function ValidateCreateAccountInformation(doOnlyEmailLookup) 
    {    
        var isValidNewAccInfo;
	    isValidNewAccInfo = true;
	    
	    if(doOnlyEmailLookup == false)
	    {
            if($(".CreateAcctPasswordTextBox").val().length != 0)
            {
                if(!$(".CreateAcctPasswordTextBox").val().match($(".CreateAcctConfirmPasswordTextBox").val()))
                {
                    $(".CreateAcctConfirmPasswordTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountConfirmPasswordErrorLabel"]').text('Password and Confirm Password do not match.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                $(".CreateAcctPasswordTextBox").addClass("FormTextBoxError");
                $('[id$="_CreateAccountPasswordErrorLabel"]').text('Please enter a password.');
                isValidNewAccInfo = false;
            }
            
            if($(".CreateAccountFormFieldsDropDownList").val() != "-1")
            {
                if($(".CreateAcctAnswerTextBox").val().length == 0)
                {
                    $(".CreateAcctAnswerTextBox").addClass("FormTextBoxError");
                    $('[id$="_CreateAccountPasswordResetAnswerErrorLabel"]').text('Please answer the password reset question.');
                    isValidNewAccInfo = false;
                }
            }
            else
            {
                //$("._CreateAccountPasswordResetQuestions").addClass("FormTextBoxError");
                $('[id$="CreateAccountPasswordResetQuestionsErrorLabel"]').text('Please select a password reset question.');
                isValidNewAccInfo = false;
            }
        }
        
        if(isValidNewAccInfo)
        {     httpresponse = $.get('../AjaxValidation/CheckoutStep1aEmail.aspx?email=' + $(".BAEmailTextBox").val(), function(response) {                                        
                    if(response=="BAD")
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('The email address you are trying to register with is already in use.');
                        return false ;
                    }
                    else
                    {
                        $('[id$="_BAEmailErrorLabel"]').text('');
                        return true ;
                    }
              });
              
              if($('[id$="_BAEmailErrorLabel"]').text() != '')
                    {                        
                        isValidNewAccInfo = false;                                          
                    }                      
        }
                          
        return isValidNewAccInfo;
    }
    
    function enableDisableMultShipToButton(setToEnabled){
        if(setToEnabled == true){
            $(".MultShipToLinkButton:disabled").removeAttr('disabled');
        } else {
            $(".MultShipToLinkButton").attr('disabled','disabled');
        }
        
    }
    
        /* begin of the Photo Pers*/
function closeModal(){
   $('.window').hide();
}

function openModal()
{
    //Get the A tag
    var id = $('#test').attr('href');
            
    //Get the screen height and width
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();
      
    //Set heigth and width to mask to fill up the whole screen
    $('#mask').css({'width':maskWidth,'height':maskHeight});
            
    //transition effect           
    $('#mask').fadeIn(1000);      
    $('#mask').fadeTo("slow",0.8);      
      
    //Get the window height and width
    var winH = $(window).height();
    var winW = $(window).width();
              
    //Set the popup window to center
    $(id).css('top',  winH/2-$(id).height()/2);
    $(id).css('left', winW/2-$(id).width()/2);
      
    //transition effect
     $(id).fadeIn(2000);
}

/* end of the Photo Pers*/
//     var data = "cat, cat litter, cat and hat, dog, dog collar, dog leash, fish, fish fry, fishing".split(", ");
//    $("#ctl00_txtSearch").autocomplete(data);

    function openWin(pageName)
    {
        openWinWithProperties(pageName,"width=725, height=600,scrollbars=yes, menubar=no, resizable=yes");
    }
    
    function openWinWithProperties(pageName, winProperties)
    {
        window.open(pageName,null,winProperties);
    }
    
// Browser Detect

function browserDetect()
{
    if(document.getElementById("showFlash") != null)
    {
        if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) {
		    document.getElementById("showFlash").style.display = "none";
		    document.getElementById("showImage").style.display = "block";
	    }
	    else
	    {
	        document.getElementById("showFlash").style.display  = "block";
		    document.getElementById("showImage").style.display = "none";
    	
	    }
	}
}

/* jQuery BubblePopup 
    http://jqueryfordesigners.com/coda-popup-bubbles/
    Wrap the contents of the popup in a table to get the special border
    The contents may be wrapped in any element (DIV, SPAN) as long as it has 'class="bubblePopup"'
*/
$(function () {  
    $('.bubbleInfo').each(function () {    
    
    // options    
    var distance = 10;    
    var time = 250;    
    var hideDelay = 500;    
    var hideDelayTimer = null;    
    
    // tracker    
    var beingShown = false;    
    var shown = false;        
    
    var bubbleTrigger = $('.bubbleTrigger', this);    
    var bubblePopup = $('.bubblePopup', this).css('opacity', 0).css('position','absolute'); 
      
    // set the mouseover and mouseout on both element    
    $([bubbleTrigger.get(0), bubblePopup.get(0)])
        .mouseover(function () { 
            // stops the hide event if we move from the trigger to the popup element      
            if (hideDelayTimer) clearTimeout(hideDelayTimer);      
        
            // don't trigger the animation again if we're being shown, or already visible      
            if (beingShown || shown) 
            {
                return;
            } 
            else 
            {
                beingShown = true;
                // reset position of popup box        
                bubblePopup.css
                ({       
                    top: -25,          
                    left: 150,          
                    display: 'block'// brings the popup back in to view        
                })        
        
                // (we're using chaining on the popup) now animate it's opacity and position        
                .animate(
                    {top: '-=' + distance + 'px',opacity: 1}, time, 'swing', function() {          
                    // once the animation is complete, set the tracker variables          
                    beingShown = false;          
                    shown = true;        
                }); //end animate     
        }})//end mouseover
            
        .mouseout(function () {      
            // reset the timer if we get fired again - avoids double animations      
            if (hideDelayTimer) clearTimeout(hideDelayTimer);            
        
            // store the timer so that it can be cleared in the mouseover if required      
            hideDelayTimer = setTimeout(function () {        
            hideDelayTimer = null;        
        
            bubblePopup.animate(
                {top: '-=' + distance + 'px', opacity: 0}, time, 'swing', function () {
                    // once the animate is complete, set the tracker variables          
                    shown = false;          
        
                    // hide the popup entirely after the effect (opacity alone doesn't do the job)          
                    bubblePopup.css('display', 'none');        
                });//end popup.animate      
        }, hideDelay);    
    });//end trigger
    });//end bubble info
});//end function

