//New Mega Menu Dropdown functions
$(document).ready(function() {
	function megaHoverOver(){
		$(this).find(".sub").stop().fadeTo('fast', 1).show();
	    (function($) {
	        //Function to calculate total width of all ul's
	        jQuery.fn.calcSubWidth = function() {
	            rowWidth = 0;
	            //Calculate row
				if($(this).hasClass("tabs")) {
		            /*$(this).find("ul").each(function() { //for each ul...
		                rowWidth += $(this).width(); //Add each ul's width together
		            });*/
					alert("OMG WE HAVE TABS");
				}else{
		            $(this).find("ul").each(function() { //for each ul...
		                rowWidth += $(this).width(); //Add each ul's width together
		            });
					//alert("NO TABS TO SEE HERE KEEP MOVING");
				}
	        };
	    })(jQuery);
	    if ( $(this).find(".row").length > 0 ) { //If row exists...
	
	        var biggestRow = 0;	
	
	        $(this).find(".row").each(function() {	//for each row...
	            $(this).calcSubWidth(); //Call function to calculate width of all ul's
	            //Find biggest row
	            if(rowWidth > biggestRow) {
	                biggestRow = rowWidth;
	            }
	        });
	
	        //$(this).find(".sub").css({'width' :biggestRow}); //Set width
	        $(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin
	
	    } else { //If row does not exist...
	        $(this).calcSubWidth();  //Call function to calculate width of all ul's
	        //$(this).find(".sub").css({'width' : rowWidth}); //Set Width
	    }

	}
	
	function megaHoverOut(){ 
	  $(this).find(".sub").stop().fadeTo('fast', 0, function() {
		  $(this).hide(); 
	  });
	}
	
	var hoverConfig = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 20, // number = milliseconds for onMouseOver polling interval
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 100, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};

	$("#navbar td .sub").css({'opacity':'0'});
	$("#navbar td").not(".click").hoverIntent(hoverConfig);
	$(".outlet .sub").css({'opacity':'0'});
	$(".outlet").not(".click").hoverIntent(hoverConfig);
});

//Check for cart items and show # of items next to header link
$(document).ready(function(){
	if (getCookie('item_count')) {
		if(getCookie('item_count') > 0) {
			$("#header table.right td.cart a").text("CART ("+getCookie('item_count')+")");
		}
	}
});

//Add hover effect for outerwear/clothing highlights
$(document).ready(function(){
	//Add hover effect for outerwear/clothing highlights
	$("div#navbar td.clothing").hover(function(){
		$("div#header td.clothing").toggleClass("hover");
	});
});

//Hide refineby submit button for js enabled browsers and swap clear results link for button
$(document).ready(function(){
	$("#refinebyform .clearresults input").css({'display':'inline'});
	$("#refinebyform .clearresults a").css({'display':'none'});
	$("#refinebyform .submitbutton").css({'display':'none'});
});

//Product Thumbnail Rollover
$(document).ready(function(){
	$(".products #product .multi a").hover(
		function() {
			//Capture the new image link and build a new medium image link for display
			var swapimglink = $(this).attr("href");
			var medimglink = $(this).attr("href");
			medimglink = medimglink.replace("-zoom","-prod");
			swapimglink = swapimglink.replace("-zoom","");
			
			//Swap Product Image Link
			$(".product-image a").attr("href",swapimglink);
			//Swap Product Image
			$(".product-image #large img").attr("src",medimglink);
			//Swap Infobar Enlarge Link
			$("#specs .stripe #largeimglink").attr("href",swapimglink);
			
			//Reset Shadowbox Cache to update links
			Shadowbox.clearCache();
			Shadowbox.setup();
			$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();			
		}
	);
});

//Recently viewed products
$(document).ready(function(){
	if ($("body").hasClass("product")) {
		if (getCookie('recently_viewed_products')) {
			var rvphtml = '<div id="recently-viewed-products"><h3>Recently Viewed Products</h3><ul class="ui-helper-clearfix"></ul></div><hr>';
			$("div#product-reviews").before(rvphtml);
			
			try { 
				var recent_products = JSON.parse(getCookie('recently_viewed_products')); 
			} catch(e) { 
				console.log(e);
			}
		
			if (recent_products) {
				for (var product in recent_products) {
					var prodhtml = '<li>' +
						'<a href="'+recent_products[product]["url"]+'"><img src="'+recent_products[product]["img"].replace("-prod.jpg","-thumb.jpg")+'" width="110" height="130" alt="'+recent_products[product]["url"]+'" /><br />' +
						'<strong>'+decodeURIComponent(recent_products[product]["name"])+'</strong><br />';
					if (recent_products[product]["rating"] > 0) {
						prodhtml = prodhtml+'<div class="rateit" data-rateit-value="'+recent_products[product]["rating"]+'" data-rateit-ispreset="true" data-rateit-readonly="true"></div><br />';
					}
					prodhtml = prodhtml+recent_products[product]["price"]+'</a></li>';
					
					$("div#recently-viewed-products ul").append(prodhtml);
				}
				
				addRecentProduct(getProduct(),recent_products);
			}
		}else{
			var recent_products = [];
			recent_products.push(getProduct());
			setCookie("recently_viewed_products",JSON.stringify(recent_products),7);
		}
	}
});

//Recently Viewed Product functions
function getProduct() {
	var product = new Object;
	product['url'] = $('meta[itemprop="url"]').attr('content');
	product['name'] = encodeURIComponent($('h1[itemprop="name"]').text());
	product['price'] = $('div[itemprop="price"]').text();
	product['img'] = $('img[itemprop="image"]').attr('src');
	product['rating'] = $('div[itemprop="aggregateRating"] span[itemprop="ratingValue"]').text();
	return product;
}
function addRecentProduct(product,recent_products) {
	var uniqueProduct = true;
	for (var checkproduct in recent_products) {
		if(recent_products[checkproduct]["url"] == product["url"]) {
			uniqueProduct = false;
			break;
		}
	}
	if(uniqueProduct) {
		if(recent_products.length >= 5) {
			while(recent_products.length >= 5) {
				recent_products.shift();
			}
		}
		recent_products.push(getProduct());
		try { 
			setCookie("recently_viewed_products",JSON.stringify(recent_products),7);
		} catch(e) { 
			console.log(e);
		}
	}
}

//Cookie functions
function setCookie(name,value,days) {
	if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function removeCookie(name) {
	setCookie(name,"",-1);
}

//Clear default text from a form field
function doClear(theText) { if (theText.value == theText.defaultValue) { theText.value = "" } }

