jQuery(function() {
	jQuery("#cart tr .remove input").click(function() {
		var orderCode = jQuery(this).val();
		jQuery.ajax({
			type: "GET",
			url: "cart_action.php",
			data: "remove[]=" + orderCode,
			success: function() {
				jQuery("#cart tr .remove input[value=" + orderCode + "]").parent().parent().parent().fadeOut(500, function() {
					jQuery(this).remove();
					calcPrice();
				});
			},
			error: function() {
				window.location("cart_action.php?remove[]="+orderCode);
			}
		});
	});

	jQuery("#cart tr .quantity input").change(function() {
		var orderCode = jQuery(this).attr("name").slice(9, -1);
		var quantity = jQuery(this).val();
		jQuery.ajax({
			type: "GET",
			url: "cart_action.php",
			data: "quantity[" + orderCode + "]=" + quantity,
			success: function() {
				var startColor = jQuery("#cart tr .quantity input[name*=" + orderCode + "]").parent().parent().hasClass("odd") ? "#eee" : "#fff";
				jQuery("#cart tr .quantity input[name*=" + orderCode + "]").parent().parent().find("td").animate({ backgroundColor: "#ff8" }, 100).animate({ backgroundColor: startColor }, 800);
				calcPrice();
			},
			error: function() {
				window.location("cart_action.php?quantity[" + orderCode + "]=" + quantity);
			}
		});
	});
});

function calcPrice() {
	var totalPrice = 0;
	jQuery("#cart tr .quantity").parent().each(function() {
		var quantity = jQuery(".quantity input", this).val();
		var unitPrice = jQuery(".unit_price", this).text();
		var extendedPrice = quantity*unitPrice;
		totalPrice += extendedPrice;

		jQuery(".extended_price", this).html(extendedPrice);
		jQuery("#total_price").html(totalPrice);
	});
	if ( totalPrice == 0 ) {
		jQuery("#cart").parent().replaceWith("<p class='center'>Ваша корзина пуста.</p>");
	}
}