$(document).ready(function(){
	
	// Add to cart interceptor and display
	$("#product_add").click(function(){
		
		// Disable button and change text
		newText = $(this).attr("value");
		$(this).attr("value", "Adding to your cart...").attr("disabled", "disabled");
		
		// Find size if applicable
		size = false;
		if ($("#product_size").attr("disabled") != true) size = $("#product_size").attr("value");
		
		// Get product and colorway ids
		addToCart($("#product_id").attr("value"), $("#colorway_id").attr("value"), size);
		
		return false;
		
		
	});
	
	// Size UI transformer
	if ($("#product_size").length && typeof allSizes != "undefined") {
		$("#product_size").hide().before("<ul id=\"sizeselector\" />");
		jQuery.each(allSizes, function(key, val) {
			sizeOption = $("<li id=\"size" + key + "\" title=\"This size is currently not available.\" onclick=\"selectSize(this);\">" + val + "</li>");
			if ($("#product_size option[value='" + key + "']").length || $("#product_size").attr("disabled")) sizeOption.addClass("available").attr("title", "This size is available!");
			if ($("#product_size option[value='" + key + "']:selected").length || $("#product_size").attr("disabled")) sizeOption.addClass("active");
			$("#sizeselector").append(sizeOption);	
		});
	}
	
	// Product zoom/unzoom
	$(".hero .zoom").click(function() {
	
		// Create markup if it doesn't exist
		if (!$("#wrapper #zoom").length) {
			$("#wrapper").append("<div id=\"zoom\" onclick=\"$('#wrapper #zoom').hide();\">" + 
				"<div class=\"box\">" + 
					"<img src=\"" + $(this).attr("href") + "\" alt=\"Large View\" />" +
					"<span class=\"close\" onclick=\"$('#wrapper #zoom').hide();\">Close Zoom</span>" +
				"</div>" +
			"</div>");
		}
		
		$("#wrapper #zoom").show();
		
		return false;
		
	});

});

// Add to cart function
function addToCart(productID, colorwayID, size) {
	
	addURL = "/shop/cart/add/?method=ajax&product_id=" + productID + "&colorway_id=" + colorwayID;
	if (typeof size != "undefined" && size) addURL += "&product_size=" + size;
	
	// Ajax to the cart
	$.getJSON(addURL, function(results) {
		
		// Modify quantities if necessary
 		if (results.updatedquantity) {
 			
 			// Make sure amount is present
 			if (!$(".cartamount").length) $(".shopping .shoppingcart strong").append(" (<span class=\"cartamount\"></span>)");
 			
 			// Write total price to page
		 	totalPrice = new Number(results.updatedtotal / 100);
		 	$(".cartamount").text("$" + totalPrice.toFixed(2));
		 	
		 	// Write new quantity to page
		 	$(".numitems").text(results.updatedquantity);
		 	// Make sure items is plural (or not)
		 	if (results.updatedquantity == 1) $(".shopping").html($(".shopping").html().replace(/ items /," item "));
		 	else $(".shopping").html($(".shopping").html().replace(/ item /," items "));
		 	
		 	// Append message
			$(".shopping .status").remove();
			$("<div class=\"status\" style=\"position: absolute; right: 0; top: 0;\">" +
				"<span class=\"shoppingcart\">" + $(".shopping > .shoppingcart").html() + "</span>" +
				"<div class=\"window\">" +
					"<p class=\"message\"><span>Item added to your cart!</span></p>" +
					"<div class=\"container\">" +
						"<span class=\"name\">" + results.item.name + "</span>" +
						"<span class=\"price\">" + results.item.price + "</span>" +
						"<img src=\"" + results.item.thumbURL + "\" alt=\"New item\" />" +
						"<a class=\"button\" href=\"/shop/cart/\">Checkout</a>" +
					"</div>" +
				"</div>" +
			"</div>").appendTo(".shopping").animate({ opacity: 1 }, 2000, function() {
				$(this).animate({ opacity: 0 }, 1000, function() {
					$(this).remove();	
				});
			});
			
			newText = "Add Another!";		 	
 			
 		}
 		// Display error messages if present
 		else if (results.errors) {
 			for (var i = 0; i < results.errors.length; i++) {
 				alert(results.errors[i].message);
 			}
 		}
		
		// Undo button hold
		$("#product_add").attr("value", newText).removeAttr("disabled");
		
	});		
	
	return true;
	
}

// Size selection
function selectSize(sizeItem) {

	selectedSize = $(sizeItem).attr("id").replace(/size/, "");
	sizeOption = $("#product_size option[value='" +  selectedSize + "']");

	if (sizeOption.length) {
		$("#sizeselector li").removeClass("active");
		$(sizeItem).addClass("active");
		sizeOption.attr("selected", "selected");
	}
	
}

function updateCartDisplay() {
	
	totalPrice = 0;
	totalQuantity = 0;
	
	// Check quantities on each item
 	$("tr.item").each(function(){
 		
 		itemPrice = parseInt($(this).find(".price").text().replace(/\$|\.|\s/g, ""));
 		itemQuantity = parseInt($(this).find(".quantity").attr("value"));
 		itemTotal = itemPrice * itemQuantity;
 		totalPrice += itemTotal;
 		totalQuantity += itemQuantity;
 		
 		// Write item total to page
 		itemTotalNumber = new Number(itemTotal / 100);
 		$(this).find(".totalcolumn strong").text("$" + itemTotalNumber.toFixed(2));
 		
 	});
 
 	// Write total price to page
 	totalPrice = new Number(totalPrice / 100);
 	$(".cartamount").text("$" + totalPrice.toFixed(2));
 	
 	// Write new quantity to page
 	$(".numitems").text(totalQuantity);
	
}