/*
* Developed by Gideon
* gotodiscuss@gmail.com
*/

$(function()
{
    // remove
    $("#cart tr .remove input").click(function() {
        var item = $(this).val();
        $.ajax({
            type: "GET",
            url: "G_cart_action.php",
            data: "remove[]=" + item,
            success: function() {
                $("#cart tr .remove input[value=" + item + "]").parent().parent().fadeOut(500, function() {
                    $(this).remove();
                    calcPrice();
                });
            },
            error: function() {
                window.location("G_cart_action.php?remove[]="+item);
            }
        });
    });

    //	change
    $("#cart tr .quantity input").change(function()
    {
        var item = $(this).attr("name").slice(9, -1);
        var qty  = $(this).val();

        $.ajax({
            type: "GET",
            url: "G_cart_action.php",
            data: "change=change&qty[" + item + "]=" + qty,
            success: function() {
                var startColor = $("#cart tr .quantity input[name*=" + item + "]").parent().parent().hasClass("odd") ? "#eee" : "#fff";
                $("#cart tr .quantity input[name*=" + item + "]").parent().parent().find("td").animate({
                    backgroundColor: "#ff8"
                }, 100).animate({
                    backgroundColor: startColor
                }, 800);
                calcPrice();
            },
            error: function() {
                window.location("G_cart_action.php?qty[" + item + "]=" + qty);
            }
        });
    });
});

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)*1; 
        var extendedPrice = quantity*unitPrice; 
        totalPrice += extendedPrice;
		
        $(".extended_price", this).html("$" + extendedPrice);
        $("#total_price").html("$"+totalPrice);
    });
    if ( totalPrice == 0 ) {
        $("#cart").parent().replaceWith("<p class='center'>You have no items in your cart.</p>");
    }
}
