var itemTimer;

jQuery(function($) {
    // Your code using failsafe $ alias here...
	$(document).pngFix(); 

	$('.itemWrapper itemImage').live('click',function(){
		window.location = $(this).parents(".itemWrapper").find("a.itemLink").attr("href");
		return false;
	}).css('cursor', 'pointer');

	$('.roundedText').corner("3px");
	$('.innerRail').corner("7px").parent().css({padding: '1px', background:'#8c8b8b'}).corner("10px");	
	$('.roundedInner').corner("8px").parent().css({padding: '1px'}).corner("10px");	

    $(".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();

    $(".productImage").live("click", function() {
        $(".enlargeView").dialog("open");
        return false;
    }).css("cursor", "pointer");
    // END dialog windows 
    
    $('.tabModule .tabsRow').tabs();
    $('.cartSupport .supportTabs').tabs();


	$('.homeProduct .listing li').matchHeights();
	$(".contentCenter").each(function(){
		var $rightWidgets = $(this).next().find(".innerRail");
		$rightWidgets.matchHeights();
	});
	$('.leftRail .innerRail, .mainRail .innerRail:not(.cartLayout)').matchHeights();
	//$('.leftRail .innerRail, .contentCenter, .contentRight, .rightRail').matchHeights();
	

	
    $(".itemRow").equalHeights(true);
    $(".modCarousel .items").equalHeights(true);
    $(".columnRow").equalHeights(true);
    $(".productDetails ul.textLink").equalWidths(true);
    //$(".leftRail .innerRail, ").matchHeight();

    $(".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.toLowerCase().replace('/large/', '').replace('/regular/', '') == children.eq(j).attr("href").toLowerCase().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.toLowerCase().replace('/large/', '/regular/') });

        //find the large image
        $(".imageViewer .mainImage img").attr({ src: newimg.toLowerCase().replace('/regular/', '/large/') });

        return false;
    });

    //Banner slide show
    $("#homeSSW").cycle({
        fx: 'fade',
        speed: 300,
        timeout: 10000,
        pager: '.nav'
    });
    $(".sswControls").css({ 'background-color': '#fff', 'opacity': '0.9' });

    $(".truncate").truncate({
        max_length: 400,
        more: "read more",
        less: "read 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');
            }
        }
    });

    $(".pageTools .recent").live("click", function() {
        $(".recentDialog").dialog("open");
        return false;
    });

//    $(".productImage").live("click", function() {
//        $(".enlargeView").dialog("open");
//        return false;
//    }).css("cursor", "pointer");
    // END dialog windows 


    // carousels 
    $(".modCarousel4 .scrollable").scrollable({
        size: 4,
        items: ".items",
        clickable: false
    });


    $(".modCarousel5 .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
    
  
  	$('#promoOffer-trigger').click(function() { 
  		$.blockUI({ 
  			message: $('#promoOfferPopup'),
  			css: {
  				textAlign: 'left',
  				border: '0',
  				width: '600px',
  				top: '10%',
  				left: '33%',
  				cursor: 'default'
  			},
  			overlayCSS:  { 
  				backgroundColor: '#000', 
  				opacity: 0.50 
  			}
  		});
  		$('.blockOverlay, #promoOfferPopup .closeBtn').click($.unblockUI); 
  		return false;
	});
  
    
	$(".toolTip").bgIframe();

	$(".toolTipTrigger").tooltip({
		position: "top center",
		lazy: false,
		delay: 200,
		events: { 
			def: 'click, mouseout'
		} 
	}).dynamic( { 
        // customized configuration on bottom edge 
        bottom: { 
            direction: 'down' 
        },
        right: { 
            direction: 'right'
        } 
    });
    
    $(".tooltip-trigger").tooltip({
    	position: "bottom left",
        lazy: false,
        relative: true,
        offset: [-27, -88]
    });


    
	$(".ratingBreakdown-trigger").tooltip({
		position: "bottom center",
		lazy: false,
		delay: 200,
		offset: [15, 40],
		events: { 
			def: 'mouseover, mouseout'
		} 
	}).dynamic( { 
        // customized configuration on bottom edge 
        top: { 
            direction: 'up',  
            offset: [-5, 40]
        },
        right: { 
            direction: 'right'
        } 
    });
    
	$(".addTag-trigger").tooltip({
		position: "top center",
		delay: 700,
		lazy: false,
		events: { 
			def: 'click, mouseout'
		} 
	}).dynamic( { 
        // customized configuration on bottom edge 
        bottom: { 
            direction: 'down' 
        },
        right: { 
            direction: 'right'
        } 
    });   
    
	$('.hover-star').rating({ 
		focus: function(value, link){ 
			var tip = $(this).parent().find('.hover-text'); 
			tip[0].data = tip[0].data || tip.html(); 
			tip.html(link.title || 'value: '+value); 
		}, 
			blur: function(value, link){ 
			var tip = $(this).parent().find('.hover-text'); 
			tip.html(tip[0].data || ''); 
		} 
	});

	// BEGIN ADVANCED MARKETING RULES
	$(".promoBreakdown-trigger").tooltip({
	    position: "top center",
	    relative: true,
	    lazy: false,
	    delay: 200,
	    offset: [-5, 0],
	    events: {
	        def: 'mouseover, mouseout'
	    }
	});
    // END ADVANCED MARKETING RULES
	
});


