var moduleBoxes;
var today = new Date();

window.onload = function init() {
	moduleBoxes = document.getElementById('Modules').getElementsByTagName('INPUT');

	for (var i=0; i < moduleBoxes.length; i++) {
		moduleBoxes[i].onclick = updateForm;
	}

	document.applicationForm.discount_sb_subscriber.onclick = updateForm;
	document.applicationForm.discount_esa.onclick = updateForm;
	document.applicationForm.discount_golf.onclick = updateForm;
	document.applicationForm.discount_isrm.onclick = updateForm;

	if(today.getMonth() == 0 && today.getYear() == 106) {
		document.getElementById('discountDisplay').innerHTML = "10%";
	} else {
		document.getElementById('discountDisplay').innerHTML = "None";
	}
}



function updateForm() {
	// Count the modules selected
	j = 0;
	for (var i=0; i < moduleBoxes.length; i++) {
		if(moduleBoxes[i].checked == true) j++;
	}

	//calculate the cost based on selection (0, 1, 2, 3, 4 or other (ie more))
	var moduleCost = 0;
	switch(j) {
		case 0  : moduleCost = 0; break;
		case 1  : moduleCost = 295; break;
		case 2  : moduleCost = 550; break;
		case 3  : moduleCost = 775; break;
		case 4  : moduleCost = 995; break;
		default : moduleCost = 0; alert("You have selected too many course, please deselect some"); break;
	}

	//display that cost...
	document.applicationForm.subtotal.value = moduleCost;

	//Now we need to work out if they get a discount...
	var discount = document.applicationForm.discount_sb_subscriber.checked ||
				   document.applicationForm.discount_esa.checked ||
				   document.applicationForm.discount_golf.checked ||
				   document.applicationForm.discount_isrm.checked;

	//Above discount
	var discountFactor = 1.0;
	if(discount) { discountFactor = 0.9; }

	//Date discount	(0 = January, 1 = Feb, etc)
	if(today.getMonth() == 0 && today.getYear() == 106) { discountFactor -= 0.1; }

	//Now display the discounted price if we need to - otherwise, disable the box
	var TotalWithDiscount = moduleCost * discountFactor;
	document.applicationForm.total.value = TotalWithDiscount.toFixed(2);


	//Change the label percentage...
	if((today.getMonth() == 0 && today.getYear() == 106) && (discount)) {
		document.getElementById('discountDisplay').innerHTML = "20%";
	} else if((today.getMonth() == 0 && today.getYear() == 106) || (discount)) {
		document.getElementById('discountDisplay').innerHTML = "10%";
	} else {
		document.getElementById('discountDisplay').innerHTML = "None";
	}



	//Now, finally, we can do VAT
	var TotalWithVAT = moduleCost * discountFactor * 1.175;
	document.applicationForm.totalvat.value = TotalWithVAT.toFixed(2);
}
