/*
Used for the spreadsheet like functionality of SSA's size
calculator.

*/

// Clear any data from the form
// document.forms.calc.resetButton.click();

// Define array used to update grand total quickly
grandTotal = new Array();

// Define an error variable so that we know weather or 
// not to skip forward on tab
err = false;

// initialise the values in the array
for (grandIndex = 0; grandIndex < 150; grandIndex++)
{
	grandTotal[grandIndex] = 0;
}

function update(name)
{
	sizeField = "s_" + name;
	size = eval("document.forms.calc." + sizeField + ".value");
	
	qtyField = "q_" + name;
	qty = eval("document.forms.calc." + qtyField + ".value");
	
	countField = "c_" + name;
	count = eval("document.forms.calc." + countField + ".value");

	totalField = "t_" + name;
	
	// Check up on the qty field to check that it is a number
	if (!isInteger(qty))
	{
		alert ("You must enter a number for the quantity");
		eval("document.forms.calc." + totalField + ".value = 0");
		err = true;
	}
	else
	{
		totalSize = qty * size;
		grandTotal[count] = totalSize;
		
		totalSize = roundOff(totalSize);
		
		eval("document.forms.calc." + totalField + ".value = " + totalSize);
		
		updateGrandTotal();
	}
}


function updateGrandTotal()
{
	total = 0;

	for (i = 0; i < grandTotal.length; i++)
	{
		total += grandTotal[i];
	}
	
	total = roundOff(total);
	document.forms.calc.total.value = total;

}


function getIndex(input)
{
	var index = -1, i = 0, found = false;
	while (i < input.form.length && index == -1)
	{
		if (input.form[i] == input)
		{
			index = i;
		}
		else
		{
			i++;
		}
	}
	return index;
}


function nextFocus(element)
{
	name = element.name;
	name = name.substr(2, name.length);
	
	count = eval("document.forms.calc.c_" + name + ".value");
	
	if (!err)
	{
		count++;
	}
	else
	{
		err = false;
	}

	fieldName = eval("document.forms.calc.a_" + count + ".value");
	eval("document.forms.calc.q_" + fieldName + ".focus()");
}


function resetAll()
{
	for (i = 0; i < grandTotal.length; i++)
	{
		grandTotal[i] = 0;
	}
	
	document.forms.calc.reset();
}

//-------------------------------------------------------------------
// isInteger(value)
//   Returns true if value contains all digits
//-------------------------------------------------------------------
function isInteger(val) {
	for (var i=0; i < val.length; i++) {
		if (!isDigit(val.charAt(i))) { return false; }
		}
	return true;
	}

//-------------------------------------------------------------------
// isDigit(value)
//   Returns true if value is a 1-character digit
//-------------------------------------------------------------------
function isDigit(num) {
	var string="1234567890";
	if (string.indexOf(num) != -1) {
		return true;
		}
	return false;
	}


function roundOff(value)
{
 	return Math.round(value*100)/100 
}
