$(document).ready(function() {

    $.preloadImages(
        "/lib/yhst-85423705257693/background-topnav-arrow.gif",
        "/lib/yhst-85423705257693/background-dropdown.gif",
        "/lib/yhst-85423705257693/background-navitem.gif",
        "/lib/yhst-85423705257693/background-leftnav.gif",
        "/lib/yhst-85423705257693/button-view-details.gif",
        "/lib/yhst-85423705257693/button-remove.gif",
        "/lib/yhst-85423705257693/ajaxLoader.gif",
        "/lib/yhst-85423705257693/indicator.gif"
    );


    // target="_blank" is invalid XHTML, so use rel="external" instead and assign an event to links with that attribute
    // also open Gift Card Balance Inquiry link in new window -- we have to intercept this because we can't place rel or target attributes on it
    $("a[rel*='external'], div#topnav a[href='https://www.privatelabelcard.com/kohler/balanceinquiry.cfm'],  ul#leftnav a[href='https://www.privatelabelcard.com/kohler/balanceinquiry.cfm']").click(function() {
        window.open($(this).attr('href'));
        return false;
    });

    // hide Gift Card Balance Inquiry on Gifts & Gift Cards landing page
    $("table#contents-table div.thumbnail a[href='https://www.privatelabelcard.com/kohler/balanceinquiry.cfm']").parents("td.horizontal-seperator").css("display", "none");

    // search box auto-erase/auto-fill
    $("#query").click(function() {
        if($(this).val() == 'Search') { $(this).val(''); }
    }).focus(function() {
        if($(this).val() == 'Search') { $(this).val(''); }
    }).blur(function() {
        if($(this).val() == '') { $(this).val('Search'); }
    });

    // add dropdown arrow if topnav item has children
    $("ul.topnav>li:has(ul)").hover(function() {
        $(this).addClass("hasChildren");
    }, function() {
        $(this).removeClass("hasChildren");
    });

    // :last-child support is spotty so we script it
    $("ul.topnav li:hover ul li:last-child a").css("backgroundImage", "none");

    // left nav tweak - no border on sub-levels
    $("#leftnav ul").siblings("a").css("backgroundImage", "none");



    // 8/21/2009 - For gift cards, hide Yahoo's upsell syntax from users to avoid confusion
    var dollar_amount_regex = /\$[0-9]+ add \(\+\$[0-9]+\)/;
    var add_regex = / add \(\+\$[0-9]+\)/;
    $("#col2_a select").each(function() {
        if($(this).attr("name") == "Amount") {
            $(this).children("option").each(function() {
                var option_text = $(this).text();
                if(option_text.match(dollar_amount_regex)) {
                    option_text = option_text.replace(add_regex, "");
                    $(this).text(option_text);
                }
            });
        }
    });


    // sorting interface
    var sortByNameText = "Click to sort by name";
    var sortByPriceText = "Click to sort by price";
    var sortByNameClass = "sort-by-name";
    var sortByPriceClass = "sort-by-price";
    var arrowAsc = "\u25b2";
    var arrowDesc = "\u25bc";

    $(".sort-control a").click(function() {
        var sortType = $(this).hasClass(sortByNameClass) ? sortByNameClass : sortByPriceClass;

        var arrow = $(this).siblings("span:first");
        if(arrow.html() == arrowAsc) {
            $(this).hasClass(sortByNameClass) ? sortByName("desc") : sortByPrice("desc");
        }
        else if(arrow.html() == arrowDesc) {
            $(this).hasClass(sortByNameClass) ? sortByName("asc") : sortByPrice("asc");
        }

        $(".sort-control a").each(function() {
            var arrow = $(this).siblings("span:first");

            if(!$(this).hasClass(sortType)) {
                $(this).removeClass("activeSort");
            }
            else {
                $(this).addClass("activeSort");
                if(arrow.html() == arrowAsc) {
                    arrow.html(arrowDesc);
                    $(this).attr("title", ( $(this).hasClass(sortByNameClass) ? sortByNameText : sortByPriceText ) + " ascending");
                }
                else if(arrow.html() == arrowDesc) {
                    arrow.html(arrowAsc);
                    $(this).attr("title", ( $(this).hasClass(sortByNameClass) ? sortByNameText : sortByPriceText ) + " descending");
                }
            }
        });

        return false;
    });



    // modal lightbox thing ("View Larger")
    $("#itemarea a").nyroModal({
        type: 'image',
        regexImg: '',
        padding: 0,
        title: $(this).attr("title"),
        closeButton: '<a href="#" class="nyroModalClose" id="closeBut" title="Close">X</a>'
    });



    // Cross-sell/related items tweaks
    crossSellTweaks();



    // Checkout tweaks
    $("#yahoo-store-checkout table.ys_basket th:not(.ys_last)").css("text-align", "left");
    $("#yahoo-store-checkout table.ys_basket tbody td span.ys_itemInfo em a").text("").append('<img src="/lib/yhst-85423705257693/button-remove.gif" alt="[remove]" />');
    $("#yahoo-store-checkout table.ys_basket tr.ys_orderLine.ys_evenRow td:contains('Subtotal')").siblings("td").andSelf().css("padding-top", "15px");        // chained classes don't work in IE6, plus we need to make sure we're only affecting the row with the subtotal
    $("#yahoo-store-checkout .ys_majorSection h4:contains('Shipping Options')").addClass("jQuerySpecial");
    $("#yahoo-store-checkout .ys_majorSection h4:contains('Gift Message')").addClass("jQuerySpecial");
    /*$("#yahoo-store-checkout #ys_giftWrap #labelgift-wrap-checkbox strong").remove();
    $("#yahoo-store-checkout #ys_giftWrap #gift-wrap-checkbox").remove();
    $("#yahoo-store-checkout #ys_giftWrap label:contains('Gift wrap my order for no additional charge.')").remove();*/
    var giftWrapText = $("#yahoo-store-checkout #ys_giftWrap label[for='gift_wrap']").text();
    giftWrapText = giftWrapText.replace(/wrap/, "box");
    $("#yahoo-store-checkout #ys_giftWrap label[for='gift_wrap']").text(giftWrapText);
    $("#yahoo-store-checkout .ys_sideCart td.ys_itemInfo br").replaceWith(" ");
    $("#yahoo-store-checkout .ys_sideCart tr.ys_orderLine:first").before('<tr><td colspan="3" id="sideCartBackgroundCell"></td></tr>');
	$("#yahoo-store-checkout #ys_confirmation h4:contains('Confirmation')").css("display", "none");
    $("#yahoo-store-checkout #ys_orderStatus h4:contains('Confirmation')").css("display", "none");


    // Shuffle the cart/checkout DOM around
    $("#yahoo-store-checkout .breadcrumbs").appendTo("#bodycontent");
    $("#yahoo-store-checkout .top-message-box").appendTo("#bodycontent");
    $("#yahoo-store-checkout #ys_progress").prependTo("#formerly_fake_h1");
    $("#yahoo-store-checkout #ys_progress span span.ys_progressLabel:not(:last)").append('<span class="arrow">&nbsp;&rsaquo;</span>');
    $("#yahoo-store-checkout #formerly_fake_h1").appendTo("#bodycontent");
    $("#yahoo-store-checkout #ys_pageBody").appendTo("#bodycontent");


    // IE6 fixes
    if(jQuery.browser.msie && parseInt(jQuery.browser.version) <= 6) {
        // add :hover pseudoclass support to certain things
        $("ul.topnav li, #contents-table td.horizontal-seperator, table.ystore-cross-sell-table tr.ystore-cross-sell-row td, #yahoo-store-checkout input.ys_submitLinkBtn").hover(function() {
            $(this).addClass("ie6_hovering");
        }, function() {
            $(this).removeClass("ie6_hovering");
        });
    }


    // IE6/IE7 fixes
    if(jQuery.browser.msie) {
        // this box takes up space when it's empty, so we hide it
        if($("#ys_pageMessage:empty").length > 0) {
            $("#ys_pageMessage").css("display", "none");
        }

        // In the checkout make sure only one radio button is checked when page is returned with errors
        if($("#useShippingRadio:checked").length > 0 && $("#useBillingRadio:checked").length > 0) {
            $("#useShippingRadio").attr("checked", false);
        }
    }


    // Safari/Chrome font/padding tweaks
    if(jQuery.browser.safari)
    {
        $("ul.topnav li a").css({"height": "25px", "padding-top": "10px"});
        $("ul.topnav ul li a").css({"height": "auto", "padding-top": "5px"});
        $("#footer").css({"height": "40px", "padding-top": "13px"});
        $("input.gift-message").css("width", "295px");
        $("input#card-number").css("width", "155px");
    }

});



