storebar = {};
storebar.id = '#store-bar';
storebar.cartUrl = '/shop/cart/';

storebar.submitForm = function(form, callback) {
    $.ajax({
        type: "POST",
        url: form.attr('action'),
        data: form.serialize(),
        cache: false,
        success: function(data){
            if(callback) {
                callback();
            }
        }
    });
}

storebar.refresh = function() {
    $.ajax({
        url: '/',
        type: 'GET',
        cache: false,
        success: function(data) {
            // reload the page if it's already on the cart
            if(window.location.pathname == storebar.cartUrl) {
                window.location.reload();
                return;
            }

            // on every other page dynamically update the bar
            var content = $(data).find(storebar.id).html();
            $(storebar.id).html(content);
        }
    });
}

$(document).ready(function() {
    // dynamically remove items from cart
    $('.cartitem-remove').live('click', function(event) {
        event.preventDefault();
        form = $(this).parents('form');
        storebar.submitForm(form, storebar.refresh);
    });

    // override addcart submit buttons to ajax load
    $('input[name="addcart"]').click(function(event) {
        event.preventDefault();
        form = $(this).parents('form');
        storebar.submitForm(form, storebar.refresh);
    });
});

