if (typeof P4 == 'undefined')
	var P4 = {};
// define P4 so we can later include P4.Util

var ShoppingCart =
{
	init: function()
	{
		$$('input.remove-button').each(function(checkbox)
		{
			Event.observe(checkbox, "click", this.recalculate.bind(this), true);
			Event.observe(checkbox, "change", this.recalculate.bind(this), true);
		}.bind(this));
		$$('input.quantityInput').each(function(checkbox)
		{
			Event.observe(checkbox, "keyup", this.recalculate.bind(this), true);
			Event.observe(checkbox, "change", this.recalculate.bind(this), true);
		}.bind(this));
		this.orderTotalElement = $$('.order-total-row .total-column')[0];
		this.shippingElement = $$('.shopping-cart tr.shipping-fee-row .total-column')[0];
		var orderTotal = this.orderTotalElement.innerHTML;
		this.fractionSeparator = P4.Util.getFractionSeparator(orderTotal);
		this.currencySymbol = P4.Util.getCurrencySymbol(orderTotal);
		var getFee = function(type)
		{
			var elements = $$('.shopping-cart tr.' + type + '-row .total-column');
			if (elements && elements.length > 0)
				return P4.Util.parseCurrency(elements[0].innerHTML);
			else
				return 0;
		};
		this.handlingFee = getFee('handling-fee');
		this.couponDiscount = getFee('coupon');
		this.promoDiscount = getFee('promo');
		this.recalculate();
	},

	recalculate: function()
	{
		var shipping = this.baseShipping;
		var orderTotal = this.handlingFee + this.couponDiscount + this.promoDiscount;
		$$('.shopping-cart tbody tr.item-row').each(function(row, index)
		{
			var quantityElement = row.select('.quantityInput')[0];
			var removeElement = row.getElementsByClassName('.remove-button')[0];
			var quantity = quantityElement.value;
			if (!isNaN(quantity))
			{
				var priceElement = row.select('.price-column')[0];
				var price = P4.Util.parseCurrency(priceElement.innerHTML);
				if (quantity < 0)
					quantity = 0;
				var total = Math.floor(quantity) * price;
				if (removeElement && removeElement.checked)
					total = 0;
				row.select('.total-column')[0].innerHTML =
				P4.Util.formatNumber(total, 2, this.fractionSeparator, this.currencySymbol);
				orderTotal += total;
				shipping += Math.floor(quantity) * this.shipping[index];
			}
		}.bind(this));
		orderTotal += shipping;
		this.orderTotalElement.innerHTML = P4.Util.formatNumber(orderTotal, 2, this.fractionSeparator, this.currencySymbol);
		this.shippingElement.innerHTML = P4.Util.formatNumber(shipping, 2, this.fractionSeparator, this.currencySymbol);
		this.innerHTML = P4.Util.formatNumber(orderTotal, 2, this.fractionSeparator, this.currencySymbol);
	}
};