// Yahoo's cross sell code runs after $(document).ready(), so we have to retry this code until Yahoo is done generating the elements

var CROSS_SELL_RETRY_LIMIT = 25;
var CROSS_SELL_RETRY_WAIT = 200;   // in milliseconds
var crossSellRetryAttempts = 0;

function retryCrossSellTweaks() {
    crossSellRetryAttempts++;
    crossSellTweaks();
}

function crossSellTweaks() {
    if(!($("#ys_relatedItems td.ystore-cross-sell-cell").length > 0)) {
        if(crossSellRetryAttempts < CROSS_SELL_RETRY_LIMIT) {
            setTimeout(retryCrossSellTweaks, CROSS_SELL_RETRY_WAIT);
        }
        return;
    }

    // Remove "Price: " from the text
    $("#ys_relatedItems td.ystore-cross-sell-cell p.ystore-cross-sell-product-price, #ys_relatedItems td.ystore-cross-sell-cell p.ystore-cross-sell-product-reg-price").each(function() {
        var price = $(this).text();
        $(this).text(price.replace("Price: ", ""));
    });

    // add a View Details button to cross-sell/related items
    $("body#itemtype #ys_relatedItems td.ystore-cross-sell-cell").each(function() {
        var buttonContainer = $(document.createElement("div")).addClass("ystore-cross-sell-order-button-container");
        var itemLink = $(document.createElement("a")).attr({
            title: "View Details",
            href: $(this).children("a").attr("href")
        });
        var button = $(document.createElement("img")).attr({
            "src": "/lib/yhst-85423705257693/button-view-details.gif",
            "alt": "View Details"
        });
        $(itemLink).append(button);
        $(buttonContainer).append(itemLink);
        $(this).append(buttonContainer);
    });
}





