 var $ = jQuery,
        getById = function(n){ return document.getElementById(n); };


document.getElementsByAttribute = function(attribute, value, tagName, parentElement) {
	var __children = (parentElement || document.body).getElementsByTagName((tagName || '*'));
	var __child, __attributeValue;
	var __elements = new Array();
	for(var ___e=0;___e < __children.length-1;___e++) {
		__child = __children[___e];
		__attributeValue = __child.getAttribute(attribute);
		if(!value || __attributeValue == value)
			__elements.push(__child);
	}
	return __elements;
}

$("#CategoryRefine").change(function() {
    var src = $("option:selected", this).val();
    window.location = src;
});


$('.compare_link').each(function(){
	$(this).removeAttr("href")
	$(this).qtip({
		content:{text:'Select two or more products, then click yellow button to compare'},
		position:{corner:{target:'bottomMiddle',tooltip:'topMiddle'},adjust:{screen:true}},
		show:{effect:{type:'slide',length:200},when:{event:'mouseover'}},
		hide:{effect:{type:'fade',length:0},when:{event:'mouseout'},fixed:true},
		style:{
			width: 230,
			background:'#FCD309',
			color:'black',
			textAlign:'left',
			'font-weight': 'normal',
			border:{width:1,radius:0,color:'#FCD309'},
			tip:{corner:'topMiddle'},
			name:'dark'}
		})
});


__oosT = false;
var setTooltips = function () {
	
	if(!__oosT)
	jQuery('.add-to-cart-disabled').tooltip({
	    delay: 0,
	    track: true,
	    showURL: false,
	    fixPNG: true,
	    top: -25,
	    left: -10,
	    bodyHandler: function() {
	        return __select_msg; 
	    }
	});
	
	jQuery('.add-to-wishlist').tooltip({
	    delay: 0,
	    track: true,
	    showURL: false,
	    fixPNG: true,
	    top: -25,
	    left: -10,
	    bodyHandler: function() {
	        return __select_msg; 
	    }
	});
	
	
	
}

$(document).ready(setTooltips);


//show Shop Partner tooltip
var showSPTooltip = function(id) {
	
	var thisSizeID = '#' + $(id).attr('id');
	
	var thisLeft = $(thisSizeID).position().left;
	var thisTop = $(thisSizeID).position().top;
	var thisWidth = $(id).width();
	var oosWidth = $('.outOfStock').width();
	var oosCentered = thisLeft - (oosWidth / 2) + (thisWidth / 2) + 3;
	
	var isDisabled = $(id).hasClass('disabled');

	// alert("l:" + thisLeft + "t:" + thisTop + " w:" +  oosWidth + " c:" + oosCentered);
	
	if (isDisabled == true)
	{

		$('.outOfStock').css('left', oosCentered);
		$('.outOfStock').css('top', thisTop + 1 );
		$('.outOfStock').show();			
	}
	
}

// hide Shop Partner tooltip
var hideSPTooltip = function () {
	$('.outOfStock').hide();
}


// initialize Shop Partners OOS (Out Of Stock)
var initShop = function() {

	// dimension OOS
	$('.innerdimension').mouseenter(function (){
		
		if ($(this).hasClass('disabled') == true)
		{
			showSPTooltip(this);
		}
		
	}).mouseleave(function() {
		hideSPTooltip();
	});
	
	// size OOS
	$('.disabled').mouseenter(function (){
		
		showSPTooltip(this);
		
		
	}).mouseleave(function() {
		hideSPTooltip();
	});
	
	$('.innersize').hover(function (){
		
		var isDisabled = $(this).hasClass('disabled');
			
		if (isDisabled == false)
		{
			hideSPTooltip();			
		}
		
	});
	
	$('.outOfStock').mouseenter(function() {
		$(this).show();
	}).mouseleave(function() {
		$(this).hide();
	});
	
	$('.swatch').click(function (){
		hideSPTooltip();	
	});
	/* end shop partners */
}

$('.innersize').click(function(){
	initShop();
});

$('.innerdimension').click(function(){
	initShop();
});

