/*
** COPYRIGHT NETACTIVE Ltd.
** 
** Notes: 	This Script assumes that for each item in the list there are 3 fields to access.
** 		These being - A hidden field storing the cubic metres space of 1 item
				- Input field for the number of pieces of that item
				- Read only field for the total space for that item
		If an item does not have 3 fields then things will go wrong.
*/

function calculate(form){
					
	var unitName = new Array(11);	// The Description for each unit size
	var unitSize = new Array(11);	// The Size of the unit in Cubic metres
	
	var cubicSum = 0;			// The total Space required for storage
	var unitToUse = -1;			// The Unit that is recommended to use
	
	// Dimensions of different unit Sizes available and their space in cubic metres
	// NOTE: These must be listed in Ascending order to work
	unitName[0] = "1.5m x 1.5m";
	unitSize[0] = 6.08;
	unitName[1] = "1.5m x 2m";
	unitSize[1] = 8.1;
	unitName[2] = "1.5m x 2.5m";
	unitSize[2] = 10.13;
	unitName[3] = "1.5m x 3.0m";
	unitSize[3] = 12.15;
	unitName[4] = "1.7m x 3.7m";
	unitSize[4] = 17;
	unitName[5] = "2.4m x 3m";
	unitSize[5] = 19.44;
	unitName[6] = "3m x 3m";
	unitSize[6] = 24.3;
	unitName[7] = "3.5m x 3m";
	unitSize[7] = 28.35;
	unitName[8] = "4m x 3m";
	unitSize[8] = 32.4;
	unitName[9] = "5m x 3m";
	unitSize[9] = 40.5;
	unitName[10] = "6m x 3m";
	unitSize[10] = 48.6;
	
	// Add up all of the space needed from the items selected 
	for (i = 0; i < form.length - 4; i = i+3) {
		var itemSize = parseFloat(form.elements[i].value);
		if (isNaN(itemSize) || form.elements[i].name == "other") break;
		var numItems = parseInt(form.elements[i+1].value);
		if (!isNaN(numItems) && numItems >= 0) {
			form.elements[i+2].value = Math.round(itemSize * numItems * 100)/100;
			cubicSum = cubicSum + (itemSize * numItems);
		}
		else {
			form.elements[i+2].value = "";
		}
	}
	// Add estimated other items
	var otherItems = parseFloat(form.other.value);
	if (!isNaN(otherItems)) cubicSum += otherItems;
	// Set Grand Total text field
	form.grandTotal.value = Math.round(cubicSum*100)/100;
	
	// Work out which is the smallest unit size that fits all the items specified
	for (i = 0; i < unitName.length; i++) {
		if (cubicSum < unitSize[i]) {
			unitToUse = i;
			break;
		}
		if (i == unitName.length-1) {
			unitToUse = i;
		}
	}
	form.unitSize.value = unitName[unitToUse] + " = " + unitSize[unitToUse] + " cubic metres";
}