$(document).ready(function(){

	// Help popup
	$("a.help").click(function(){
	
		helpWindow = window.open($(this).attr("href") + "?popup=true", "help", "width=300,height=300,resizable=yes,scrollbars=yes");
		helpWindow.moveTo(50,50);
		return false;
		
	});
	
	// Newsletter signup email box usability
	emailBoxText = "Your email";
	$("#newsletter-widget #subscription_email").focus(function() {
		if ($(this).val() == emailBoxText) $(this).val("");
	});
	$("#newsletter-widget #subscription_email").blur(function() {
		if ($(this).val() == "") $(this).val(emailBoxText);
	});
	$("#newsletter-widget #subscription_email").blur();
	
	// Change image on the fly with swatch behavior
	$(".swatches a").click(function(){
		
		// Check if already active
		if ($(this).parent().hasClass("active")) return true;
		
		// Main display
		productDisplay = $(this).parents(".swatches").parent();
	
		// Overlay image for custom swatch
		if ($(this).parent().hasClass("custom")) {
			// Add overlay if not present
			if (!$(productDisplay).find(".customoverlay").length) {
				imagePath = $(this).find("img").attr("src").replace(/-swatch/, "-overlay");
				$(productDisplay).children("a").append("<img style=\"margin-left: -62px; margin-top: -50px;\" class=\"customoverlay\" src=\"" + imagePath + "\" width=\"124\" height=\"100\" alt=\"Design Your Own!\" />");
			}
			$(productDisplay).find(".customoverlay").show();
			$(productDisplay).children("a").attr("href", $(this).attr("href"))
		}
		// Else Change image
		else {
			$(productDisplay).find(".customoverlay").hide();
			imagePath = $(this).find("img").attr("src").replace(/-swatch/, "-thumb");
			$(productDisplay).children("a").attr("href", $(this).attr("href")).find("img:not(.customoverlay)").attr("src", imagePath);
		}
		
		// Change stock message
		if ($(this).parent().find(".available").length) {
			if ($(productDisplay).children("a").find(".available").length) $(productDisplay).children("a").find(".available").show();
			else $(productDisplay).children("a").append("<span class=\"available\">This colorway is available!</span>");
		}
		else $(productDisplay).children("a").find(".available").hide();
			
		// Change price
		$(productDisplay).children("a").find(".price").replaceWith($(this).parent().find(".price").clone());
		
		// Change state
		$(productDisplay).find(".swatches").children().removeClass("active");
		$(this).parent().addClass("active");
		
		return false;
		
	});

});