var refreshSwatches = function() {
	$('.swatch').click(function(){
		
		
		//debugger;
        if($('a', this.parentNode).hasClass('plus')) return;
        
        $('.innerswatch', $(this).parentNode).removeClass('selected');
        $('.innerswatch', $(this)).addClass('selected');
      
        var __imgid = this.attributes['imageid'].value;
        var __el = document.getElementById(__imgid);
        
        if(__el) __el.src = $('a', $(this)).attr('rel');
        
        return false;
    });
}


$('.swatch').click(function(){

	
	
	var __imgid = this.attributes['imageid'].value;
	var __swf = this.attributes['swf'];
	var __colorid = this.attributes['colorid'].value;
	var __pid = ParseID(this.attributes['pid'].value);
	
	var __colorname = this.attributes['colorname'].value;
	var __el = document.getElementById(__imgid);
	var __parent = document.getElementById(__pid + "_product_variations");	
	
	$('.innerswatch', $('.' + __pid + '_container')).removeClass('selected');
    $('.innerswatch', $('.' + __pid + '_' + __colorid)).addClass('selected');
      
 	this.colorid=__colorid;
 	this.image=__colorid;
 	//debugger;
 	
 	
 	

 	if(FlashDetect) {
 		// FLASH NOT INSTALLED - SHOW JPG OF PRODUCT
 		if(!FlashDetect.installed){
 			
 			// get product variation image
 			 var src = $('.swatch .selected a').attr("rel");
 		
 			 // remove pgrid_sm from the url - add pgrid_large to get the large image
 			 src = src.replace('$MHW_pgrid_med$','$MHW_pgrid_large$')
 			 
 			 // replace product image src w/ large image
 			 $('#product-img img').attr('src', src);
 			 $('#product-img img').attr('height', '385');
 			 
 			 
 			
 			// show jpg, hide flash
 			$('#product-img').show();
 			$('#flashcontent').hide();

 			if(__productArray !== undefined) { 
				// Change Color Selected Name
				var __csname = $('#' + __pid + '_color_name', __parent);
				
				if(__csname.length > 0)
				{
					$(__csname[0]).html(__colorname);
				}

				ProcessVariantAttributeSelection(__pid, __colorid, "", 'color');		
				CheckEnableAddToCart(__pid);
			}
 			
 		}
 		
 		// FLASH IS INSTALLED - SHOW PRODUCT SWF
 		else {
 	
		 	if(!(__swf.value == "")) {
				// <![CDATA[
				var so = new SWFObject(__swf.value, "", "488", "388", "9", "#FFFFFF");
				so.addParam("wmode", "transparent");
				so.addParam("allowScriptAccess", "always");
				so.addParam("allowFullScreen", "true");
				so.addParam("flashVars", "allowScriptAccess=always");
				so.write("flashcontent");
				// ]]>
			} else {
				if(__el) {
					__el.src = $('a', $(this)).attr('rel');
				} else {
					var __el = $('#' + ParseID(__imgid) + '_primary', document.body);
		
					if(__el) {
						for(var ___sw=0; ___sw<__el.length;___sw++)
							__el[___sw].src = $('a', $(this)).attr('rel');
					}
				}
			}
		
			var __fb=document.getElementById("fbhl");
			if (__fb) {
				__fb.href=__fb.href.substring(0,__fb.href.indexOf("Product-Show"));
				__fb.href=__fb.href + "Product-Show?pid="+__pid+"&v=true&color="+__colorid;
				}
			
			if(__productArray !== undefined) { 
				// Change Color Selected Name
				var __csname = $('#' + __pid + '_color_name', __parent);
				
				//throws JS error in IE
				//if(__csname.length > 0)
				//	__csname[0].innerHTML = __colorname;
				
				//s.golden - use this instead of innerHTML above to make IE happy
				if(__csname.length > 0)
				{
					$(__csname[0]).html(__colorname);
				}
				
				
				// 360 Spinner and Enlarge
				var __a360 = $('a.scene7enlarge-modal');
				var __aEnlarge = $('a.360spinner-modal');
				
				if(__a360.length > 0) {
					var __a360url = __a360.attr("url").split("=")[0] + '=' + __pid + "&colorid=" + __colorid;
					__a360.attr("url", __a360url);
				}
				if(__aEnlarge.length > 0) {
					var __aEnlargeUrl = __aEnlarge.attr("url").split("=")[0] + '=' + __pid + "&colorid=" + __colorid;
					__aEnlarge.attr("url", __aEnlargeUrl);
				}
		
				ProcessVariantAttributeSelection(__pid, __colorid, "", 'color');		
				CheckEnableAddToCart(__pid);
		
			}
 		}
 	}
 	
 	initShop();
 	
    return false;
});

