$(document).ready(function() {
	
	var checkFormData = true;

	var serializedStartString = $(':input', $('.shopping-order-cart form')).serialize(); 

	$('.shopping-order-cart form').submit(function() {
		checkFormData = false;
		});
	
	// update order totals for a cart
	$('table.shopping-order-cart').bind('updateTotal', function() {
		var cart = this;
		// get list of each product and its quantity. the id referenced
		// here is the id of its entry in the cart, not the product id
		var products = [];
		$('tr.product', this).each(function() {
			var id = $(this).attr('id').replace(/.*products_(\d+)_row/,"$1");
			products.push(id+':'+$('.cart-product-quantity', this).val());
		});

		$.getJSON(
			URL_CMSROOT+'ajax/ShoppingOrderCartRecalculate',
			{ ajaxType : 'json', quantities : products.join(',') },
			function(data)
			{
				if (data['status'] == 'success') {
					$('.cart-price-total span:first').html(data['subTotalFormatted']);
					$('.cart-price-total input').val(data['subTotal']);

					// remove all existing discount lines
					$('.discount', cart).remove();
					if (data['discounts']) {
						for (var i=0;i<data['discounts'].length;i++) {
							var d = $('.discount-template').clone().removeClass('discount-template').addClass('discount').show();
							$('.cart-discount', d).html(data['discounts'][i]['description']);
							$('.cart-discount-price', d).html(data['discounts'][i]['amountFormatted']);
							d.appendTo($('.discounts', cart));
						}
					}
				} else {
					// if theres an error instruct user to submit form to see update total
					var buttonText = $('.cart-button-update').show().val();
					alert("There was a problem updating your cart total. Please click the button '"
						+buttonText+"' to see the updated total");
				}
			}
		);
			
	});
	
	// Handle quantity changes
	$('.cart-product-quantity').keyup(function() {
		// fetch cart we are working on
		var cart = $(this).closest('.shopping-order-cart');
		// fetch row for this product
		var row = $(this).closest('tr.product');
		// calculate & update price for this product
		var newPrice = $('.cart-product-price', row).val() * $(this).val();
		var currencyCode = $('.cart-currency-code', cart).val();
		$('.cart-price', row).html(newPrice.formatMoney(this, currencyCode));	

		// update cart total
		cart.trigger('updateTotal');
	});

	// Handle removing products
	$('.cart-button-remove').click(function() {
		var cart = $(this).closest('.shopping-order-cart');

		// if this is the last product in the cart we can just submit
		if ($('tr.product', cart).length <= 1) {
			// check to see if there are any items... if there aren't then
			// allow the request to go through and reload the page.
			return true;
		}

		$(this).closest('tr.product').remove();	

		// update cart total
		cart.trigger('updateTotal');
		return false;
	});

	// by default show an update button but if javascript is available we hide it
	$('.cart-button-update').hide();

	window.onbeforeunload = function() {
		if (checkFormData && serializedStartString != $(':input', $('.shopping-order-cart form')).serialize()) {
			return "Your cart has changed. To save your changes please click the 'Continue Shopping' or 'Checkout' button.";
		}
	};

});

