$(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() {
				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: "#dcdcdc" }, 100).animate({ backgroundColor: startColor }, 800);
				calcPrice();
			},
			error: function() {
				window.location("cart_action.php?quantity[" + orderCode + "]=" + quantity);
			}
		});
	});
});

function calcPrice() {
	var totalPrice = 0;
    var delivery = 0;
    var volDiscount = 0;
	$("#cart tr .quantity").parent().each(function() {
		var quantity = $(".quantity input", this).val();
		var unitPrice = $(".unit_price", this).text().slice(0, -2);
		var extendedPrice = quantity*unitPrice;
        
		totalPrice += extendedPrice;

        if ( totalPrice >= 700) {
            volDiscount = 17.5;
        } else if ( totalPrice >= 500 && totalPrice < 700 ) {
            volDiscount = 15;
        } else if ( totalPrice >= 300 && totalPrice < 500) {
            volDiscount = 12.5;
        } else {
            volDiscount = 0;
        }
        
       

        

        
        
		$(".extended_price", this).html(extendedPrice.toFixed(2)+"лв");
		
	});
    var vipDiscount = $("#vipdiscount").text().slice(1, -1);

     var voldiscountPrice = totalPrice*(volDiscount/100);
    var vipdiscountPrice = totalPrice*(vipDiscount/100);
    totalPrice = totalPrice - voldiscountPrice;
    totalPrice = totalPrice - vipdiscountPrice;


    if(totalPrice > 60) {

        delivery = 0;
    } else {

        delivery = 5;
    }
    
    totalPrice += delivery;

    $("#voldiscount").html("-"+volDiscount+"%");
    $("#voldiscountPrice").html("-"+voldiscountPrice.toFixed(2)+"лв");
    $("#vipdiscountPrice").html("-"+vipdiscountPrice.toFixed(2)+"лв");
    $("#delivery").html(delivery.toFixed(2)+"лв");
    $("#total_price").html(totalPrice.toFixed(2)+"лв");

	if ( totalPrice == 0 ) {
		$("#cart").parent().replaceWith("<p class='center'>Вашата количка е празна.</p>");
	}
}