$('.size_box').click(function(){

	if($('.innersize', $(this)).hasClass('disabled')) return;
	if($('.innersize', $(this)).hasClass('no_ecommerce')) return;
	
    $('.innersize', $(this).parentNode).removeClass('selected');
    $('.innersize', $(this)).addClass('selected');
    
   
    
	var __pid = ParseID(this.attributes['pid'].value);
	var __sizeid = this.attributes['sizeid'].value;
	var __parent = document.getElementById(__pid + "_product_variations");
	var __colorSelected = $('.selected', $('.swatch', __parent));
	var __colorid;

	if(__colorSelected)
		__colorid = __colorSelected[0].parentNode.attributes['colorid'].value
	
	if(!(__colorid === undefined)) {
		ProcessVariantAttributeSelection(__pid, __colorid, __sizeid, 'size');
	}
	
	CheckEnableAddToCart(__pid);
	
	initShop();
	
    return false;
});

$('.dimension').click(function(){

	if($('.innerdimension', $(this)).hasClass('disabled')) return;
	if($('.innerdimension', $(this)).hasClass('no_ecommerce')) return;

	var __pid = ParseID(this.attributes['pid'].value);
	
    $('.innerdimension', $(this).parentNode).removeClass('selected');
    $('.innerdimension', $(this)).addClass('selected');

    CheckEnableAddToCart(__pid);
    
    initShop();
    
    return false;
});

$('.add-to-cart').click(function() {
	
	var __pid = ParseID($(this).attr("id"));
	var __form = $('#' + __pid + '_product_detail_form', document.body);
		
	if($(this).hasClass('add-to-cart-disabled') == true) return;
	
	app.minicart.add(__form[0], jQuery(this).attr('rel'), undefined, function() {
        // redraw scollpane to prevent problems with firefox and safari
        // untested in ie
		   $('#minicart-content .items').jScrollPane({showArrows:true, scrollbarWidth: 21, arrowSize: 19});
		   $('#minicart-layer a.mini-close').click(function(){
		        minicartClosedTime = (new Date()).getTime();
		        $('#minicart-layer').toggle();
		    });
  });
	$('.checkout_link').show();
});

$('.wishlistbutton').click(function() {
	if($(this).hasClass('add-to-cart-disabled') == true) return false;
});

function ParseID(id)
{
	var __oldid = id.split("_");
	var __idlen = __oldid.length-1;
	var __newid = "";
	var __el;

	for(var ___i=0;___i<__oldid.length;___i++)
	{
		if(!(__idlen == ___i))
			__newid += __oldid[___i];
		
		if(___i < __idlen-1)
			__newid += "_";
	}
	
	return __newid;
}

