$(function() {
	$("#cart tr .remove input").click(function() {
		var orderCode = $(this).val();
		$.ajax({
			type: "GET",
			url: "cart_action.php",
			data: "remove[]=" + orderCode,
			success: function() {
				$("#cart tr .remove input[value=" + orderCode + "]").parent().parent().fadeOut(500, function() {
					$(this).remove();
					calcPrice();
				});
			},
			error: function() {
				window.location("cart_action.php?remove[]="+orderCode);
			}
		});
	});
	
	$("#cart tr .quantity input").change(function() {
		var orderCode = $(this).attr("name").slice(9, -1);
		var quantity = $(this).val();
		$.ajax({
			type: "GET",
			url: "cart_action.php",
			data: "quantity[" + orderCode + "]=" + quantity,
			success: function() {
				calcPrice();
			},
			error: function() {
				window.location("cart_action.php?quantity[" + orderCode + "]=" + quantity);
			}
		});
	});
});

function calcPrice() {
	var totalPrice = 0;
	var totalTax = 0;
	var totalPriceExcTax = 0;
	$("#cart tr .quantity").parent().each(function() {
		var quantity = $(".quantity input", this).val();
		var unitPrice = $(".unit_price", this).text().slice(0);
		var unitTax = $(".unit_tax", this).text().slice(0);
		var unitPriceExcTax = $(".unit_price_exc_tax", this).text().slice(0);

		var extendedPrice = quantity*unitPrice;
		var extendedTax = quantity*unitTax;
		var extendedPriceExcTax = quantity*unitPriceExcTax;
			
		totalPrice += extendedPrice;
		totalTax += extendedTax;
		totalPriceExcTax += extendedPriceExcTax;
		
		$(".extended_price", this).html(extendedPrice.toFixed(2));
		$(".extended_price_exc_tax", this).html(extendedPriceExcTax.toFixed(2));
		$("#total_price").html(totalPrice.toFixed(2));
		$("#total_tax").html(totalTax.toFixed(2));
		$("#total_price_exc_tax").html(totalPriceExcTax.toFixed(2));
	});
	if ( totalPrice == 0 ) {
		$("#container_cart_table").replaceWith("<strong class=error>Sepetinizde ürün kalmadi.</strong>");
	}
}