$(document).ready(function() {
	// remove item
    $('.remove-item').click(function(e) {
        var quantityField = $(this).parents('tr').find('.quantity')[0],
            quantity = quantityField.value,
            itemId; 

        itemId = quantityField.id.split('_')[1];

        Shopify.removeItem(itemId, function(cart) {
            var row = $(quantityField).parents('tr');
            row.slideUp('slow', function(){
                row.remove();
            });     
            if (!cart.item_count && !document.getElementById('shop_cart').length) {
                Arabica.updateCartHtml();
            }       
            Arabica.updateTotals(cart);
        });     

        return false;
    });

	// Add to basket
	$('.add-to-basket').click(function(e) {
		var quantityField = $(this).parents('form').find('.quantity')[0],
			quantity = quantityField.value,
			itemId = $(this).parents('form').find('.item-id')[0].value;

		Shopify.addItem(itemId, quantity, function(line_item) {
			Shopify.getCart(function(cart) {
				Arabica.updateTotals(cart);
			});

		});
		return false;
	});

	// make sure the basket is always up to date!
	Shopify.getCart(function(cart) {
		Arabica.updateTotals(cart);
	});

	// highlight active directory
	var loc = window.location.href;
	$('#categories > ul > li > a').each(function() {
		if (this.href === loc) {
			this.style.fontWeight = 'bold';
		}
	});
	
});

var Arabica = {
    updateTotals: function(cart) {
        var $itemCountFields = $('.item-count'),
        $totalPriceFields = $('.total-price'),
        itemLabel = cart.item_count === 1 ? 'item' : 'items',
        formattedPrice = Shopify.formatMoney(cart.total_price, '£{{amount}}');
        $itemCountFields.text(cart.item_count + ' ' + itemLabel);
        $totalPriceFields.text(formattedPrice);

		if (cart.item_count) {
			$('#basket input.checkout').css('display', 'block');
		}

    },

    updateCartHtml: function() {
        $('#cart-form').fadeOut('fast', function() {
            $(this).remove();
        });     
        $('#cart-summary').text('You currently have no items in your basket.');
    }
};


