var fancyPhotoOptions = { 
	'centerOnScroll': true,
	'zoomSpeedIn': 200, 
	'zoomSpeedOut': 200, 
	'overlayShow': true,
	'hideOnContentClick': true,
	'frameWidth': 500,
	'frameHeight': 500,
	'ajaxParam': "&ajax=true",
	'overlayOpacity': 0.8
};

var fancyAddOptions = { 
	'centerOnScroll': false,
	'zoomSpeedIn': 200, 
	'zoomSpeedOut': 200, 
	'overlayShow': true,
	'hideOnContentClick': false,
	'frameWidth': 450,
	'frameHeight': 500,
	'ajaxParam': "&ajax=true",
	'overlayOpacity': 0.8 
};

var initializeCartOptions;

$(function() {

	$(".viewLink").fancybox(fancyPhotoOptions);	
	
	$(".addToCart a").fancybox(fancyAddOptions);
	
	
	//make sure all external links always open in new window, and others open in fancybox
	$("a[href^=http]").live("click", function (e) { 
		e.preventDefault(); 
		window.open(this.href);
	});
	
	function updateCart(cartHTML) {
		var cart = $("#shoppingCart");
		cart.fadeOut("slow", function () {
			cart.html(cartHTML).fadeIn("slow");
		});
	}
	
	//sets up pricing, display of add to cart window
	initializeCartOptions = function() {
		var cartOpts = $("#size, #matType, #frameType, #cartQuantity, #typeOption input");
		
		if (cartOpts.length > 0) {
			
			$("#cartAdd").click(function () {
				var formValues = $("#cartOptions").serialize();
				formValues += "&ajax=true";
				jQuery.post("add.php", formValues, function (data, textStatus) {
					$.fn.fancybox.close();
					updateCart(data);
				});
				
				return false;
			});
			
			$("#cartCancel").click(function () {
				$.fn.fancybox.close();
				
				return false;
			});
			
			$(".advancedOptions").hide()
				.before("<p><a class='more' href='#'>More Options...</a></p>")
				.prev().find("a").click(function () {
					$(".advancedOptions").show('fast');
					$(this).parent().hide('fast');
					
					return false;
				});
			
			//setup hints
			$("#size").after("<span id='sizeHint' class='hint'></span>");
			$("#matType").after("<span id='matHint' class='hint'></span>");
			$("#frameType").after("<span id='frameHint' class='hint'></span>");
			
			cartOpts.change(checkOptions);
			
			checkOptions();
		}
	};
	
	//checks and corrects options. also calculates and sets the price
	function checkOptions() {	
		var sizeF = $("#size");
		var matF = $("#matType");
		var frameF = $("#frameType");
		var typeF = $("#typeOption input");
		var quantityF = $("#cartQuantity");
		
		var size = $("#size").attr("value");
		var mat = parseInt($("#matType").attr("value"));
		var frame = parseInt($("#frameType").attr("value"));
		var type = parseInt($("#typeOption input:checked").attr("value"));
		var quantity = parseInt(quantityF.val());

		if (quantity <= 0) //first deal with invalid quantity
			quantityF.val("1");
		
		$("#matHint").html("");
		$("#frameHint").html("");
		
		//fix the dropdowns to valid values
		if (size == "Notecard") {
			$("#typeOption input[value=0]").attr("disabled", false).attr("checked", true);
			$("#typeOption input[value!=0]").attr("disabled", true);
			type = 0;
			
			frameF.attr("disabled", true);
			matF.attr("disabled", true);
			
			$("#sizeHint").html("(Minimum six-card order.)");
		}
		else {
			frameF.attr("disabled", false);
			matF.attr("disabled", false);
			$("#sizeHint").html("");
			
			$("#typeOption input").attr("disabled", false);
			
			//open editions don't come in big sizes, 
			//and that's the only other invalid price according to the price table
			if (prices[size][0] <= 0) {
				var openEdOpt = $("#typeOption input[value=0]");					
				if (openEdOpt.attr("checked")) {
					$("#typeOption input[value=1]").attr("checked", true);
					type = 1;
				}
				openEdOpt.attr("checked", false).attr("disabled", true);
			}				
			
			frameF.attr("disabled", false);
			matF.attr("disabled", false);
			
			//must have a mat if using a frame!
			if (frame > 0 && mat <= 0) {
				mat = 1;
				matF.val(mat);
				$("#matHint").html("You must select a mat if selecting a frame.");
			}
			
			//deal with "Custom" mat and frame colors
			//TODO: add color picker!!!!
			var colorPicker = "We will contact you about custom frame &amp; and mat options when you place your order.";
			if (matF.find("option:selected").html() == "Custom")
				$("#matHint").html(colorPicker);
			if (frameF.find("option:selected").html() == "Custom")
				$("#frameHint").html(colorPicker);
		}
		
		var price = prices[size][type] * quantity;
		if (price > 0) {
			//add mounting price
			var mountingPrice = 0;
			if (size != "Notecard") {
				if (mat > 0) {					
					mountingPrice += matPrices[size];
					if (frame > 0) {
						mountingPrice += framePrices[size];
					}
				}
			}
			
			//update price
			price += mountingPrice * quantity;
			
			var printPrice = price;
			if (price != Math.round(price))
				printPrice = price.toFixed(2);
			$(".optionsPreview .price").html("$" + printPrice);
			
			//update frame and mat on image preview
			showPhotoPreview(size, type, mat, frame);
		}
	}
	
	//update frame and mat on image preview
	function showPhotoPreview(size, type, mat, frame) {
		var preview = $(".optionsPreview .thumb");
		var frameE = preview.children();
		var matE = frameE.children();
		var imgE = matE.children();
		
		//prepare sizes by img orientation
		if (imgE.width() < imgE.height()) {
			preview.removeClass("horizontal");
			preview.addClass("vertical");
		}
		else {
			preview.removeClass("vertical");
			preview.addClass("horizontal");
		}
		
		frameE.css("background", colorTable[frame]);
		matE.css("background", colorTable[mat]);
	}
	
	
	
	
	//view cart functions
	function initializeCart() {
		var cartSummary = $("#cartSummary");
		
		if (cartSummary.length > 0) {
			cartSummary.find(".quantity input")
				.after('<a href="#" class="removeLink"><span>Remove</span></a>')
				.next().click(function () {
					var rm = $(this);
					var quantity = rm.prev();
					var itemIdx = parseInt(quantity.attr("rel"));
					
					quantity.val(0);
					
					//just resubmit the form, it works better
					quantity.parents("form").submit();
					
					
					/*
					jQuery.get("remove.php", {itemIdx: itemIdx}, function (data, textStatus) {
						if (data.trim().length > 0) {
							$("#googleCheckout input[name$=_" + (itemIdx + 1) + "]").remove();
						
							rm.parents("tr").fadeTo("slow", 0.1, function () {
								$(this).find(".quantity").children().fadeOut('fast');
							})
								//change the indices of all following items since this one's
								//just been spliced out of the array!
								.nextAll().find(".quantity input").each(function() {
									var e = $(this);
									e.attr("rel", parseInt(e.attr("rel")) - 1);
								});

							updateCart(data);
						}
					});
					*/
					
					return false;
				});
		}
	}
	
	
	initializeCartOptions();
	initializeCart();
	
	
	//fix spamproof emails
	function fixEmails() {
		$(".emailAt").replaceWith("@");
		$(".emailLink").each(function() {
			var t = $(this);
			var addr = t.html();
			t.html("<a href='mailto:" + addr + "'>" + addr + "</a>");
		});
	}
	
	fixEmails();
});

