$(document).ready(function() {
    cartRefresh();
});

function cartKey(evt, el, product_id) {
    var e = evt || window.event;
    var code;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;

    if (code == 13) {
        cartUpdate(product_id, el.value);
        el.blur();
    }
}

function cartUpdate(product_id, amount) {
    $.getJSON('cart', { action: 'set', id: product_id, count: amount }, function(ret) {
        if (ret.error == true) return;

        if ($('#count'+product_id).length) $('#count'+product_id).val(ret.count);
        if ($('#unit_price'+product_id).length) $('#unit_price'+product_id).html(ret.unit_price);
        if ($('#total'+product_id).length) $('#total'+product_id).html(ret.total);
        if ($('#stock'+product_id).length) $('#stock'+product_id).attr('src', ret.stock);

        cartRefresh();
    });
}

function cartAdd(product_id, amount) {
    $.getJSON('cart', { action: 'add', id: product_id, count: amount }, function(ret) {
        if (ret.error == true) return;

        if ($('#count'+product_id).length) $('#count'+product_id).val(ret.count);
        if ($('#unit_price'+product_id).length) $('#unit_price'+product_id).html(ret.unit_price);
        if ($('#total'+product_id).length) $('#total'+product_id).html(ret.total);
        if ($('#stock'+product_id).length) $('#stock'+product_id).attr('src', ret.stock);
        
        cartRefresh();
    });
}

function cartRemove(product_id, amount) {
    $.getJSON('cart', { action: 'remove', id: product_id, count: amount }, function(ret) {
        if (ret.error == true) return;

        if ($('#count'+product_id).length) $('#count'+product_id).val(ret.count);
        if ($('#unit_price'+product_id).length) $('#unit_price'+product_id).html(ret.unit_price);
        if ($('#total'+product_id).length) $('#total'+product_id).html(ret.total);
        if ($('#stock'+product_id).length) $('#stock'+product_id).attr('src', ret.stock);

        cartRefresh();
    });
}

function cartDelete(product_id, amount) {
    cartRemove(product_id, amount);
    document.location.reload();
}

function cartClear()
{
    $.getJSON('cart', { action: 'clear' }, function(ret) {
        if (ret.error == true) return;
        document.location.reload();
    });
}

function cartRefresh() {
    $.getJSON('cart', { action: 'info' }, function(ret) {
        $('#cart_product_count').html(ret.products);
        $('#cart_price').html(ret.price);
        $('#cart_price_novat').html(ret.price_novat);
        if(ret.products == 1) {
            $('#cart_many').css('display', 'none');
        } else {
            $('#cart_many').css('display', 'inline');
        }
    });
}

