jQuery(function($) {
	$(document).ready(function () {
		$("#cart tr .remove input").click(function() {
			var orderCode = $(this).val();
			$.ajax({
				type: "GET",
				url: "/shopping-cart-action/",
				data: "remove[]=" + orderCode,
				success: function() {
					$("#cart tr .remove input[value=" + orderCode + "]").parent().parent().fadeOut(500, function() {
						$(this).remove();
						calcPrice();
					});
				},
				error: function() {
					window.location("/shopping-cart-action/?remove[]="+orderCode);
				}
			});
		});
		
		// deprecated: quantity is always 1.
		$("#cart tr .quantity input").change(function() {
			var orderCode = $(this).attr("name").slice(9, -1);
			var quantity = $(this).val();
			$.ajax({
				type: "GET",
				url: "shopping-cart-action",
				data: "quantity[" + orderCode + "]=" + quantity,
				success: function() {
					var startColor = $("#cart tr .quantity input[name*=" + orderCode + "]").parent().parent().hasClass("odd") ? "#eee" : "#fff";
					$("#cart tr .quantity input[name*=" + orderCode + "]").parent().parent().find("td").animate({ backgroundColor: "#ff8" }, 100).animate({ backgroundColor: startColor }, 800);
					calcPrice();
				},
				error: function() {
					window.location("shopping-cart-action?quantity[" + orderCode + "]=" + quantity);
				}
			});
		});
		
		// closes the shopping cart when submitting the cart content's to paypal.
		$("#checkout").submit(function() {
			parent.tb_remove();
		});
		
		if('function' === typeof(parent.updateCatalogPrice)) {
			parent.updateCatalogPrice($('#total_price').html());
		}
	});
	
	function calcPrice() {
		var totalPrice = 0;
		$("#cart tr .quantity").parent().each(function() {
			var quantity = parseFloat($(".quantity input", this).val());
			var unitPrice = parseFloat($(".unit_price input", this).val());
			var extendedPrice = quantity*unitPrice;
			totalPrice += extendedPrice;
			
			$(".extended_price", this).html("$" + extendedPrice);
			$("#total_price").html("$"+ (Math.round(totalPrice*100) / 100) );
		});
		if ( totalPrice == 0 ) {
			$("#cart").parent().replaceWith("<p class='center'>You have no items in your cart.</p>");
		}
		
		if('function' === typeof(parent.updateCatalogPrice)) {
			parent.updateCatalogPrice($("#total_price").html());
		}
	}
});