var itemTimer;

jQuery(function($) {
    // Your code using failsafe $ alias here...

    $('.itemRow input[type=checkbox], .tabnav, .tabdivBottom input[type=checkbox]:not([disabled=disabled])').click(function() {
        blockFilters();
    });

    $('.selectWrapper select').change(function() {
        blockFilters();
    });

    

    $("input[type=radio]").checkbox({
        cls: 'jquery-radio',
        empty: '/images/spacer.gif'
    });

    $("a.itemLink", ".mainFilters").live("click", function() {
        var checkbox = $(this).parents(".itemWrapper").find("input[type=checkbox]");
        checkbox.attr('checked', checkbox.attr('checked') ? false : true);
        return false;
    });

    $(".enterZip").live("click", function() {
        $(this).parent().siblings(".shipData").toggle();
        return false;
    });

    $("ul.sf-menu").superfish({
        animation: { height: 'show' },
        speed: 300,
        autoArrows: false,
        dropShadows: false
    }).find("ul").bgIframe();

    $(".itemRow").equalHeights(true);
    $(".modCarousel .items").equalHeights(true);
    $(".columnRow").equalHeights(true);

    $(".itemWrapper ul.swatchList li a").live("mouseover", function() {
        $(this).parents(".swatchList").find("a").removeClass("active");
        $(this).addClass("active");
        var newImg = $(this).find(".swatchAlt").html();
        $(this).parents(".itemWrapper").find(".itemImage").attr({ src: newImg });
    });

    $('.altViews li a').live("click", function() {
        //the new image
        var newimg = $(this).attr("href");

        //update active status
        var altViews = $(".altViews li")
        altViews.each(function(i) {
            var children = altViews.eq(i).children("a");
            children.each(function(j) {
                if (newimg.replace('/large/', '').replace('/regular/', '') == children.eq(j).attr("href").replace('/large/', '').replace('/regular/', '')) {
                    children.eq(j).addClass("active");
                } else {
                    children.eq(j).removeClass("active");
                }
            });
        });

        //find the regular image
        $(".productImage img.mainImage").attr({ src: newimg.replace('/large/', '/regular/') });

        //find the large image
        $(".imageViewer .mainImage img").attr({ src: newimg.replace('/regular/', '/large/') });

        return false;
    });

    //Banner slide show
    $("#homeSSW").cycle({
        fx: 'fade',
        speed: 300,
        timeout: 8000,
        pager: '.nav'
    });

    $(".txtCalloutCol .truncate").truncate({
        max_length: 224,
        more: "Learn More",
        less: "Show Less"
    });

    $(".welcomeMsg .truncate").truncate({
        max_length: 127,
        more: "Learn More",
        less: "Show Less"
    });

    $(".detailsRight .truncate").truncate({
        max_length: 200,
        more: "Show More",
        less: "Show Less"
    });

    // dialog windows 
    $(".uiModal").dialog({
        autoOpen: false,
        width: "720px",
        bgiframe: true,
        modal: true,
        resizable: false,
        live: false,
        buttons: {
            Close: function() {
                $(this).dialog('close');
            }
        }
    });

    $(".uiDialog").dialog({
        autoOpen: false,
        width: "720px",
        bgiframe: true,
        modal: false,
        resizable: false,
        buttons: {
            Close: function() {
                $(this).dialog('close');
            }
        }
    });

    $(".recentTool .recent").live("click", function() {
        $(".recentDialog").dialog("open");
        return false;
    });

    $(".productImage").live("click", function() {
        $(".enlargeView").dialog("open");
        return false;
    }).css("cursor", "pointer");
    // END dialog windows 

    $(".tabModule .tabsRow").tabs();
    $(".cartSupport .supportTabs").tabs();

    // carousels 
    $(".modCarousel4 .scrollable").scrollable({
        size: 4,
        items: ".items",
        clickable: false
    });

    $(".modCarousel5 .scrollable").scrollable({
        size: 5,
        items: ".items",
        clickable: false
    });

    $(".alsoPurchased .scrollable").scrollable({
        size: 5,
        items: ".items",
        clickable: false
    });

    $(".otherItems .scrollable").scrollable({
        size: 5,
        items: ".items",
        clickable: false
    });

    $(".scrollable").each(function() {
        var mcHeight = $(".itemWrapper:first", this).height();
        $(this).css({ 'height': mcHeight });
    });
    // END carousels 

    $(".swatchList a").cluetip({
        cluetipClass: 'swatch',
        width: '178px',
        positionBy: 'fixed',
        topOffset: '-122px',
        leftOffset: '-115px',
        local: true,
        dropShadow: false,
        showTitle: false
    });

    // Item Added to Cart Slider
    $("#item-dialog").mouseover(function() { clearTimeout(itemTimer); });
    $("#item-dialog").mouseout(function() { itemTimer = setTimeout(function() { hideItemSlider(); }, 1500); });
    // END Item Added
    /* START QUICK BUY */
    var sBuyNow = '';
    sBuyNow += '<div id="detailView">';
    sBuyNow += '	<input type="hidden" id="hdn_sel" />';
    sBuyNow += '	<h5 class="hdng2 hdng-item-dialog">Product Details</h5>';
    sBuyNow += '	<div class="close">CLOSE X</div>';
    sBuyNow += '	<div class="pad">';
    sBuyNow += '    	<div class="leftCol">';
    sBuyNow += '    		<div class="productImage"><img class="mainImage" src="/images/spacer.gif" alt="" /></div>';
    sBuyNow += '	        <div class="productDetails">';
    sBuyNow += '            	<div class="rating" id="rating" style=" width:85px; margin: 0 auto; float:none;">';
    sBuyNow += '            	</div>';
    sBuyNow += '	            <br /><div class="clear">&nbsp;</div>';
    sBuyNow += '	        </div>';
    sBuyNow += '	        <div class="productDetails center">';
    sBuyNow += '                <a class="itemAnchor" href="#">Go to Product &raquo;</a>';
    sBuyNow += '	        </div>';
    sBuyNow += '	    </div>';
    sBuyNow += '    	<div class="rightCol">';
    sBuyNow += '	    	<strong class="itemTitle center larger"><a class="itemAnchor" href="#" id="hdngItemName"></a></strong>';
    sBuyNow += '	        <div class="productDetails">';
    sBuyNow += '	        	<div class="itemSku">';
    sBuyNow += '	        		sku# <span id="spanSKU"></span>';
    sBuyNow += '	        	</div>';
    sBuyNow += '	        </div>';
    sBuyNow += '    		<p id="pShortDesc"></p>';
    sBuyNow += '    		<div id="Selections"></div>';
    sBuyNow += '    		<div class="productDetails">';
    sBuyNow += '    		    <div class="detailsRow">';
    sBuyNow += '    		        <div class="itemPrice">';
    sBuyNow += '    		            Price: <span id="spanPrice">';
    sBuyNow += '    		            </span>';
    sBuyNow += '    		            <div id="itemPricing"></div>';
    sBuyNow += '    		        </div>';
    sBuyNow += '                    <div class="itemMSRPPrice">';
    sBuyNow += '    		            MSRP Price: <span id="spanMSRPPrice">';
    sBuyNow += '    		            </span>';
    sBuyNow += '    		            <div id="itemMSRPPricing"></div>';
    sBuyNow += '    		        </div>';
    sBuyNow += '    		    </div>';
    sBuyNow += '    		</div>';
    sBuyNow += '            <div class="productDetails">';
    sBuyNow += '                <div class="detailsRow">';
    sBuyNow += '                    <label class="rowLabel">Select a Qty</label>';
    sBuyNow += '                    <input type="text" class="text integer" style="width:30px;" id="txtQty" maxlength="4" name="txtQty" value="1" />';
    sBuyNow += '                </div>';
    sBuyNow += '            </div>';
    sBuyNow += '            <div class="productDetails" id="divRecipient">';
    sBuyNow += '                <div class="detailsRow">';
    sBuyNow += '                    <label class="rowLabel">Ship To</label>';
    sBuyNow += '                    <select id="drpRecipient"></select>';
    sBuyNow += '                    <div id="divNew" class="hide">';
    sBuyNow += '                        <input type="text" id="txtRecipient" class="text" columns="30" maxlength="50" style="width:130px;" />';
    sBuyNow += '                        <p class="note">Enter full name. We\'ll ask for delivery information at checkout.</p>';
    sBuyNow += '                    </div>';
    sBuyNow += '                </div>';
    sBuyNow += '            </div>';
    sBuyNow += '		    <div class="clear">&nbsp;</div>';
    sBuyNow += '		    <div id="emailContainer"></div>';
    sBuyNow += '    	    <div style="margin-top:10px;">';
    sBuyNow += '    	        <span class="btnWrapper btnAddToCart"><input type="image" src="/images/buttons/btn_addToCart.gif" class="btn" id="btnAdd2Cart" value="Add To Cart" /></span>';
    sBuyNow += '                <span class="btnWrapper btnWishlist"><input type="image" src="/images/buttons/btn_addToWishlist.gif" id="btnWishlist" class="" value="[ + ] Add To Wishlist" /></span>';
    sBuyNow += '    	    </div>';
    sBuyNow += '    	</div>';
    sBuyNow += '	    <div class="clear">&nbsp;</div>';
    sBuyNow += '    </div>';
    sBuyNow += '</div>';

    $(".itemWrapper").each(function() {
        var me = $(this);
        if ($(this).hasClass("GftCrt")) {
            return;
        }
        var wrp = $(this).find("span.btnWrapper");
        $(this).mouseenter(function() { wrp.show(); $(this).find(".itemTitle a").addClass("underlined"); });
        $(this).mouseleave(function() { wrp.hide(); $(this).find(".itemTitle a").removeClass("underlined"); });

        var btn = wrp.find("input");
        btn.click(function() {
            $("#detailView").remove();
            $(".itemWrapper").css({ "z-index": "1" });
            me.css({ "z-index": "100" });
            var ItemId = me.find("input[type=hidden]").val();
            $.getJSON("/ajax.aspx?F=BuyNow&ItemId=" + ItemId, function(o) {
                if (!o.Success) return;
                $("body").prepend(sBuyNow);
                var dtl = $("#detailView");
                // initialize the selections script
                window[o.VariableName] = new Selections(o.VariableName, o.HiddenId, o.ContainerId, o.CurrentItemId, o.EnableInventory, o.AddToCartButtonId, o.EmailContainerId, o.QuantityTextId, o.RecipientDropDownId, o.RecipientTextId, true);

                // show/hide recipient information
                if (o.MultipleShipTo) {
                    $("#divRecipient").show();
                    var html = '';
                    for (var r = 0; r < o.Recipients.length; r++) {
                        var R = o.Recipients[r];
                        html += '<option value="' + R.Value + '">' + R.Text + '</option>';
                    }
                    html += '<option value="OtherSpecify">Other (specify)</option>';
                    $("#drpRecipient").change(function() { $(this).val() == "OtherSpecify" ? $("#divNew").show() : $("#divNew").hide(); }).html(html);
                    $("#txtRecipient").keypress(function(e) { return window[o.VariableName].HandleKeyPress(e); });
                } else {
                    $("#divRecipient").hide();
                }

                // initialize the properties
                for (var p = 0; p < o.Properties.length; p++) {
                    var P = o.Properties[p];
                    window[o.VariableName].AP(P.PropertyId, P.Name, P.PropertyImage, P.ImageAlt, P.SelectionType, P.SwatchPath, P.DisplayCurrentValue);
                    for (var s = 0; s < P.Selections.length; s++) {
                        var S = P.Selections[s];
                        window[o.VariableName].AS(S.PropertyId, S.SelectionId, S.Selection, S.Image, S.SwatchAlt);
                    }
                }

                // initialize the selections
                for (var i = 0; i < o.Items.length; i++) {
                    var I = o.Items[i];
                    var SelectionIds = new Array();
                    var sids = I.SelectionIds.split(",");
                    for (var x = 0; x < sids.length; x++) {
                        if (sids[x] && sids[x] != '' && parseInt(sids[x])) SelectionIds[SelectionIds.length] = parseInt(sids[x]);
                    }
                    var aIP = new Array();
                    for (var ip = 0; ip < I.ItemProperties.length; ip++) {
                        var prop = I.ItemProperties[ip];
                        aIP[aIP.length] = new IP(prop.Type, prop.Target, prop.Value);
                    }
                    window[o.VariableName].AI(I.ItemId, SelectionIds, I.InventoryQty, I.InventoryAction, I.InventoryActionThreshold, I.BackorderDate, aIP);
                }

                // create the selections controls
                window[o.VariableName].Create();

                // allow only numeric values in quantity box and handle enter button
                $(".integer").numeric().keypress(function(e) { return window[o.VariableName].HandleKeyPress(e); });

                // bind the add to cart call
                $("#btnAdd2Cart").click(function() {
                    window[o.VariableName].AddToCart(processAddToCart); return false;
                });

                // bind the add to wishlist call
                $("#btnWishlist").click(function() {
                    window[o.VariableName].AddToWishlist(function(o) { if (!o.Success) return; window.location = o.Url; }); return false;
                });

                $(".imgEnlarge").click(function() { NewWindow("/store/Enlarge.aspx?ItemId=" + window[o.VariableName].h.val(), 'EnlargeView', 720, 475, 'Yes', 'No') });

                // center the window, add dragging capability, bind click event for close button, and show the window
                dtl.center().draggable({ handle: ".hdng-item-dialog" }).find(".close").click(function() { dtl.remove(); return false; }).show();

                ////uncomment to keep window centered on page
                //$(window).scroll(function() {
                //    dtl.center();
                //});
            });

            return false;
        });
    });
    /* END QUICK BUY */
    $(".homeColumns .roundedBtm").matchHeights();

    $(".itemTitle a", ".itemRow").matchHeights();

    $(".prodFinder").each(function() {
        var dropdown = $(".dropDown", this);
        var finderCont = $(this);

        dropdown.hide().css("top", "28px");

        $(".finderBtn", this).live("click", function() {
            dropdown.show().bgiframe();
            $(this).css("background-position", "0 -24px");

            finderCont.mouseleave(function() {
                dropdown.hide()
                $(".finderBtn", this).css("background-position", "0 0");
            });

            $("select, dl, dt, dd", finderCont).mouseleave(function(event) { event.stopPropagation(); });

            $(".dropDownWrapper, .shadowRight", finderCont).matchHeights();
            $(".shadowBtm, .shadowRight", finderCont).css({ "opacity": 0.25 });

            return false;
        });
    });

    $(".dd-trigger", ".dd-wrapper").live("click", function() {

        var dropwrapper = $(this).parents(".dd-wrapper");
        var dropdown = dropwrapper.find(".dd-content");

        dropdown.css("left", "0");

        dropwrapper.mouseleave(function() {
            dropdown.css("left", "-9999em");
        });

        return false;
    });

    $(".mediaLink").live("click", function() {
        $.blockUI({
            message: $(".mediaWindow"),
            bindEvents: false,
            css: {
                width: '500px',
                border: '6px solid #B96829',
                top: '15%',
                left: '35%',
                cursor: 'default'
            },
            overlayCSS: {
                backgroundColor: '#fff',
                opacity: 0.6
            }
        });
        $(".blockOverlay, .closeOverlay").attr("title", "Click to unblock").click($.unblockUI).css("cursor", "pointer");

        $(document).keydown(function(e) {
            if (e.which == 27) {  // escape, close box
                $.unblockUI();
            }
        });

        return false;
    }).attr('title', 'Click to Enlarge').css("cursor", "pointer");
});

