$(document).ready(function() {
	
	// 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()+':'+$('.cart-product-payment-option', this).val());
		});
		var gatewayId = $('.cart-gateway-id', cart).val();
		var currencyCode = $('.cart-currency-code', cart).val();
		$.getJSON(
			URL_CMSROOT+'ajax/ShoppingOrderPurchaseBlockRecalculate',
			{ ajaxType : 'json', quantities : products.join(','), gatewayId: gatewayId },
			function(data)
			{
				if (data['status'] == 'success') {
					var total = data['subTotal'];
					$('.cart-price-total span').html(data['subTotalFormatted']);
					$('.cart-price-total input').val(total);

					// fulfilment costs
					var method = $('.cart-fulfilment-method input:checked');
					if (method.val()) {
						// method selected, update total
						var id = method.attr('id').replace('MethodId', 'MethodCost');
						total += parseFloat($('#'+id).val());
						$('.cart-price-grand-total span').html(total.formatMoney(2, currencyCode));
						$('.cart-price-grand-total').show();
					} else {
						// no method selected, hide grand total
						$('.cart-price-grand-total').hide();
					}


					// 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");
				}
			}
		);

			
	}).trigger('updateTotal');

	$('.cart-coupon-code-apply').click(function() {
		var cart = $(this).closest('.shopping-order-cart');
		var couponCode = $('.cart-coupon-code', cart).val();
		$.getJSON(
			URL_CMSROOT+'ajax/ShoppingOrderApplyCouponCode',
			{ ajaxType : 'json', couponCode: couponCode },
			function(data)
			{
				if (data['status'] == 'success') {
					cart.trigger('updateTotal');
				} else {
					alert("Sorry, that doesn't appear to be a valid coupon code");
				}
			}
		);
		return false;
	});
	
	// Handle quantity changes
	$('.cart-product-quantity').change(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');
	});

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

});