function CheckEnableAddToCart(pid) {
	var __enable = true;
	var __parent = document.getElementById(pid + "_product_variations");
	
	var __colorid="";
	var __sizeid="0";
	var __dimensionid="0";
	
	var __color = $('.product_swatches', __parent).length;
	var __size = $('.size_boxes_row', __parent).length;
	var __dimension = $('.dimension_container', __parent).length;
	
	var __oos = true;
	
	if(__color > 0) {
		var __color_selected = $('.selected', $('.swatch', __parent));
		if(__color_selected.length == 0)
			__enable = false;
		else
			__colorid = __color_selected[0].parentNode.attributes["colorid"].value;
	}
	
	if(__size > 0) {
		var __size_selected = $('.selected', $('.size_box', __parent));
		if(__size_selected.length == 0)
			__enable = false;
		else
			__sizeid = __size_selected[0].parentNode.attributes["sizeid"].value;
	}
	
	if(__dimension > 0) {
		var __dimension_selected = $('.selected', $('.dimension', __parent));
		if(__dimension_selected.length == 0)
			__enable = false;
		else
			__dimensionid = __dimension_selected[0].parentNode.attributes["dimensionid"].value;
	}
	
	var __addToCartBtn = document.getElementById(pid + "_submit");
	var __wishListLink = document.getElementById("wishlistlink");
	
	if(__enable == true) {
		if(__addToCartBtn) {
		
			$(__addToCartBtn).removeClass('add-to-cart-disabled');
			$(__addToCartBtn).tooltip({});
			$(__wishListLink).tooltip({});
			
			// Find variant product id based on selected attributes
			var __found = false;
			var __product, __variant;
			for(var ___p=0;___p < __productArray.length; ___p++) {
				if(__productArray[___p][0] == pid) {
					__product = __productArray[___p];
					
					for(var ___v=0;___v < __product[1].length; ___v++) {
						__variant = __product[1][___v];

						if((__variant[0] == __colorid) && (__variant[1] == __sizeid) && (__variant[2] == __dimensionid)) {
							var __txtPID = $('#pid', $('#' + pid + '_product_detail_form'));
							__txtPID[0].value = __variant[5];
							if(__wishListLink) {
								var __wishlisturl = __wishListLink.attributes["wurl"].value;
								
								__wishListLink.onclick = function() {
						            window.location = __wishlisturl + "?pid=" + __variant[5] + "&Quantity=" + $('#Quantity').val(); + "return false;";
						        };
								
								$('#wishlistlink').removeClass('disabledWishlist');
							}
							__found=true;
							break;
						}						
					}					
				}
				if(__found)
					break;
			}
		}
	} else {
		var __addToCartBtn = document.getElementById(pid + "_submit");
		if(__addToCartBtn) {
			if($(__addToCartBtn).hasClass('add-to-cart-disabled') == false) {
				$(__addToCartBtn).addClass('add-to-cart-disabled');
				$(document).ready(setTooltips);
			}
		}
		if(__wishListLink) {
			__wishListLink.removeAttribute("href");
			__wishListLink.setAttribute("onclick", "return false;");
			$('#wishlistlink').addClass('disabledWishlist');
		}
	}

	if($('.size_box div').length != $('.size_box div.disabled').length)
		__oos = false;

	if(__oos == true) {
		if(__addToCartBtn) {
			if($(__addToCartBtn).hasClass('add-to-cart-disabled') == false) {
				$(__addToCartBtn).addClass('add-to-cart-disabled');
			}
			$(__addToCartBtn).val("OUT OF STOCK");
			$(__addToCartBtn).tooltip({});
			__oosT = true;
			$('#wishlistlink').hide();

			var __o = $('.innerdimension');
			if(__o) {
				__o.addClass('disabled');
			}
		}
	}
	else
	{
		$(__addToCartBtn).val("ADD TO CART");
		$('#wishlistlink').show();
		__oosT = false;
	}
	
	initShop();
}

