





var redirectUrl = "";
function submitForm(actType) {
    document.itemsForm.act.value = actType;
    // if checkout, perform google method to change domains.
	if (actType == 'checkout' || actType == 'logincheckout'){
//		__utmLinkPost(document.itemsForm)
        pageTracker._link(document.itemsForm);
        trackerALL._link(document.itemsForm);
	}
	document.itemsForm.submit();
}

jQuery.preloadImages = function(){
  for(var i = 0; i
<arguments.length
	; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}


$(function(){


    /* Live Chat Link */

    $('a.live-chat').click(function() {
        window.open(this.href,"_blank","top=25,left=25,scrollbars=1,resizable=1,location=0,menubar=0,toolbar=0,width=620,height=450");
        return false;
    });

    /* Countdown Timer [ begin ] */

	function countDown(countdn,cd){
        if(countdn < 0){
           countdn = 0;
        }

		var secs = countdn % 60;
		var mins = 0;
		var hours = 0;
		var days = 1;
		var countdn1 = 0;



		if (secs < 10){
		  secs = '0'+secs;
		}
		  countdn1 = (countdn - secs) / 60;
		  mins = countdn1 % 60;
		if (mins < 10){
			mins = '0'+mins;
		}
			countdn1 = (countdn1 - mins) / 60;
             hours = countdn1;
            days = (countdn1 - hours) / 24;
            
           

            

        if (hours >= 2 && mins > 0){
			$(cd).html("Order in the next " + hours + " hours " + mins + " minutes");
		}else if (hours < 2 && hours >= 1 && mins >= 0){
			$(cd).html("Order in the next " + hours + " hour " + mins + " minutes");
		}else if (hours < 1){
			$(cd).html("Order in the next " + mins + " minutes");
		}

	 setTimeout(function() {return countDown((countdn-1),cd);}, 999);
     }
    countDown(parseInt($("#timer").html()), "#timer");
	/* Countdown Timer [ end ] */

	/* png transparency [ begin ] */
	fixPNG($(".png_ie"));
	resetOverlaySize();
	function fixPNG(o) {
		o.each(function(){
			s = $(this).attr("src");
			s = s.substr(0,s.lastIndexOf("/")) + "/" + $(this).attr("id") + ".png";
			if (navigator.appName.indexOf("Microsoft") != -1) {
				$(this).css("filter","progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + s + "', sizingMethod='scale')");
			} else {
				$(this).attr("src",s);
			}
		});
	}
	function resetOverlaySize(){
	  $(".popup-middle",".overlay-pop").height($(".inner",".overlay-pop").height());
	   $(".otherstores-middle","#stores-overlay").height($("#stores-overlay-inner","#stores-overlay").height());
	 }

  /* png transparency [ end ] */


	$("#emailSubscribeButton").click(function(event) {
		$("#panel_email_subscribe").css("display","none");
		$("#panel_email_subscribe_loader").css("display","inline");
		$.get(
			"/email_subscribe.cmd",
			{
				siteCode: $("input[@name=siteCode]").val(),
				emailPreference: $("input[@name=emailPreference]").val(),
				emailFormat: $("input[@name=emailFormat]").val(),
				emailAddress: $("input[@name=emailAddress]").val()
			},
			function(d) {
				var txtError = $("/hooks/errors/error[@id=invalid_subscribe_email_address]",d);
				var txtMessage = $("/hooks/messages/message[@id=email_subscribe_successful]",d);
				if (txtError.length > 0) {
					$("#panel_email_subscribe_text").html($(txtError).text());
					$("#panel_email_subscribe_text").parent().attr("class","error");
				}
				if (txtMessage.length > 0) {
					$("#panel_email_subscribe_text").html($(txtMessage).text());
					$("#panel_email_subscribe_text").parent().attr("class","success");
				}
				$("#panel_email_subscribe").css("display","inline");
				$("#panel_email_subscribe_loader").css("display","none");
			}
		);
		return false;
		event.preventDefault();
	});
    swapValues = [];
    $(".swap_value").each(function(i){
        swapValues[i] = $(this).val();
        $(this).focus(function(){
            if ($(this).val() == swapValues[i]) {
                $(this).val("");
            }
        }).blur(function(){
            if ($.trim($(this).val()) == "") {
                $(this).val(swapValues[i]);
            }
        });
    });

  /* Other Stores Overlay */
  var otherStores = {
       timer: null,
       bindLayover: function() {
            $('#stores-overlay').hover(function() {
                otherStores.stopTimer();
				$(".stores-close").click(function(){
					otherStores.isClicked = true;
					otherStores.setTimer();
				});
			},function(){
				if (!otherStores.isClicked){
					otherStores.setTimer();
				}
			});
        },
        toggleOn: function(){
            if (otherStores.timer == null) {
                $('#stores-overlay').fadeIn("normal");
                resetOverlaySize();
            }else{
			return false;
           }
        },
        setTimer : function() {
           otherStores.stopTimer();
		  	if (!otherStores.isClicked){
			   otherStores.timer = setTimeout(function(){
					$('#stores-overlay').fadeOut("normal",function(){
						otherStores.timer = null;
					});
				},0);
			}else {
				otherStores.timer = setTimeout(function(){
					$('#stores-overlay').fadeOut("normal",function(){
					otherStores.timer = null;
					});
				},0);
			 }
	   },
        stopTimer: function(){
           if(otherStores.timer != null) {
              clearTimeout(otherStores.timer);
           }
        },
		isClicked: false
	};

	$("#stores-text a").hover(function(){
	   otherStores.isClicked = false
	   otherStores.stopTimer();
       otherStores.toggleOn();
    },function(){
       otherStores.setTimer();
        return false;
    });

	$("#stores-text a").click(function(){
        return false;
    });
	otherStores.bindLayover();

	/* Other Stores Overlay [ end ] */

	/* Shipping Countdown and Persistent Cart */
	cartTimer = {
		/*Set the default widths to 0 initially*/
		countdownWidth: 0,
		cartWidth: 0,
		isCartOpen: false,
		/*
		  Open up the hover cart and set to display block, and give padding for text,
		  also set the width to auto for the container because if it was closed then there was a small width applied
		*/

		cartOpen: function(){
			$("#cart-total").animate({width: cartTimer.cartWidth},"fast",function(){
				$("#cart-total").width("");
			});
			$("#cart-total").css({
				display: "block",
				padding: "0 20px"
			});
			$("#global-cart").width("");
			cartTimer.isCartOpen = true;
		},
		/*
			Animate the cart total div to 0 setting, open the countdown, remove some of the styles, change the button image, set the container to
			the width of the button image and turn the hover cart to display none
		*/
		cartClose: function(){
			$("#cart-total").animate({width: 0},"fast", function(){
				cartTimer.countdownOpen();
				$("#cart-total").css("padding","0");
				$("#cart_corner").css("display","none");
				$("#cart-button img").attr("id","cart_button");
				fixPNG($(".png_ie"));
				$("#global-cart").width($("#cart-button").width());
				$('#hovercart-items').css("display","none");
			});
			cartTimer.isCartOpen = false;
		},
		/*
			Open the countdown by setting the width of the countdown time div to the original value when the page first loaded and set the
			container's width to auto because a previous width was set
		*/
		countdownOpen: function(){
			$("#countdown-time").animate({width: cartTimer.countdownWidth},"fast");
			$("#countdown-time").css("display","block");
			$("#countdown").width("");
		},
		/*
			Animate the countdown time div to 0, open the persistent cart and display the end rounded corner of the persistent cart,
			change the button to the one with a flat side and set the width of the container for the countdown to the size of the
			clock image and end corner combined
		*/
		countdownClose: function(){
			$("#countdown-time").animate({width: 0},"fast", function(){
				cartTimer.cartOpen();
				$("#cart_corner").css("display","inline");
				$("#cart-button img").attr("id","cart_button_extended");
				fixPNG($(".png_ie"));
				$("#countdown").width($("#countdown_end").width() + $("#countdown-clock").width());
			});
		}
	}
	/* Get the initial width of the countdown time div */
	cartTimer.countdownWidth = $("#countdown-time").width();

    /* Get the persistent cart's total text div */
	cartTimer.cartWidth = $("#cart-total").width();
 	/*
		Set the  display of the cart total to none after we have got the width, since we had to get the width to apply it later
		we set the visibility to hidden in the style sheet, so we now give it visibility visible to set it back
	*/
	$("#cart-total").css({
		display: "none",
		visibility: "visible"
	});
	/* The click function that runs the the cartClose method,closing the cart after the user clicks the clock */
	$("#countdown-clock").click(function(){
		cartTimer.cartClose();
		$(this).blur();
		return false;
	});
	/* The click function that runs the countdownClose method, closing the countdown after the user clicks the  cart button*/
	$("#cart-button").click(function(){
		cartTimer.countdownClose();
		$(this).blur();
		return false;
	});
 	/* if the HTML in the element with the class of span inside the cart total div is greater then 0 open the cart and close the countdown */
	if ($(".quantity", "li#cart-total").html() > 0){
        cartTimer.countdownClose();
        cartTimer.cartOpen();
	}
	/*
		We set the initial visibility of the countdown container to hidden so that we can grab the initial width and since the persistent cart
		can be the first one open if there is something in the cart we had it to be set to hidden so there wouldn't be a flash of the full countdown,
		so now we set the div back to visible
	*/
	$("#countdown").css("visibility","visible");


    $("#countdown").css("visibility","visible");

    /* Shipping Countdown and Persistent Cart [end] */



/* Hover Cart Overlay */
  var hoverCart = {
	  timer: null, // set the initial timer to null
	  isHovered: false,
		 /*
			This function creates our slide down effect, if the timer is set to null which it is by default
			thenrun our animation
		*/
	  toggleOn: function(){
			if (hoverCart.timer == null && $(".quantity", "div#cart-total").html() == 0){
				return false;
           }else if (hoverCart.timer == null) {
                $('#hovercart-items').slideDown("normal");
           }
        },
		/*
		Stop the timer if it already exist and check to see if the isHoveredmethod is set to false
		if it is user our timer method to create a set timeout and slide our hover cart back up and reset the timer to
		null
		*/
		setTimer : function() {
           hoverCart.stopTimer();
              if (!hoverCart.isHovered){
			   hoverCart.timer = setTimeout(function(){
					$('#hovercart-items').slideUp("normal",function(){
						hoverCart.timer = null;
                        addToCart.hideSelect(false);
                    });
				},2000);
            }
	   },
        stopTimer: function(){// if the timer is running cear our setimeout function
           if(hoverCart.timer != null) {
              clearTimeout(hoverCart.timer);
           }
        },
		/*
			This function is used for when the user moves their mouse away from the main div and over the hover cart
			Since a timeout is creating when moving the cursor away from the main div we use the stopTimer method
			to clear the timeout and when we hover off the hover cart we set the timer again.
		*/
		bindLayover: function() {
            $('#hovercart-items').hover(function() {
                hoverCart.stopTimer();
			},function(){
				if (!hoverCart.isHovered){
					hoverCart.setTimer();
				}
			});
        }
	};

	$("#cart-total").hover(function() {
		hoverCart.stopTimer();
        if(addToCart.isPopped){
           addToCart.removeCartPopped();
           addToCart.isPopped = false
        }
        if (!addToCart.isPopped){
             addToCart.hideSelect(true);
        }
        /* If The hover cart has already been pulled in with AJAX
		toggle on the hover overlay with existing content*/
		if ($("#hovercart-items").html() != null && !addToCart.isProductUpdated){
			hoverCart.isHovered = false
			hoverCart.toggleOn();
		}
			/*
				If Cart Total div hasn't been hovered yet, make an AJAX call and get the cart info from
				an include and set the toogle on and hover off  timer code
			*/
		else {
			if ($(".quantity", "div#cart-total").html() == 0){
				return false;
			}else{
				$("#hovercart-items").remove();
				$.get("/includes/layer_hover_cart.jsp",
				{ cartParam: new Date().getTime() },
				function(data) {
					var html = "<div id='hovercart-items' style='display: none;'>";
					html+= data;
					html+= "</div>";
					$("#header").append(html)
					hoverCart.toggleOn();
					addToCart.isProductUpdated = false;
					$("#hovercart-items").width($("#global-cart").width() + 2)
					/*
						Stop the timer if the user hovers from the main text div to the hover cart and then set the timer
						again if the user hovers off the hover cart.
					*/
					hoverCart.bindLayover();
				}
				);

			}
		}
	},function(){
		//If the user has hovered off just the main text block and not the cart overlay set the timer to turn off the overlay
		hoverCart.setTimer();
    });

	/* Hover Cart Overlay [ end ] */

    /* Add To Cart Click Function */
	$(".product-addtocart").click(function() {
            var pEmSku = "";
            var pEmColor = "";
            var pEmFont = "";
            var pEmMsg1 = "";
            var pEmMsg2 = "";
            var pEmVarId = "";
            var pGiftWrapSku = "";
            var pGiftWrapVarId = "";
            var pItemGUID = "";
            if ($("input[@name=productVariantId]").val() == null){
                var pVarId = $("select[@name=productVariantId] option:selected").val();
			}else{
				var pVarId = $("input[@name=productVariantId]").val();
			}
			if ($("input[@name=embroiderySku]").attr("checked")){
				 pEmSku = $("input[@name=embroiderySku]").val();
				 pEmColor = $("select[@name=embroideryColor] option:selected").val();
				 pEmFont = $("select[@name=embroideryFont] option:selected").val();
				 pEmMsg1 = $("input[@name=embroideryMsg1]").val();
				 pEmMsg2 = $("input[@name=embroideryMsg2]").val();
				 pEmVarId = $("input[@name=embroideryProductVariantId]").val();
			}
           if ($("input[@name=giftWrapSku]").attr("checked")){
                 pGiftWrapSku = $("input[@name=giftWrapSku]").val();
                 pGiftWrapVarId = $("input[@name=giftWrapVariantId]").val();
            }
            pReqProd = {};
			pReqProdCount = 0;
			if ($("input[@name=requiredProductCount]").val() > 0){
				var pReqProdCount = $("input[@name=requiredProductCount]").val();
				for (i = 0; i < pReqProdCount; i++) {
					pReqProd["requiredProductVariant" + i] = $("#required-product-"+ i +" option:selected").val();
				}
			}
			var pId = $("input[@name=productId]").val();
			var pCatId = $("input[@name=parentCategoryId]").val();
			var catId = $("input[@name=categoryId]").val();
			var pQuantity = $("input[@name=quantity]").val();
            pItemGUID = $("input[@name=itemGUID]").val();
            addToCart.addTo(pVarId,pId,pCatId,catId,pQuantity,pEmColor,pEmFont,pEmMsg1,pEmMsg2,pEmVarId,pEmSku,pGiftWrapSku,pGiftWrapVarId,pReqProdCount,pReqProd,pItemGUID);
            $(this).blur();
        return false;
    });
    
    
    /* Add To Cart Click Function for CLEK */
	$(".clek-product-addtocart").click(function() {
            var errorMsg = "";
            var pEmSku = "";
            var pEmColor = "";
            var pEmFont = "";
            var pEmMsg1 = "";
            var pEmMsg2 = "";
            var pEmVarId = "";
            var pGiftWrapSku = "";
            var pGiftWrapVarId = "";
            var pVarId;
            var pItemGUID = "";
            if ($("input[@name=productVariantId]").val() == null){
                pVarId = $("select[@name=productVariantId] option:selected").val();
			}else{
				pVarId = $("input[@name=productVariantId]").val();
			}
			if ($("input[@name=embroiderySku]").attr("checked")){
				 pEmSku = $("input[@name=embroiderySku]").val();
				 pEmColor = $("select[@name=embroideryColor] option:selected").val();
				 pEmFont = $("select[@name=embroideryFont] option:selected").val();
				 pEmMsg1 = $("input[@name=embroideryMsg1]").val();
				 pEmMsg2 = $("input[@name=embroideryMsg2]").val();
				 pEmVarId = $("input[@name=embroideryProductVariantId]").val();
			}
           if ($("input[@name=giftWrapSku]").attr("checked")){
                 pGiftWrapSku = $("input[@name=giftWrapSku]").val();
                 pGiftWrapVarId = $("input[@name=giftWrapVariantId]").val();
            }
            pReqProd = {};
			pReqProdCount = 0;
			if ($("input[@name=requiredProductCount]").val() > 0){
				var pReqProdCount = $("input[@name=requiredProductCount]").val();
				for (i = 0; i < pReqProdCount; i++) {
					pReqProd["requiredProductVariant" + i] = $("#required-product-"+ i +" option:selected").val();
				}
			}
			var pId = $("input[@name=productId]").val();
			var pCatId = $("input[@name=parentCategoryId]").val();
			var catId = $("input[@name=categoryId]").val();
			var pQuantity = $("input[@name=quantity]").val();
            pItemGUID = $("input[@name=itemGUID]").val();
            
			if("" == pVarId){
			 	errorMsg += "<ul><li class=\"error-container\">Please choose a product</li></ul>";	
			}
			
		    if(isNaN(pQuantity)){
		     errorMsg += "<ul><li class=\"error-container\">Please enter a valid quantity</li></ul>";
		    }else if(parseInt(pQuantity) <= 0){
		     errorMsg += "<ul><li class=\"error-container\">Quantity must greater than zero</li></ul>";
		    }
		    
		    if("" == errorMsg){
		      addToCartNoOverlay.addTo(pVarId,pId,pCatId,catId,pQuantity,pEmColor,pEmFont,pEmMsg1,pEmMsg2,pEmVarId,pEmSku,pGiftWrapSku,pGiftWrapVarId,pReqProdCount,pReqProd,pItemGUID);
              $(this).blur();
		    }else{
             //handle error
         //    var errorMsgDisplay = "";
         //    errorMsgDisplay += "<ul><li>";
         //    errorMsgDisplay += errorMsg;
         //    errorMsgDisplay += "</li></ul>";
		     document.getElementById("general-error").innerHTML = errorMsg;
		    }		
            
        return false;
    });
    
    $("#pp-printer-friendly").click(function() {
        if (window.print) {
        window.print();
        } else {
            alert("Please click File >> Print in your browser file menu.");
        }
        return false;
    });
    $("#pp-email-to-friend").click(function() {
		window.open("/catalog/product_email.jsp?pageURL=" + $("#pageURL").val(),"","width=500,height=500");
		return false;
	});

    /* refinements */

    toggleRefinements( "close" );

    $(".close-refinement-options").click(function() {
        toggleRefinements("close");
        return false;
    });

    $(".open-refinement-options").click(function() {
        toggleRefinements("open");
        return false;
    });


    /* Comare Links Search */
    $('#search-results .compare').click(function() {
        var $this = $(this);
        var p = $this;
       document.refineProductsForm.showCompareChart.value = false;
        if($("img", p).attr( "src" ) == "/assets/images/btn_compare_selected.gif" ){
            $this.prev("input").attr({checked: ''});
            $("img", p).attr("src","/assets/images/btn_compare_not_selected.gif");
        }else{
            $this.prev("input").attr({checked: 'checked'});
            $("img", p).attr("src","/assets/images/btn_compare_selected.gif");
        }
        $(this).blur();
        submitCompare()
        return false;
    });
    $("#search-results .compare-check").each(function(){
        var $this = $(this);
        if ($this.is('input:checked')){
            $this.next().children().attr("src","/assets/images/btn_compare_selected.gif");
        }
    });
    /* Init Report Issues popup */
    reportIssue.init();

	/* Colorado Tax Info popup */
	coloradoTax.init();
	
    /* Select Box Reset */
    $(".reset").focus(function(){
        resetValue(this);
    });
    function resetValue(input) {
        if (input.value = "^[a-zA-Z0-9]+$]")
            input.value = "";
    }
// popup overlay. generic add popupoverlay functionality to any link by adding class .popup tad
		//when a tag with class equal to popup clicked function
		$('a.popup').click(function (e) {
			//Cancel the link behavior
			e.preventDefault();
			popupOverlay(this.href);
		});
// popup overlay End

});
//pop up overlay function.  the heart of popupOverlays  tad
function popupOverlay(popURL, popWidth, popHeight) {
			/*build popup and overlay*/
			if ($('div#dialog.popupWindow').length <= 0) {
				var strJq = "<div id='dialog' class='popupWindow'>";
				strJq += " <div id='overlay-utility'>";
				strJq += "   <a class='close' href='#'>Close</a>";
				strJq += " </div>";
				strJq += " <iframe id='popup' src='/assets/images/backgrounds/ajax-loader.gif' width=100% height=100%>loading...</iframe>";
				strJq += "</div>";
				strJq += "<div id='mask'></div>";
				$("body").prepend(strJq);

			}
			//Get the A tag URL and brake it up into its parts
			var fulu = popURL;
			var queryString = (fulu.indexOf("?") > -1) ? fulu.substr(fulu.indexOf("?") + 1) : null;
			var urlz = (fulu.lastIndexOf("#") > -1) ? fulu.slice(0, fulu.lastIndexOf("#")) : fulu;
			var id = '#dialog';
			var newWidth = String(popWidth);
			var newHeight = String(popHeight);
			if (popWidth == null || popWidth == 'undefinded'){
				newWidth = "80%";
			}
			if (popWidth == null || popWidth == 'undefinded'){
				newHeight = "80%";
			}

			//set iframe size, start by getting parameters if there
			if (queryString != null && typeof queryString != 'undefined') {
				var queryVarsArray = queryString.split("&");
				for (var i = 0; i < queryVarsArray.length; i++) {
					if (unescape(queryVarsArray[i].split("=")[0]) == 'width') {
						newWidth = queryVarsArray[i].split("=")[1];
					}
					if (escape(unescape(queryVarsArray[i].split("=")[0])) == 'height') {
						newHeight = queryVarsArray[i].split("=")[1];
					}

				}
			}
			// convert height to pixels, add title bar spacing and size to fix window
			if (newHeight.indexOf('%') > -1) {
				newHeight = Math.floor(parseInt($(window).height()) * (parseInt(newHeight) / 100));
				newHeight = Math.floor(parseInt(newHeight) + 34);
			}
			if (parseInt(newHeight)+100 > Math.floor(parseInt($(window).height()))) {
				newHeight = Math.floor(parseInt($(window).height()) - 100);
			}
			// let's run through all possible values: 90%, nothing or a value in pixel
			if (newWidth.indexOf('%') > -1) {
				newWidth = Math.floor(parseInt($(window).width() / 100) * parseInt(newWidth));
			}
			if (parseInt(newWidth)+30 > Math.floor(parseInt($(window).width()))) {
				newWidth = Math.floor(parseInt($(window).width()) - 30);
			}

			newHeight = String(newHeight) + "px";
			newWidth = String(newWidth) + "px";

			// put URL in iframe src
			$('iframe#popup').attr('src', urlz);
			//Get the screen height and width
			//var maskHeight = $(window).height();
			//var maskWidth = $(window).width();
			var maskHeight = '100%';
			var maskWidth = '100%';
			//Set heigth and width to mask to fill up the whole screen
			$('#mask').css({
				'width': maskWidth,
				'height': maskHeight,
				'display': 'block'
			});
			//transition effect

			
			//Get the window height and width
			var winH = $(window).height();
			var winW = $(window).width();

			//transition effect
			$('#mask').animate({opacity: 0.8}, function (){
				$(id).fadeIn('fast');
			});
			// sizing of popup
			$(id).css({
				'width': newWidth,
				'height': newHeight
			});
			//set postion and lower if higher than window
			var newTop = Math.floor(winH / 2 - $(id).height() / 2);
			if (newTop <= 0) {
				newTop = 1;
			}
			//Set the popup window to center
			$(id).css('top', newTop);
			$(id).css('left', winW / 2 - $(id).width() / 2);

			//if close button clicked
		$('.popupWindow .close').click(function (e) {
			//Cancel the link behavior
			e.preventDefault();
			$('#mask').fadeOut('fast');
			$('.popupWindow iframe#popup').attr('src', '/assets/images/backgrounds/ajax-loader.gif');
			$('.popupWindow').hide();

		});
		//if mask is clicked
		$('#mask').click(function () {
			$(this).fadeOut('fast');
			$('.popupWindow iframe#popup').attr('src', '/assets/images/backgrounds/ajax-loader.gif');
			$('.popupWindow').hide();

		});
			return false;

}
//pop up overlay function end 
// Report Issue Functionality 
var reportIssue = {
    init: function(){
        var report = $("a.report");
        if(report.length <= 0)return false;
        reportIssue.createDiv();
        $('#report-problem').jqm({
            ajax: '/assets/popups/report_problem.html',
            trigger: report,
            closeClass: 'close',
            onLoad: reportIssue.onLoad
        });
    },
    createDiv: function(){
         var strJq = "<div id='report-problem' class='jqmWindow'>";
            strJq += "</div>";
         $("body").append(strJq);
    },
    onLoad: function(hash){
        $('input[@name=location]').val(window.location.href);
        $('#report-issues',hash.w).validate({
            errorPlacement: function(error, element) {
                   element.nextAll("div:eq(0)").append(error);
               },
            errorElement: "strong"
        });
        reportIssue.submit();
    },
    submit: function(){
        $("#report-issues").submit(function() {
            if($(this).valid() == true){
                var str = $(this).serialize();
                addToCart.cartLoader();
                $.ajax({
                    type: "POST",
                    url: "/processForm.cmd",
                    data: str,
                    success: function(msg){
                    $('h2','#report-problem').html($("#content-primary h1:eq(0)",msg).html()).attr("class","success");
                     var para =  "<p>";
                       para += $("#content-primary p:eq(0)",msg).html();
                       para += "</p>";
                     $('#overlay-content').html(para);
                       $("#ajax-loading").remove();
                       $('#report-problem').jqmAddClose($('.close'));

                    }
                });
            return false;
          }
      });
    }
}
/* Report Issue End */

// Colorado Tax Popup  
var coloradoTax = {
    init: function(){
        var cotax = $("a.colorado-tax");
        if(cotax.length <= 0)return false;
        coloradoTax.createDiv();
        $('#colorado-tax').jqm({
            ajax: '/assets/popups/colorado-tax-info.html',
            trigger: cotax,
            closeClass: 'close',
            onLoad: coloradoTax.onLoad
        });
    },
    createDiv: function(){
         var strJq = "<div id='colorado-tax' class='jqmWindow'>";
            strJq += "</div>";
         $("body").append(strJq);
    }
}

function submitCompare(){
        document.refineProductsForm.submit()
    }
function submitSortForm(selectBox){
    $("#sort:eq(0)").val(selectBox.options[selectBox.selectedIndex].value);
    $("#sortForm").submit();
}

function refine( id, isSelected, newURL, refinementsOpen ) {
    newUrl = decodeURI( newURL );
    if ( isSelected ) {
        newUrl = [ decodeURI( newUrl ), "&remove=", id, "&refinementsOpen=", refinementsOpen ].join("");
    } else {
        newUrl = [ decodeURI( newUrl ), "&add=", id, "&refinementsOpen=", document.refinementForm.refinementsOpen.value ].join("");
    }
    document.location = newUrl;
}

function toggleRefinements( state ) {
    if ( state == "close" ) {
        $("#refinements-container").slideUp();
        $("#browse-toggle-on").attr( "class", "hide" );
        $("#browse-toggle-off").attr( "class", "show" );
    } else {
        $("#refinements-container").slideDown();
        $("#browse-toggle-on").attr( "class", "show" );
        $("#browse-toggle-off").attr( "class", "hide" );
    }
}



var addToCart = {
    o: function() {
        if (self.innerHeight) {
            this.pageYOffset = self.pageYOffset;
            this.pageXOffset = self.pageXOffset;
            this.innerHeight = self.innerHeight;
            this.innerWidth = self.innerWidth;
        } else if (document.documentElement && document.documentElement.clientHeight) {
            this.pageYOffset = document.documentElement.scrollTop;
            this.pageXOffset = document.documentElement.scrollLeft;
            this.innerHeight = document.documentElement.clientHeight;
            this.innerWidth = document.documentElement.clientWidth;
        } else if (document.body) {
            this.pageYOffset = document.body.scrollTop;
            this.pageXOffset = document.body.scrollLeft;
            this.innerHeight = document.body.clientHeight;
            this.innerWidth = document.body.clientWidth;
        }
        return this;
    },
    init: function(el) {
        $(el).css("left",Math.round(addToCart.o().innerWidth/2) + addToCart.o().pageXOffset - Math.round($(el).width()/2));
        $(el).css("top",Math.round(addToCart.o().innerHeight/2) + addToCart.o().pageYOffset - Math.round($(el).height()/2));
    },
    resetOverlaySize: function(){
        $("#add-middle").height($("#cart-overlay-content").height() +10);
    },
    hideSelect: function(isHidden){
        // This is only for IE6
        if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
           $(".options-container select").css("visibility","hidden");
           if (isHidden && addToCart.isPopped) {
            $(".options-container select").css("visibility","hidden");
          } else if (!isHidden && !addToCart.isPopped){
            $(".options-container select").css("visibility","visible");
          }
        }
    },
    cartLoader: function(){
        var strJq = "<div id='ajax-loading'>";
        strJq += "<img src='/assets/images/ajax-loader.gif' alt=''/>";
        strJq += "<h2>Loading</h2>";
        strJq += "</div>";
        addToCart.hideSelect(true);
        $("body").append(strJq);
        addToCart.init("#ajax-loading");
     },
    addTo: function(pVarId,pId,pCatId,catId,pQuantity,pEmColor,pEmFont,pEmMsg1,pEmMsg2,pEmVarId,pEmSku,pGiftWrapSku,pGiftWrapVarId,pReqProdCount,pReqProd,pItemGUID){
        var params = {
            productVariantId: pVarId,
            productId: pId,
            parentCategoryId: pCatId,
            categoryId: catId,
            quantity: pQuantity,
            embroideryProductVariantId: pEmVarId,
            embroiderySku: pEmSku,
            embroideryColor: pEmColor,
            embroideryFont: pEmFont,
            embroideryMsg1: pEmMsg1,
            embroideryMsg2: pEmMsg2,
            giftWrapSku: pGiftWrapSku,
            giftWrapVariantId: pGiftWrapVarId,
            requiredProductCount: pReqProdCount,
            itemGUID: pItemGUID
        }
        for (key in pReqProd){
           params[key] = pReqProd[key];
        }
        $.get(
                "/add_item_async.cmd",
                params,
                function(data) {
                    $(".error-container").css("display","none");
                    $(".error-message").html("").css("display","none");
                    $(".error-container-special").css("display","none");
                    var err = $("/hooks/errors/error",data);
                     if ($.trim($(err).text()) == ""){
                        addToCart.isError = false;
                     }else{
                        $(".error-container").css("display","block");
                        $(err).each(function(i) {
                            $(".error-message:eq(" + i + ")").html($(this).text()).css("display","list-item");
                            addToCart.isError = true;
                        });
                     $("#ajax-loading").remove();
                     addToCart.hideSelect(false);
                    }
                    if(!cartTimer.isCartOpen && !addToCart.isError){
                            cartTimer.countdownClose();
                    }
                    if (!addToCart.isError){
                        if($("input[@name=itemGUID]").val() != ""){
                            location.href = "/checkout/basket.jsp";
                        }
                        addToCart.isPopped = true;
                        addToCart.hideSelect(true);
                        $(".cart-overlay").remove();
                        addToCart.getCartLayer();
                    }
                }
            );
    },
    getCartLayer: function(){
         $.ajax({
            type: "GET",
            url: "/includes/layer_add_to_cart.jsp?date="+new Date(),
            success: function(data) {
                var strJq = "<div class='cart-overlay'>";
                strJq += "<img src='/assets/images/widgets/cart_popup/png.gif' id='add-top' class='png_ie' alt='' />";
                strJq += "<a href='#' class='cart-close'>close</a>";
                strJq += "<div id='cart-overlay-content'>";
                strJq += data;
                strJq += "</div>";
                strJq += "<img src='/assets/images/widgets/cart_popup/png.gif' id='add-bottom' class='png_ie' alt='' />";
                strJq += "<img src='/assets/images/widgets/cart_popup/png.gif' id='add-middle' class='png_ie' alt='' />";
                strJq += "</div>";
                $("#ajax-loading").remove();
                $("body").append(strJq);
                addToCart.init(".cart-overlay");
                fixPNG($(".png_ie"));
                addToCart.resetOverlaySize();
                $(".cart-close,.close").click(function(){
                    addToCart.isPopped = false;
                    addToCart.hideSelect(false);
                    $(".cart-overlay").remove();
                    return false;
                });
                addToCart.isProductUpdated = true;
                $("#quantity-value").html($("input[@name=orderQauntity]").val());
                $("#order-total").html($("input[@name=orderTotal]").val());
            }
        });
    },
    isProductUpdated: false,
    isError: false,
    isPopped: false,
    removeCartPopped: function(){
        $(".cart-overlay").remove();
    }
};

var addToCartNoOverlay = {
    	addTo: function(pVarId,pId,pCatId,catId,pQuantity,pEmColor,pEmFont,pEmMsg1,pEmMsg2,pEmVarId,pEmSku,pGiftWrapSku,pGiftWrapVarId,pReqProdCount,pReqProd,pItemGUID){  
        var params = {
            productVariantId: pVarId,
            productId: pId,
            parentCategoryId: pCatId,
            categoryId: catId,
            quantity: pQuantity,
            embroideryProductVariantId: pEmVarId,
            embroiderySku: pEmSku,
            embroideryColor: pEmColor,
            embroideryFont: pEmFont,
            embroideryMsg1: pEmMsg1,
            embroideryMsg2: pEmMsg2,
            giftWrapSku: pGiftWrapSku,
            giftWrapVariantId: pGiftWrapVarId,
            requiredProductCount: pReqProdCount,
            itemGUID: pItemGUID
        }
        for (key in pReqProd){
           params[key] = pReqProd[key];
        }
        $.get(
                "/add_item_async.cmd",
                params,
                function(data) {             
                    if(!cartTimer.isCartOpen && !addToCart.isError){
                            cartTimer.countdownClose();
                    }
                       $("#ajax-loading").remove();
                    location.href = "/checkout/basket.jsp";
                }
        );
	}
};

var NICHE = function() {
    var utils = {};
    utils.countdown = {
        setCountdown : function( params ) {
            var m = params.month;
            if ( params.month == "*" ) {
                params.month = 0;
            }
            var c = utils.countdown.setC( params );
            params.month = m;
            if ( params.month == "*" && c < 0 ) {
                c = utils.countdown.setC( params );
            }
            return c;
        },
        setC : function( params ) {
            var toDate = new Date();
            if ( params.day.substr( 0, 1 ) == "+" ) {
                toDate.setDate( toDate.getDate() + parseInt( params.day.substr( 1 ) ) );
            } else {
                toDate.setDate( params.day );
            }
            if ( params.month == "*" ) {
                toDate.setMonth( toDate.getMonth() + 1 );
            } else if ( params.month > 0 ) {
                if ( params.month <= toDate.getMonth() ) {
                    toDate.setFullYear( toDate.getFullYear() + 1 );
                }
                toDate.setMonth( params.month - 1 );
            }
            if ( params.day_of_week > 0 ) {
                toDate.setDate( toDate.getDate() + ( params.day_of_week - 1 - toDate.getDay() ) % 7 );
            }
            toDate.setHours( params.hour );
            toDate.setMinutes( 0 - ( params.timezone * 60 ) );
            toDate.setSeconds( 0 );
            var fromDate = new Date();
            fromDate.setMinutes( fromDate.getMinutes() + fromDate.getTimezoneOffset() );
            var diffDate = new Date( 0 );
            diffDate.setMilliseconds( toDate - fromDate );
            return Math.floor( diffDate.valueOf() / 1000 );
        }
    };
    return {
        countdown : {
            displayCountdown : function( params ) {
                if ( params.time == undefined ) {
                    params.time = utils.countdown.setCountdown( params );
                } else {
                    params.time -= 1;
                }
                if ( params.time < 0 ) {
                    document.getElementById( params.element ).innerHTML = "Sorry, you are too late.";
                } else {
                    var secs = params.time % 60;
                    if ( secs < 10 ) {
                        secs = "0" + secs;
                    }
                    var countdn1 = ( params.time - secs ) / 60;
                    var mins = countdn1 % 60;
                    if ( mins < 10 ) {
                        mins = "0" + mins;
                    }
                    countdn1 = ( countdn1 - mins ) / 60;
                    var hours = countdn1 % 24;
                    var days = ( countdn1 - hours ) / 24;

                    if (params.just_days == true){
                      document.getElementById( params.element ).innerHTML =  days;
                    }else{
                       document.getElementById( params.element ).innerHTML = [ days, " days + ", hours, " : ", mins, " : ", secs].join("");
                     }
                    setTimeout(
                        function() {
                            return NICHE.countdown.displayCountdown( params );
                        }
                    , 999 );
                }
            }
        }
    };
}();
/* SuckerFish Menue IE fix */

sfHover = function() {
  if($("#primary-nav").length){
    var sfEls = document.getElementById("primary-nav").getElementsByTagName("LI");
    for (var i=0; i< sfEls.length; i++) {
      sfEls[i].onmouseover=function() {
        this.className+=" sfhover";
      }
      sfEls[i].onmouseout=function() {
        this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
      }
    }
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

/* SuckerFish Menue IE fix [ end ] */

function saveReviewId(reviewIdStr, foundHelpfulVal) {
        document.updateProductReviewHelpfulCountForm.productReviewId.value = reviewIdStr;
        document.updateProductReviewHelpfulCountForm.foundHelpful.value = foundHelpfulVal;
        document.updateProductReviewHelpfulCountForm.submit();
}
utilityBrowserVer = parseInt(navigator.appVersion);
function imgOn(imgName) {
	if (utilityBrowserVer >= 3) {
		imgOnString = eval(imgName + "_on.src");
		document.images[imgName].src = imgOnString;
	}
}
function imgOff(imgName) {
	if (utilityBrowserVer >= 3) {
		imgOffString = eval(imgName + "_off.src");
		document.images[imgName].src = imgOffString;
	}
}
function goToLink(address) {
	var linkURL = address.options[address.selectedIndex].value;
	window.top.location.href = linkURL;
	address.selectedIndex = 0;
}
// modified function to use popupoverlay insted of using window.open this updates all other popup functions used on the cart tad 
function openWindow(address, width, height) {
//	var newWindow = window.open(address, 'Popup_Window', 'width=' + width + ',height=' + height + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no');
//	newWindow.focus();
	var newWindow = popupOverlay(address, width, height)
}
function openWindow1(address, width, height, resize) {
	var newWindow = window.open(address, 'Popup_Window', 'width=' + width + ',height=' + height + ',toolbar=yes,location=yes,directories=no,status=no,menubar=no,scrollbars=no,resizable=' + resize);
	newWindow.focus();
}
function openPayPalWindow(address) {
	var newWindow = window.open(address, 'Popup_Window');
	newWindow.focus();
}
function confirmWindow(url, text) {
	if (confirm(text)) {
		window.go = url;
		window.location = url;
	}
}
 // Display tabs.
    function landingPageTabs(){
        $(".landingpage-tab-view","#landingpage-tabs-view").css("display","none");
        if (location.search.length > 0){
            var dataPassed = unescape(location.search.substring(1));
            var openTabParam = "tab="
            var openTabIndexExists = dataPassed.indexOf(openTabParam);
            var openTabIndex = null;
            if (openTabIndexExists >= 0){
                openTabIndex = dataPassed.substring(openTabParam.length)
            }
        }
        if (openTabIndex != null){
            $(".landingpage-tab:eq("  + openTabIndex + ")").parent("li").addClass("current");
            $(".landingpage-tab-view:eq(" + openTabIndex + ")","#landingpage-tabs-view").css("display","block");
        }
        else {
         $("div:eq(0)","#landingpage-tabs-view").css("display","block");
         $(".landingpage-tab:eq(0)").parent("li").addClass("current");
        }
        $(".landingpage-tab","#landingpage-tabs").click(function() {
            $(".landingpage-tab-view","#landingpage-tabs-view").css("display","none");
            $(".landingpage-tab").parent("li").removeClass("current");
            var o = this;
            $(".landingpage-tab","#landingpage-tabs").each(function(i) {
                if (o == this) {
                $(".landingpage-tab:eq(" + i + ")").parent("li").addClass("current");
                $(".landingpage-tab-view:eq(" + i + ")","#landingpage-tabs-view").css("display","block");
                }

            });
            return false;
        });
    }
var itemScroller = {
    init: function(outerWrap,innerWrap,item){
      itemScroller.containerWidth(outerWrap,innerWrap,item);
      if ( $(item, outerWrap).size() < 4){
        $(outerWrap).prev().hide();
        $(outerWrap).next().hide();
      }
    },
    itemCount: function(c,i){

      return  $( i , c ).size();
    },
    containerWidth: function(outerC,innerC,i){
       $(innerC, outerC).width(itemScroller.itemCount( outerC ,  i ) * $(i, outerC).width());
    }
}


/* Detect if images are are turned on */
//var DetectImageState = {
//    imagesDisabled: true
//	,inserted_id: 'detectimagestate-test-img'
//	,callback: function() { }
//	,ie_detectionComplete: false
//	,img: null
//	,ie_Timeout: 500
//
//	,init: function(testerimg, cb) {
//		this.callback = cb;
//
//		$('body').prepend('<img id="'+this.inserted_id+'" style="visibility:hidden; position:absolute;left:-1000px;" src="'+testerimg+'?'+Math.random()+'" alt="" />');
//		this.img = document.getElementById(this.inserted_id);
////
////		if(window.opera || navigator.userAgent.toLowerCase().indexOf('opera')>-1) {
////			var pre = this.img.complete;
////			this.img.src = 'about:blank';
////			this.imagesDisabled = (!pre && this.img.complete) ? false : true;
////			DetectImageState.callback(this.imagesDisabled);
////			return;
////		}else if(typeof this.img.readyState != 'undefined') {
////			this.img.src = this.img.src+'?'+Math.random();
//			this.img.onabort = function() {
//				DetectImageState.ie_detectionComplete = true;
//				DetectImageState.imagesDisabled = false;
//				DetectImageState.callback(DetectImageState.imagesDisabled);
//			};
//			setTimeout('if(!DetectImageState.ie_detectionComplete) DetectImageState.callback(DetectImageState.imagesDisabled);', this.ie_Timeout);
//			return;
//		}else {
//			this.imagesDisabled = this.img.complete;
//			DetectImageState.callback(this.imagesDisabled);
//			return;
////		}
//this.img.onerror = function (evt) {
//  alert(this.src + " can't be loaded.");
//  }
//
//        if(this.img.complete){
//          $('body').attr("class","has-images");
//        }
//	}
//};
//
///* If images are turned on then this function applies a class to the body */
//function detection_complete(bDisabled) {
//    alert(bDisabled);
////	if(!bDisabled){
////	    $('body').attr("class","has-images");
////	}
//}
