var weightelements


//-------------------------------------------------------
// Returns an array containing all the elements of the weight block in sequential order.
function weightArray(form) {

	// The order in which the array elements are listed is crucial.
	return new Array(form.kg, form.g, form.oz, form.lb)
}


//-------------------------------------------------------
//  initialize the array of form data
function init(form) {
	weightelements = weightArray(form)
}


//-------------------------------------------------------
// This is the first field in which the data was entered.
function getInputField() {
	for (var i = 0; i < weightelements.length; i++)
		if (weightelements[i].value != "")
			return i
}


//-------------------------------------------------------
//  the first field's value
function getInputValue() {
	for (var i = 0; i < weightelements.length; i++){
		if (!isNaN(weightelements[i].value)) {
			if (weightelements[i].value != "")
				return weightelements[i].value
		} else {
			return false
		}
	}
}


//-------------------------------------------------------
// Rounds a value to a specified number of decimal places and returns it.
function roundDec(val, dig) {

	// If no value is specified for number of significant digits
	// then set a predetermined value
	if (dig == "" || dig == undefined || dig == null)
		dig = 10

	var div = Math.pow(10, dig)
	return (Math.round(val * div) / div)
}


//-------------------------------------------------------
function convertWeight(form) {
	var inputField = getInputField()
	var inputValue = getInputValue()

	// Convert all values to Newtons.
	// (Later, they will be converted to other units
	switch(inputField) {
		case 0: // Kilograms
			n = 9.8 * inputValue;
			break;

		case 1: // Grams
			n = (9.8 / 1000) * inputValue;
			break;

		case 2: // Ounces
			n = (9.8 / (16 * 2.20462262184878)) * inputValue;
			break;

		case 3: // Pounds
			n = (9.8 / 2.20462262184878) * inputValue;
			break;

		default: // If this hits, an error has occurred.
			return false;
			break;
	}

	// Convert to other units of measurement
	var kg = n / 9.8
	var g  = (1000 / 9.8) * n
	var oz = ((16 * 2.20462262184878) / 9.8) * n
	var lb = (2.20462262184878 / 9.8) * n

	// Display values in form boxes
	form.kg.value = roundDec(kg,3)
	form.g.value  = roundDec(g,3)
	form.oz.value = roundDec(oz,3)
	form.lb.value = roundDec(lb,3)
}