function ProcessVariantAttributeSelection(pid, colorid, sizeid, type) {
	
	var __product, __variant;
	
	for(var ___p=0;___p < __productArray.length; ___p++) {
		if(__productArray[___p][0] == pid) {
			__product = __productArray[___p];
		
			for(var ___v=0;___v < __product[1].length; ___v++) {
				__variant = __product[1][___v];
				
				switch(type) {
					case "color":
						if(__variant[0] == colorid) {
							var __parent = document.getElementById(pid + "_product_variations");
							var __sizes, __dimensions;
							if(__parent) {
								__sizes = document.getElementsByAttribute("pid", pid + "_size", "div", __parent);
								__dimensions = document.getElementsByAttribute("pid", pid + "_dimension", "div", __parent);

								// SIZES
								var __size, __found, __svariant;
								for(var ___s=0;___s < __sizes.length;___s++) {
									__size = __sizes[___s];
									__found = false;
									for(var ___vs=0;___vs < __product[1].length; ___vs++) {
										__svariant = __product[1][___vs];
										if(__svariant[0] == colorid) {
											if(__svariant[1] == __size.attributes["sizeid"].value) {
											   if(__svariant[3] == true && __svariant[4] == true) {
											
											   	  __found = true;
											   	  break;
											   }
											}
										}
									}
									var __sz = $('.innersize', __size);
									if(!__sz.hasClass('no_ecommerce'))
									{
										if(__found) {
											if(__sz) {
												__sz.removeClass('disabled');
												__sz.removeClass('selected');
											}										
										} else {
											if(__sz) {
												__sz.addClass('disabled');
												__sz.removeClass('selected');
											}
										}
									}
								}
								
								// When a color is chosen, dimensions, if exist are all reset to default, 
								// because size denotes dimensions available
								var __dm;
								for(var ___d=0;___d < __dimensions.length;___d++) {
									__dimension = __dimensions[___d];
									__dm = $('.innerdimension', __dimension);
									if(__dm) {
										__dm.removeClass('disabled');
										__dm.removeClass('selected');
									}
								}
							}
						}
						break;
					case "size":
						if(__variant[0] == colorid && __variant[1] == sizeid) {
							var __parent = document.getElementById(pid + "_product_variations");
							var __dimensions;
							if(__parent) {
								__dimensions = document.getElementsByAttribute("pid", pid + "_dimension", "div", __parent);

								// DIMENSIONS
								var __dimension, __found, __dvariant;
								for(var ___d=0;___d < __dimensions.length;___d++) {
									__dimension = __dimensions[___d];
									__found = false;
									for(var ___vd=0;___vd < __product[1].length; ___vd++) {
										__dvariant = __product[1][___vd];
										if(__dvariant[0] == colorid && __dvariant[1] == sizeid) {
											if(__dvariant[2] == __dimension.attributes["dimensionid"].value) {
											   if(__dvariant[3] == true && __dvariant[4] == true) {
											   	  __found = true;
											   	  break;
											   }
											}
										}
									}
									if(__found) {
										$('.innerdimension', __dimension).removeClass('disabled');
									} else {
										var __o = $('.innerdimension', __dimension);
										if(__o) {
											__o.addClass('disabled');
											__o.removeClass('selected');
										}
									}									
								}
							}
						}
						break;
				}
			}
		}
	}	
}



function getWindowLocation() 
{
	var url = window.location.toString();
	
	return url;
}

/* modal for email a friend */
var emailFriendHolder = $('.email-friend-holder');        
$('.email-friend-btn').click(function(){
	 modal({
	        title: 'SHARE WITH A FRIEND'
	         ,body: emailFriendHolder.html()
	        ,width: 400
	    });
    return false;
});


this.emailFriend = function(form){
    var inputDiv = $('.ui-dialog-content');
    var inputs = $('input,textarea',form);
    var cssWarningObj = {
    	      'font-weight' : 'bold',
    	      'color' : '#FF6600'
    	    }
    var cssNormalObj = {
  	      'font-weight' : 'bold',
  	      'color' : '#FFFFFF'
  	    }
    
    $.ajax({
        type: "POST"
        ,url: form.action
        ,data: inputs
        ,success:function(response){
            /* need to update below if web service returns something else */          	
    		var myResponse = eval('(' + response + ')');
    		if(myResponse.isSuccess){
                inputDiv.html(
                    '<div class="email-friend-holder" id="confirmation-message">'
                    +'<h3>Product Shared</h3>'
                    +'<p>' + myResponse.message + '</p>'
                    +'</div>'
                );
                
            } else {
            	if (myResponse.errorCode.indexOf('0') != -1) 
            		$('.warning:eq(0)',form).html("Please fix the errors noted below.");
            		
            	var retCode = myResponse.errorCode.split(';');
            	//alert(myResponse.errorCode);
            	
            	
            	(retCode[0] == "0") ? $('label[for=Id_dwfrm_tellafriend_sendersfirstname]',form).css(cssWarningObj) : $('label[for=Id_dwfrm_tellafriend_sendersfirstname]',form).css(cssNormalObj);    	// sender FN		
            	//(retCode[1] == "0") ? $('.inputKey:eq(1)',form).css(cssWarningObj) : $('.inputKey:eq(1)',form).css(cssNormalObj);		// sender's LN
            	if (retCode[2] == "0") { 																									
            		$('label[for=Id_dwfrm_tellafriend_sendersemail]',form).css(cssWarningObj);
            		$('.warning:eq(1)',form).html("");
            	} else if (retCode[2] == "-1") {
            		$('label[for=Id_dwfrm_tellafriend_sendersemail]',form).css(cssWarningObj);
            		$('.warning:eq(1)',form).html("Invalid email.");
            	} else {
            		$('label[for=Id_dwfrm_tellafriend_sendersemail]',form).css(cssNormalObj);
            		$('.warning:eq(1)',form).html("");
            	}
            	
            	
            	(retCode[3] == "0") ? $('label[for=Id_dwfrm_tellafriend_friendsfirstname]',form).css(cssWarningObj) : $('label[for=Id_dwfrm_tellafriend_friendsfirstname]').css(cssNormalObj);		// friend's FN
            	//(retCode[4] == "0") ? $('.inputKey:eq(4)',form).css(cssWarningObj) : $('.inputKey:eq(4)',form).css(cssNormalObj);		// friend's FN
            	if (retCode[5] == "0") { 																									
            		$('label[for=Id_dwfrm_tellafriend_friendsemail]',form).css(cssWarningObj);
            		$('.warning:eq(2)',form).html("");
            	} else if (retCode[5] == "-1") {
            		$('label[for=Id_dwfrm_tellafriend_friendsemail]',form).css(cssWarningObj);
            		$('.warning:eq(2)',form).html("Invalid email.");
            	} else {
            		$('label[for=Id_dwfrm_tellafriend_friendsemail]',form).css(cssNormalObj);
            		$('.warning:eq(2)',form).html("");
            	}
            }
        }
        ,error:function(){
            inputDiv.html(
                '<div class="email-friend-holder" id="confirmation-message">'
                +'<h3>Error</h3>'
                +'<p>There was a problem sending your request.</p>'
                +'</div>'
            );
        }
    })
    return false;
};


