﻿$(document).ready(function() {

    if ($('#slider').length > 0) {
        var navTextHiddenField = document.getElementById("sliderBottomNavigationText");
        var listOfNavText = [];
        listOfNavText = navTextHiddenField.value.split(',');
        $('#slider').nivoSlider({
            controlNavThumbs: false,
            controlNavThumbsFromRel: false,
            bottomNavigationText: listOfNavText
        });

        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);

    $('.modal').modalpop({ speed: 700 });

    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');
    }


    $('#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);
    }

    $('#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');
    }

    $('#LabelViewPrint').click(function() {
        $('#LabelWrapper').printElement({
            printBodyOptions:
                {
                    styleToAdd: '',
                    classNameToAdd: 'ReturnLabelPrintCss'
                }
        });
    });

    $('[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: '#0554C1'
              },
              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 - <b>Automatically</b> and receive <b>$1.99 shipping</b>  on all Auto Refill 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: '#1b76bc'
                  },
                  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: '#1b76bc'
              },
              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: '#1b76bc'
              },
              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
                    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 Cart on the item(s) you would like to add to the cart.");
                return false;
            }
        }
    });

    $('[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$="_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;
            }
        }
    });



    //FAQ
    $('a.fAQLink', this).toggle(function() {
        $(this).next().slideDown('slow');
    }, function() {
        $(this).next().slideUp('slow');
    });

    $('[id$="_SHAlsoShippingAddressRadioButton"]').click(function() {
        //determineRadioButtonCheck(2);
        $('[id$="_SHDifferentAddressRadioButton"]').attr('checked', false);
        $('[id$="_SHMultipleAddressRadioButton"]').attr('checked', false);
        if (!$(".ShippingAddressFormFields").hasClass("FormIsHidden")) {
            $(".ShippingAddressFormFields").addClass('FormIsHidden');
            hideShippingAddressForm();
            //removeErrorClasses();
            $(".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);

    //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_ContentPlaceHolder1_EmailUnsubscribe1_EmailAddressTextBox').blur(trimText);
    $('#ctl00_ContentPlaceHolder1_EmailUnsubscribe1_ConfirmEmailAddressTextBox').blur(trimText);
    $('#ctl00_ContentPlaceHolder1_EmailSignup1_EmailAddressTextBox').blur(trimText);
    $('#ctl00_ContentPlaceHolder1_EmailSignup1_ConfirmEmailAddressTextBox').blur(trimText);

    function trimText() {
        var textValue = this.value;
        textValue.trim();
        this.value = textValue.trim();
    }

    // Tabs
    $('ul.css-tabs').tabs('> .css-panes');

    //Image Swap
    $('.altImagesStacked').click(swapImage);


    //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 == 584) {
        $('.zoomImage').jqzoom(options);
        $('#zoomIcon').show();
    }
    else {
        $('#zoomIcon').hide();
    }

    $('.zoomImage').click(zoomClick);

    // Dynamic Dropdown
    $('.dropDown').hoverIntent({
        sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)    
        interval: 100, // number = milliseconds for onMouseOver polling interval    
        over: windowSlideDown, // function = onMouseOver callback (REQUIRED)    
        timeout: 100, // number = milliseconds delay before onMouseOut    
        out: windowSlideUp // function = onMouseOut callback (REQUIRED)
    });

    function windowSlideDown() {
        $('div.dropDownWrapper', this).slideDown('slow');
        $('div.dropDownWrapperRt', this).slideDown('slow');
    }
    function windowSlideUp() {
        $('.dropDownWrapper', this).slideUp('slow');
        $('.dropDownWrapperRt', this).slideUp('slow');
    }


    function mycarousel_initCallback(carousel) {
        // Disable/Pause autoscrolling if the user clicks the prev or next button.
        carousel.buttonNext.bind('click', function() {
            //carousel.startAuto(0);
            carousel.stopAuto();
        }, function() {
            carousel.startAuto();
        });

        carousel.buttonPrev.bind('click', function() {
            //carousel.startAuto(0);
            carousel.stopAuto();
        }, function() {
            carousel.startAuto();
        });

        // Pause autoscrolling if the user moves with the cursor over the clip.
        carousel.clip.hover(function() {
            carousel.stopAuto();
        }, function() {
            carousel.startAuto();
        });
    };




    if (document.getElementById("gatewayWrapper") != null) {
        jQuery('.jcarousel-skin-home').jcarousel({
            scroll: 4,
            size: 15,
            visible: 4
        });
    }
    else {
        jQuery('.jcarousel-skin-home').jcarousel({
            scroll: 4
        });
    }

    jQuery('.jcarousel-skin-tango').jcarousel({
        scroll: 5
    });

    jQuery('.jcarousel-skin-tangovert').jcarousel({
        scroll: 3,
        size: 9,
        visible: 3,
        vertical: true
    });







    //Browser Detect
    browserDetect();

});                                        // End Doc Ready

