// Use for size and color.
var NOVAL = 0xffff;

/**
 * Cart javascript is requested for every page that inherits from base.mako.
 */
function add_to_cart(id, size, color, quantity) {
    $('#cart_status').html('<img src="/pgraphics/ajax-loader.gif"> Updating ' +
                           'cart...');

    var size = size == null ? NOVAL : size;
    var color = color == null ? NOVAL : color;

    var url = '/cart/additem/' + id + '/' + quantity + '/' + size + '/' + color;
    $.getJSON(url, color, cart_updated);
}

function cart_updated(data) {
    if (data.status != "success") {
        alert('Failure updating your cart.\n' + data.value);
        return;
    }

    var cart_status = data.value;
    $('#cart_status').html(cart_status);
    if (cart_status.indexOf('empty') == -1) {
        $('#view_cart').html('<a href="/cart/view">View Cart</a>')
    }
}

/**
 * Update the cart_status element with the status reported from the server.
 */
function update_cart_status() {
    var stat_ok = function(status) {
        $('#cart_status').html(status);

        if (status.indexOf('empty') != -1) {
            $('#view_cart').html('<a href="/cart/view">View Cart</a>')
        }
    }

    var stat_failed = function(XMLHttpRequest, textStatus, errorThrown) {
        if (textStatus != "") {
            alert("Trouble fetching cart information from the server.\n" +
                  textStatus);
        } else {
            alert("Trouble fetching cart information from the server.\n" +
                  errorThrown);
        }
    }

    $.ajax({type: "GET",
            dataType: "json",
            url: "/cart/status",
            success : stat_ok,
            error: stat_failed});
}

function validate_updatecart_form() {
    var invalid = false;
    $(":text").each(function(i) {
        var jo = $(this);
        if (jo.val().search(/^\s*\d+\s*$/) == -1) {
            invalid = true;

            jo.css({background:"yellow"});
            jo.one("focus", function() {
                $(this).css({background:"white"});
            });
        }
        return true;
    });

    if (invalid) {
        alert("Please enter a valid number in the highlighted field(s).");
        return false;
    }
    return true;
}