/* shop our partners link */
$('a.load-shop-our-partners-modal').click(function(e) {
	e.preventDefault();
	
	if (typeof omnProducts != 'undefined')
	{
		s.pageName="Product Detail: "+omnProducts;
		s.prop1="Product Details Page";
		s.prop2=s.prop1;
		s.prop3=s.prop1;
		s.prop4=s.prop1;
		s.prop7=s.eVar7="MHW";
		s.prop8=s.eVar8="US";
		s.state=omnStateCode;
		s.zip=omnPostalCode;
		s.events="event11";
		s.products=";"+omnProducts;
		/************* DO NOT ALTER ANYTHING BELOW THIS LINE ! **************/
		var s_code=s.t();if(s_code)document.write(s_code);	
	}
	
	var $this = $(this);
	var horizontalPadding = 53;
	var verticalPadding = 70;
    $('<iframe src="' + this.href + '" />').dialog({
        title: ($this.attr('title')) ? $this.attr('title') : 'External Site',
        autoOpen: true,
        zIndex: 10000,
        width: 550,
        height: 300,
        modal: true,
        resizable: true,
		autoResize: true,
        overlay: {
            opacity: 0.8,
            background: "#5C5C5C"
        }
    }).width(550 - horizontalPadding).height(350 - verticalPadding);	        
});

/*
$('a.load-shop-our-partners-modal').click(function(){
	
	var __pid = this.attributes['pid'].value;
	var __url = this.attributes['url'].value;
	var __title = ((this.attributes["mtitle"] == null) ? "Shop Our Partners" : this.attributes["mtitle"].value);
	var __width = ((this.attributes["mwidth"] == null) ? 400 : parseInt(this.attributes["mwidth"].value));
	
    modal({
            title: __title
            ,body: 'Loading...'
            ,width: __width                
        });

        $.ajax({
            type: "GET",
            url: __url,
            data: 'sku=' + __pid, 
            success: function(response){
                modals[__title].html(response);
            }

        });
    return false;
});
*/

jQuery(document).ready(function(){
/* limit textarea-s with the class of 'limitedreview' to a max of 900 characters */
$('textarea.limitedreview').keyup(function(){
	
	var limit = 900,
        text = $(this).val(),
        textlength = text.length,
        charCountInfo = $('.char-count', this.parentNode);
    /// end var block;

	/// Modified next section to fix Bug 2164   tschwartz 9-2-09
    if (textlength>limit) {  
    	$(this).val( text.substr(0, limit) );
    	this.scrollTop = this.scrollHeight;
	}

    charCountInfo.html( (limit - $(this).val().length) + ' characters remaining' );
    return false;
    
}).keyup();
});