function showItemSlider() {
    clearTimeout(itemTimer);
    $("#item-dialog").slideDown(300).bgiframe();
    itemTimer = setTimeout(function() { hideItemSlider(); }, 5000);
};
function hideItemSlider() {
    $("#item-dialog").slideUp(150);
};
function tabSwitch(tabid) {
    $('.tabModule .tabsRow').tabs('select', '#' + tabid);
};
function blockFilters() {
    $('.cbBrewSolutionFilter').addClass('jquery-checkbox-disabled');
    $('.tabdivBottom').block({
        message: '<div><img src="/images/ajaxloading1.gif" /></div>',
        css: { border: 0, background: 'none' },
        overlayCSS: { opacity: 0.12 }
    });
    $('.selectWrapper').block({
        message: null,
        css: { border: 0, background: 'none' },
        overlayCSS: { opacity: 0.12 }
    });
    //Unblock after 30 seconds in case the page doesn't redirect properly.
    setTimeout(unblockFilters, 30000);
};
function unblockFilters() {
    $('.cbBrewSolutionFilter').removeClass('jquery-checkbox-disabled');
    $('.tabdivBottom, .selectWrapper').unblock()
};



/* START QUICK BUY */
function processAddToCart(s) {
    var a = s.split('|');

    //Validate response
    var a = s.split('|');
    if (a[0] != '1') {
        alert('An error occurred while trying to add this item to your cart. Please ensure that all the required fields have been properly completed.');
        return;
    }

    $('#divItemAdded').html(a[1]);
    $('#spanCartTotal').html(a[2] + (parseInt(a[2]) == 1 ? ' Item ' : ' Items ') + a[3]);

    showItemSlider();
    window.location.hash = 'itemAdded';

    $("#detailView").remove();
}
/* END QUICK BUY */