// sorting functions
function sortText(a, b) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
}

function sortTextDesc(a, b) {
    return ((b < a) ? -1 : ((b > a) ? 1 : 0));
}	

function sortNumeric(a, b) {
    return a - b;
}

function sortNumericDesc(a, b) {
    return b - a;
}

function getElementText(node, numeric) {
    if(node.childNodes[0] && node.childNodes[0].hasChildNodes()) {
        t = node.childNodes[0].innerHTML;
    } else {
        t = node.innerHTML;
    }

    if(numeric) {
        myregexp = /[^\d\.]/g;
        t = t.replace(myregexp, "");
    }

    return t;
}

function sortByName(direction) {
    var nameNodes = $("div.name").get();
    var names = new Array();

    for(var i = 0; i < nameNodes.length; i++) {
        names.push(getElementText(nameNodes[i], false));
    }

    if(direction == "asc") {
        names = names.sort(sortText);
    } else {
        names = names.sort(sortTextDesc);
    }

    //var newTable = '';
    for(var i = 0; i < names.length; i++) {
        $("div.name:containsCustom('" + names[i] + "')", "table#contents-table").parents("tr.product-row").appendTo("table#contents-table");   // custom selector
        /*newTable += '<tr class="product-row">';
        newTable += $("div.name:containsCustom('" + names[i] + "')", "table#contents-table").parents("tr.product-row").html();
        newTable += "</tr>";*/
    }

    //$("table#contents-table").html(newTable);
}

function sortByPrice(direction) {
    var priceNodes = $("div.price, div.price-bold, div.sale-price-bold").get();

    var prices = new Array();

    for(var i = 0; i < priceNodes.length; i++) {
        prices.push(getElementText(priceNodes[i], true));
    }

    if(direction == "asc") {
        prices = prices.sort(sortNumeric);
    } else {
        prices = prices.sort(sortNumericDesc);
    }

    for(var i = 0; i < prices.length; i++) {
        $("div.price:contains('" + prices[i] + "'), div.price-bold:contains('" + prices[i] + "'), div.sale-price-bold:contains('" + prices[i] + "')", "table#contents-table").parents("tr.product-row").appendTo("table#contents-table");
    }
}