function showRecentCart() {
    var rcart = $(".recent-cart");
    var rcartTimer = 0;

    rcartTimer = setTimeout(function() { rcart.slideUp("fast"); $(window).unbind('scroll');}, 6000);

    rcart
		.css("top", "20px")
		.hide()
		.slideDown("fast")
		.animate({ "right": "30px" }, 30)
		.animate({ "right": "20px" }, 50)
		.animate({ "right": "26px" }, 20)
		.find(".close-cart").click(function() {
		    rcart.slideUp("fast");
		    $(window).unbind('scroll');
		    return false;
		})
		.mouseenter(function() { clearTimeout(rcartTimer); })
		.mouseleave(function() {
		    rcartTimer = setTimeout(function() { rcart.slideUp("fast"); $(window).unbind('scroll');}, 50000);
		});

    name = ".recent-cart";
    var menuYloc = null;
    menuYloc = parseInt($(name).css("top").substring(0, $(name).css("top").indexOf("px")))
    rcart.css("top", $(this).scrollTop() + 20 + "px");
    $(window).scroll(function() {
        var offset = menuYloc + $(document).scrollTop() + "px";
        $(name).animate({ top: offset }, { duration: 500, queue: false });
    });
};


// BEGIN ADVANCED MARKETING RULES
function amr(options) {
    $.getJSON("/ajax.aspx?F=GetPromotionDetails&NoItems=" + (options.noItems ? options.noItems : "false") + "&PromotionId=" + options.PromotionId + "&RecipientId=" + options.RecipientId + "&Page=" + (options.Page ? options.Page : 1), function(o) {
        if (!o.Success) return;

        var html = '';
        if (!options.Page) html += '<div id="promoOfferPopup" style="display:block;">'
        html += '<div class="closeBtn">Close</div><div class="hdng">';
        html += o.Heading;
        html += '</div>';
        if (o.Message && o.Message != "") html += '<p>' + o.Message + '</p>';

        var paging = '';

        if (o.NOfPages > 1) {
            paging += '	<div class="pagination">';
            paging += '		<div class="paging">';
            paging += '			<a class="arrowLeft" href="javascript:void(0);" ' + (options.Page && options.Page > 1 ? 'onclick="amr({PromotionId:' + options.PromotionId + ',RecipientId:' + options.RecipientId + ',Page:' + (options.Page - 1) + '});"' : '') + '>Previous</a>';
            for (var i = 1; i <= o.NOfPages; i++) {
                if (o.Page == i)
                    paging += '<span class="active">' + i + '</span>';
                else
                    paging += '<a href="javascript:void(0);" onclick="amr({PromotionId:' + options.PromotionId + ',RecipientId:' + options.RecipientId + ',Page:' + i + '});">' + i + '</a>';
            }
            paging += '			<a class="arrowRight" href="javascript:void(0);" ' + (o.NOfPages > (options.Page ? options.Page : 1) ? 'onclick="amr({PromotionId:' + options.PromotionId + ',RecipientId:' + options.RecipientId + ',Page:' + ((options.Page ? options.Page : 1) + 1) + '});"' : '') + '>Next</a>';
            paging += '		</div>';

            paging += '		<div class="clear" style="float:none; padding:0;">&nbsp;</div>';
            paging += '	</div>';
            paging += '	<div class="clear">&nbsp;</div>';
        }

        html += paging;

        html += '	<div class="collectionItems">';

        for (var i = 0; i < o.Items.length; i++) {
            var item = o.Items[i];

            var s = '';

            // item divider
            if (i > 0) s += '		<div class="hr"><hr /></div>';

            // begin item
            s += '		<div class="itemWrapper">';
            s += '			<a class="itemLink" href="' + item.Url + '" id="productImage_amr_' + item.ItemId + '"><img class="itemImage mainImage" src="/assets/item/cart/' + item.Image + '" alt="item name" /></a>';

            s += '			<div class="itemDetails">';
            s += '				<strong class="itemTitle"><a href="' + item.Url + '" class="itemAnchor" id="hdngItemName_amr_' + item.ItemId + '">' + item.ItemName + '</a></strong>';
            s += '				<div class="detailsRow" id="Selections_amr_' + item.ItemId + '"></div>';
            s += '				<div class="detailsRow">';
            s += '					<div class="itemPrice">';
            s += '						Price: <span id="spanPrice_amr_' + item.ItemId + '">' + item.Price + '</span>';
            s += '					</div>';
            s += '				</div>';
            s += '			</div>';

            s += '			<div class="itemQuantity">';
            s += '				<div class="padT10">';
            s += '					<input type="hidden" id="hdnRecipient_amr_' + item.ItemId + '" value="' + o.Recipient + '" /><span class="btnWrapper btnAddToCart"><input class="btn" type="button" value="Add To Cart" id="btnAdd2Cart_amr_' + item.ItemId + '" /></span>';
            s += '				</div>';
            s += '				<div id="emailContainer_amr_' + item.ItemId + '"></div>';
            s += '			</div>';

            s += '			<div class="clear">&nbsp;</div>';
            s += '		</div>';
            // end item

            html += s;
        }

        html += '	</div>';

        html += paging;

        if (!options.Page) html += '</div>';

        if (!options.Page) {
            $.blockUI({
                message: html,
                css: {
                    textAlign: 'left',
                    border: '0',
                    width: '600px',
                    top: '10%',
                    left: '33%',
                    cursor: 'default'
                },
                overlayCSS: {
                    backgroundColor: '#fff',
                    opacity: 0.75
                }
            });
            $('#promoOfferPopup .closeBtn').live("click", $.unblockUI);
        } else {
            $("#promoOfferPopup").html(html);
        }

        for (var i = 0; i < o.Items.length; i++) {
            var item = o.Items[i];
            window["sel_amr_" + item.ItemId] = new Selections({ DisableSlider: true, Variable: "sel_amr_" + item.ItemId, Suffix: '_amr_' + item.ItemId, Add2CartPreCallBack: RefreshCart, ImageFolder: 'cart', IsSmall: true, Container: "Selections_amr_" + item.ItemId, EmailContainerId: 'emailContainer_amr_' + item.ItemId, EnableInventory: o.EnableInventory, AddToCartBtn: 'btnAdd2Cart_amr_' + item.ItemId, RecipientDropDown: 'hdnRecipient_amr_' + item.ItemId, QuantityTextBox: 'txtQty_amr_' + item.ItemId, SelectedItem: (item.ItemTypeId = 1 ? item.ItemId : null), Properties: item.Properties, Items: item.Items });
            window["sel_amr_" + item.ItemId].Create();
        }
    });
}

function RefreshCart(o) {
	$.unblockUI(); 
	window.location = '/store/cart.aspx';
}
// END ADVANCED MARKETING RULES