///////////////////////////////
//// FUNCTIONS GO HERE  //////
///////////////////////////////
    

//Image Swap
 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');
        
        $('.zoomImage').children().attr('src', smallSource);
        $('.zoomImage').attr('path', smallPath);
        $('.zoomImage').attr('href', smallSource.replace(/292/g,'584'));
        $('.zoomImage').maxSize(300);
       
        $(this).children().attr('src', largeSource);
        $(this).children().attr('path', largePath);
    }
    
    //Zoom Click
function zoomClick() {
    var path = $('.zoomImage').attr('path');
    //alert(path);
    window.open(path.replace('~', '../'),'window','height=600, width=600, resizable=yes, scrollbars=yes');
    //window.open(this.href,'window','height=600, width=600, resizable=yes, scrollbars=yes');
    return false;
}

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
function shippingBoxCheckedHelper(ValidateTheBillingAddress) {
    //determineRadioButtonCheck(1);
    $('[id$="_SHAlsoShippingAddressRadioButton"]').attr('checked', false);
    $('[id$="_SHMultipleAddressRadioButton"]').attr('checked', false);
    $(this).addClass("DifferentAddressRadioButtonChecked");
    $(".ShippingAddressFormFields").show();
    $(".AddressBookContainer").show();
    $(".RequiredPhoneText").show();
    $(".ShippingAddressFormFields").removeClass('FormIsHidden');
    //if($(".ShippingAddressesRadioButtons").hasClass("ShippingAddressesRadioButtonsChecked")) {
    //alert("4");
    //toggleShippingAddressForm(true, true);
    //toggleShippingAddressForm(false, false)
    //$(".ShippingAddressesRadioButtons input")[0].checked = true;
    //$(".ShippingAddressesRadioButtons").removeClass("ShippingAddressesRadioButtonsChecked");
    //}

    var isValidSH;
    removeErrorClasses();
    //if ($(".SHAlsoShippingAddressRadioButton").hasClass("SHAlsoShippingAddressRadioButtonChecked")) {
    //        alert("5");
    //        //$(".SHMultipleAddressRadioButton:disabled").removeAttr('disabled');
    //        //$(".SHAlsoShippingAddressRadioButton").removeClass("SHAlsoShippingAddressRadioButtonChecked");
    //        //toggleShippingAddressForm(false, true);
    //        checkForBillingAddressChange(false);
    //        
    //         if($.cookie('addChecked') == 'show'){
    //            $.cookie('addChecked', null,{ expires: -1 });
    //         }
    //    } 
    //    else 
    //    {
    //        if(ValidateTheBillingAddress == true){
    //            isValidSH = validateBillingAddress();
    //        }// closes if
    //        
    //        if(isValidSH) {
    //            alert("6");
    //            //$(".SHMultipleAddressRadioButton").attr('disabled', 'disabled');
    //            $(".SHAlsoShippingAddressRadioButton").addClass("SHAlsoShippingAddressRadioButtonChecked");
    //            $('.SHAlsoShippingAddressRadioButton input').attr('checked', 'true');
    //            $(".SHErrorMessageLabel").html("");
    //            toggleShippingAddressForm(true, true);
    //            checkForBillingAddressChange(true);
    //            
    //            if($.cookie('addChecked') == null){
    //                $.cookie('addChecked', 'show');
    //            }

    //            if ($(".ShippingAddressesRadioButtons input").length > 0) {
    //                $(".ShippingAddressesRadioButtons input")[0].checked = true;
    //            }
    //        } 
    //        else {
    //            alert("7");
    //            //$(".SHMultipleAddressRadioButton:disabled").removeAttr('disabled');
    //            $('.SHAlsoShippingAddressRadioButton input').removeClass("SHAlsoShippingAddressRadioButtonChecked");
    //            $('.SHAlsoShippingAddressRadioButton input').removeAttr("checked");
    //             if($.cookie('addChecked') == 'show'){
    //                $.cookie('addChecked', null,{ expires: -1 });
    //             }
    //        }
    //    }

}

    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");
                $('[id$="_BALastNameErrorLabel"]').text('Paypal requires first name and last name combined length to be less than 31 characters.');

                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>", "");
                }
                billingErrorList += "<li>Paypal requires first name and last name combined length to be less than 31 characters.</li>";
                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 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*/

