var postageKeys = ['uk_first','uk_recorded','eu_airmail','row_airmail'];
var postage = [];
postage[postageKeys[0]] 	= [2.99, 0.5, 'UK - First class'];
postage[postageKeys[1]] 	= [4.74, 0.5, 'UK - Recorded delivery'];
postage[postageKeys[2]] 	= [4.20, 1, 'Europe - Airmail'];
postage[postageKeys[3]] 	= [5.20, 1.5, 'Worldwide - Airmail'];

var unitPrice 				= 19.99;
var shippingSelection 		= postageKeys[0];

function calculateTotal() {
	var total = calculateUnitTotal() + calculatePostageTotal(shippingSelection);
	return Number(total.toFixed(2));
}

function calculateUnitTotal() {
	var totalUnitPrice = unitPrice * $('quantity').getProperty('value');
	return totalUnitPrice;
}

function calculatePostageTotal(postageKey) {
	
	var basePostagePrice = postage[postageKey][0];
	var additionalPostagePrice = 0;
	
	if($('quantity').getProperty('value') > 0) {
		var additionalPostageUnitPrice = postage[postageKey][1];
		additionalPostagePrice = ($('quantity').getProperty('value') - 1) * additionalPostageUnitPrice;		
	}
	
	var total = Number(basePostagePrice + additionalPostagePrice);
	return total;
}

function updateTotal() {
	$('total').set('html', 'TOTAL: &#163;' + String(calculateTotal()));
}

function updateShipping2() {
	$('shipping2').set('value', postage[shippingSelection][1]);
}

function updatePostageOption() {
	for(var i = 0; i < postageKeys.length; i++) {
		$(postageKeys[i]).set('html', postage[postageKeys[i]][2] + ' (&pound;' + calculatePostageTotal(postageKeys[i]).toFixed(2) + ')');
	}
}

function getShippingSelection() {
	shippingSelection = $('shipping').getSelected().getProperty('id');
}

function updateBasket() {
	getShippingSelection();
	updateTotal();
	updateShipping2();
	updatePostageOption();
}

window.addEvent('domready', function() {
	updateBasket();
    $('quantity').addEvent('change', function() {
    	updateBasket();
    });
    $('shipping').addEvent('change', function() {
    	updateBasket();
    });
});