$(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() {
												  //alert($(this).attr("name"));
		var orderCode = $(this).attr("name").slice(9, -1);
		//alert(orderCode);
		var quantity = $(this).val();
		$.ajax({
			type: "GET",
			url: "cart_action.php",
			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("cart_action.php?quantity[" + orderCode + "]=" + quantity);
			}
		});
	});
});

function calcPrice() {
	var totalPrice = 0;
	$("#cart tr .quantity").parent().each(function() {
		var quantity = $(".quantity input", this).val();
		var unitPrice = $(".unit_price", this).text().slice(1);
		var vatprice = $(".vat_price", this).text();
		//alert(vatprice);
		if( vatprice == '-' ){ var vat_split = 0;  }  else{ var vat_split = vatprice; }
		
		var extendedPrice = quantity*unitPrice;
		var extendedPrice = extendedPrice+parseFloat(vat_split);
		//alert(extendedPrice);
		totalPrice += extendedPrice;
		
		$(".extended_price", this).html("&pound;" + number_format(extendedPrice,'2','.',''));
		$("#total_price").html("&pound;"+number_format(totalPrice,'2','.',''));
	});
	if ( totalPrice == 0 ) {
		$("#cart").parent().replaceWith("<p class='center'>You have no items in your cart. <a class='morelink1' href='../Books.php'>Click here to Shop</a></p>");
	}
}
function number_format( number, decimals, dec_point, thousands_sep ) {

    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}