//Modal
   $.fx.speeds._default = 1000;
	$(function() {
	
	var dlg = $('#dialogQO').dialog({
			autoOpen: false,
			show: 'blind',
			hide: 'blind',
			modal:true,
			width: '400px'
		
		});
		
		dlg.parent().appendTo(jQuery("form:first"));
		
		$('.modalOpener').click(function() {
			$('#dialogQO').dialog('open');
			return false;
		});
	});
	 
	 
/* Removed from checkout step 2a */

 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;
    }    
    // 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";
    	
	    }
	}
}

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 openWin(pageName) {
    window.open(pageName, null, "width=660, height=480,scrollbars=yes, menubar=no, resizable=yes");
}

//SCOTT- 9/13/2006 Javascript does not support method overloading so I had to create a function of a different name.
function openWinWithProperties(pageName, winProperties) {
    window.open(pageName, null, winProperties);
}

function OpenVeriSign() {
    window.open('https://seal.verisign.com/splash?form_file=fdf/splash.fdf&dn=www.wdrake.com&lang=en');
}

function popUpBanner(banner_clicked) {
    var _popUpBannerPath;
    var _title;
    
    if (banner_clicked == "FS") {
        _popUpBannerPath = "../images/FreeShipping/pop_fs_15_walterdrake.gif";
        _title = "FreeShippingOffer";
    } else {
        _popUpBannerPath = "../images/FreeShipping/pop_cb_10_walterdrake.gif";
        _title = "CashBackOffer";
    }
    win = window.open(_popUpBannerPath, _title, "width=285,height=435,left=150,top=100,menubar=0,toolbar=0,status=0,titlebar=0,resizable=1");
    win.document.title = "FreeShipping.com Offer";
}

function getY(oElement) {
    var iReturnValue = 0;
    while (oElement != null) {
        iReturnValue += oElement.offsetTop;
        oElement = oElement.offsetParent;
    }

    return iReturnValue;
}

function getX(oElement) {
    var iReturnValue = 0;
    while (oElement != null) {
        iReturnValue += oElement.offsetLeft;
        oElement = oElement.offsetParent;
    }
    return iReturnValue;
}

function HideButton() {
    var iReturnValue = 0;
    //    setTimeout('document.getElementById("divPopup").style.visibility="hidden"',500);
}

function DrillDetail(URLDetail, object) {
    var timeOutOjb = null;
    //Set hidden text value, so serverside knows what to load it later
    var objQuickEntry = document.getElementById('<%=QuickEntryFlag.ClientID.ToString()%>');
    var objPopup = document.getElementById('divPopup');

    document.getElementById('<%=PopupURLString.ClientID.ToString()%>').value = document.getElementById(object.id);
    if (document.getElementById('<%=PopupURLString.ClientID.ToString()%>').value != '') {
        if (timeOutOjb != null) {
            clearTimeout(timeOutOjb);
            timeOutOjb = null;
        }
        if (objQuickEntry.getAttribute('value') != 'DISABLE') {

            objPopup.style.left = (getX(object) + 15) + 'px'; // getY(objImage) + document.documentElement.scrollLeft;

            var browser = navigator.appName;
            if (browser == "Microsoft Internet Explorer") {
                objPopup.style.top = (getY(object) + 30) + 'px'; // getY(objImage) + document.documentElement.scrollTop;
            } else {
                objPopup.style.top = (getY(object) + 10) + 'px'; // getY(objImage) + document.documentElement.scrollTop;
            }
            objPopup.style.visibility = 'visible';
            //hide window after 2 seconds
            timeOutOjb = setTimeout('document.getElementById("divPopup").style.visibility="hidden"', 2000);

        }
    }
}

function ShowProgressIndicator() {
    if (!(window.Page_ClientValidate) || (typeof (Page_ClientValidate) == 'function' && Page_ClientValidate() == true)) {
        document.getElementById('ProgressDiv').style.display = "";
        setTimeout('document.images["ProgressIndicator"].src="../images/ui/uploadprogress.gif"', 200);
    }
}

function ChangeClass(My_Element, My_Class) {
     My_Element.setAttribute("className", My_Class); 
     My_Element.setAttribute("class", My_Class);
}

/* 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
                ({       
                    right:-150,top: 0,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

