var Rules = {};
Event.observe(window, "load", initRules, false);
function initRules() {EventSelectors.start(Rules);};

var cartonSize = 6;
var discountVolume = 6;
var shippingStandard = 1000;
var shippingDiscounted = 800;
var shippingDiscountVolume = 2;

var shipping = {
	inside:{
		pricing: [
			[1, 800],
			[6, 1000],
			[12, 1200]
		],
		unitDiscount:200
	},
	outside:{
		pricing: [
			[1, 800],
			[6, 1200],
			[12, 1600]
		],
		unitDiscount:200
	}
};

var products = {
	product_semillon_06:	{single:1870, 	discount:11220, cartonModifier:1},
	product_shiraz_01:	{single:2640, 	discount:15840, cartonModifier:1},
	product_shiraz_02:	{single:3080, 	discount:18480, cartonModifier:1},
	product_shiraz_03:	{single:3080, 	discount:18480, cartonModifier:1},
	product_shiraz_04:	{single:3080, 	discount:18480, cartonModifier:1},
	product_shiraz_05:	{single:3800, 	discount:22800, cartonModifier:1},
	product_rose:		{single:1650, 	discount:9900,  cartonModifier:1},
	product_mix:		{single:12320, discount:null,	 cartonModifier:6}
};

var totals = {
	bottles:null,
	sub:null,
	shipping:null,
	final:null
};

var destination;

var quantites = $A();
Rules['#content .wine input:keyup, #shipping_destination:change'] = function() {updateTotals();};
Rules['#content:loaded'] = function() {
	totals.bottles 		= $('bottlesTotal');
	totals.sub 			= $('subTotal');
	totals.shipping 	= $('shippingTotal');
	totals.final 		= $('finalTotal');
	destination 		= $('shipping_destination');
	var inputs = $$('#content .wine input');
	inputs.each(function(input) {
		quantites.push({id:input.id, node:input, total:$(input.id + '_total')});
	});
	updateTotals();
};

function updateTotals() {
	var totalBottles 	= 0;
	var subTotal 		= 0;
	var shippingTotal	= 0;
	var final			= 0;
	var unitTotal		= 0;
	// Does not account for dozens at the moment.
	quantites.each(function(quantity) {
		var productVolume = parseInt($F(quantity.node));
		if (isNaN(productVolume)) {productVolume = 0};
		// Check for volume discount 
		if (discountVolume != 0 && productVolume >= discountVolume && quantity.discount != null) {
			var r = productVolume % discountVolume;
			unitTotal =  r * products[quantity.id].single;
			unitTotal += ((productVolume - r) / discountVolume) * products[quantity.id].discount;
		}
		else {
			unitTotal = productVolume * products[quantity.id].single;
		};
		totalBottles 		+= productVolume * products[quantity.id].cartonModifier;
		var bottleTotal 	=  unitTotal;
		subTotal 			+= bottleTotal;
		quantity.total.innerHTML = formatCurrency(bottleTotal);
	});
	// Update cartons
	var remainder = totalBottles % cartonSize;
	cartons = (totalBottles - remainder) / cartonSize;
	if (remainder != 0) {
		cartons += 1;
	};
	var cartonsTag = ' carton';
	if (cartons > 1) {cartonsTag = ' cartons'};
	totals.bottles.innerHTML 	= totalBottles + ' <span>(' + cartons + cartonsTag + ')</span>';
	// Find the relevant shipping price
	var dest = shipping[$F(destination)];
	for (var i = 0; i < dest.pricing.length; i++) { // WHY NO EACH_INDEX ITERATOR!!!???		
		var price = dest.pricing[i][1];
		var volume = dest.pricing[i][0];
		var nextIsValid = false;
		if (dest.pricing[i + 1]) {
			var nextVolume = dest.pricing[i + 1][0];
		}
		else {
			var nextVolume = 0;
		}		
		// See if this is the last entry in the array
		if (totalBottles < nextVolume || dest.pricing.length == (i + 1)) {
			if (volume == 1) {
				var remainingUnits = totalBottles - 1;
			}
			else {
				var remainingUnits = totalBottles % volume;
			}
			shippingTotal = ((totalBottles - remainingUnits) / volume) * price
			// Do we discount the remaining bottles or charge case price?
			if (remainingUnits > 0) {
				if (dest.unitDiscount) {
					shippingTotal += remainingUnits * dest.unitDiscount
				}
				else {
					shippingTotal += price
				};
			};
			break;
		};
	};
	totals.shipping.innerHTML	= formatCurrency(shippingTotal);
	// The easy stuff
	totals.sub.innerHTML 		= formatCurrency(subTotal);
	totals.final.innerHTML		= formatCurrency(subTotal + shippingTotal);
	
	//update some hidden inputs too - so they can be submitted with the form:
	document.getElementById('totalsProductPrice').value 	= formatCurrency(subTotal);
	document.getElementById('totalsShippingPrice').value	= formatCurrency(shippingTotal);
	document.getElementById('totalsGrandTotal').value		= formatCurrency(subTotal + shippingTotal);
	
};

function formatCurrency(amount) {
	var i = parseFloat(amount / 100);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return '$' + s;
};