$(document).ready(function(){
	//standard AJAX mail form submission (requires mail2_plus.php, and captcha)
	//add form name to selector for submit event, the rest will take care of itself!
	$("input[type=submit]").removeAttr("disabled");
	$("#inquiry").submit(function(e){
		e.preventDefault();
		var form = $(this);
		var btn = $(this).find("input[type=submit]");
		btn.attr("disabled","disabled");
		$.post("includes/mail2_plus.php",form.serialize(),function(data){
			var err = data.split("|");
			if (err[0] == "error") {
				alert(err[1]);
				btn.removeAttr("disabled");
			} else {
				//if a redirect is specified, use that. Else replace the form with a message.
				if (form.find("input[name=redirect]").length && form.find("input[name=redirect]").val() != "") {
					window.location = form.find("input[name=redirect]").val();
				} else {
					form.html("<p class='sent'>Your message has been sent.</p>");
				}
			}
		});
	});
	
	$("#prod_det_nav a").click(function(e){
		e.preventDefault();
		var showthis = extractId($(this).attr("id"));
		$("#prod_det_nav .selected").removeClass("selected");
		$(this).parents("li").addClass("selected");
		$(".pd_content").hide();
		$("#pd_" + showthis).show();
	});
	
	
	$(".add_img_link").click(function(e){
		e.preventDefault();
		var newimg = "<img src='" + $(this).attr("href") + "' />";
		//make a link to the large image for opening the correct image when enlarge is clicked... yeah that sentence made sense.
		var large = $(this).attr("href").replace("/medium/","/large/");
		$(newimg).load(function(){
			$(".main_prod_img").attr("href",large);
			$(".main_prod_img img").replaceWith(newimg);
		});
	});
	
	$(".main_prod_img,.show_addprod").click(function(e){
		e.preventDefault();
		var id = extractId($(this).attr("id"));
		var bg = "<div id='popup_bg'></div>";
		var showimg = "<img src='" + $(this).attr("href") + "' />";
		$(bg).appendTo("body").hide().fadeTo("fast",.5);
		$.post("includes/get-sku-gallery.php",{"id":id},function(data){
			var err = data.split("|");
			if (err[0] == "error") {
				alert(err[1]);
				$("#popup_bg").remove();
			} else {
				$(showimg).load(function(){
					$(data).appendTo("body").hide();
					$("#sku_gal_large").html(showimg);
					var ypos = $(window).scrollTop() + ($(window).height() / 2) - ($("#sku_gal").height()/2);
					$("#sku_gal").css({"top":ypos}).fadeIn();
				});
			}
		});
	});
	
	$(".sku_gal_link").live("click",function(e){
		e.preventDefault();
		var newimg = "<img src='" + $(this).attr("href") + "' />";
		$(newimg).load(function(){
			$("#sku_gal_large").html(newimg);
		});
	});
	
	$("#popup_bg,#sku_gal_close").live("click",function(e){
		e.preventDefault();
		$("#sku_gal").fadeOut("fast",function(){
			$(this).remove();
		});
		$("#popup_bg").fadeOut("fast",function(){
			$(this).remove();
		});
	});
});

function extractId (id) {
	var newid = id.split("_");
	return newid[1];
}
