
function goConvert() {
	fromType = document.getElementById('fromType');
	fromTypeId = fromType.value;
	fromTypeName = fromType.options[fromType.selectedIndex].text;

	toType = document.getElementById('toType');
	toTypeId = toType.value;
	toTypeName = toType.options[toType.selectedIndex].text;

	value = document.getElementById('conversionInput').value;

	var result = '';
	
	result = convertTorque(toTypeId, toTypeName, fromTypeId, fromTypeName, value);

	
	document.getElementById('conversionResult').value = result;
}

function convert(constant, toTypeId, toTypeName, fromTypeId, fromTypeName, value) {
	value = parseFloat(value);

	if (isNaN(value)) {
		value = 1;
	}

	var result = value * (constant[fromTypeId] / constant[toTypeId]);
	result = Math.round(result * 100) / 100;
	result = commaFormat(result);

	return (value + " " + fromTypeName + " = " + result + " " + toTypeName);
}

function convertReverse(constant, toTypeId, toTypeName, fromTypeId, fromTypeName, value) {
	value = parseFloat(value);

	if (isNaN(value)) {
		value = 1;
	}

	var result = value * (constant[toTypeId] / constant[fromTypeId]);
	result = Math.round(result * 100) / 100;
	result = commaFormat(result);

	return (value + " " + fromTypeName + " = " + result + " " + toTypeName);
}

function commaFormat(num) {
	var n = Math.floor(num);
	var myNum = num + "";
	var myDec = ""

	if (myNum.indexOf('.',0) > -1){
		myDec = myNum.substring(myNum.indexOf('.',0),myNum.length);
	}

	var arr = new Array('0')
	var i = 0; 

	while (n > 0) {
		arr[i] = '' + n % 1000;
		n = Math.floor( n / 1000);
		i++;
	}

	arr = arr.reverse();
	for (var i in arr) {
		if (i > 0) {
		 	//padding zeros
			while (arr[i].length < 3) {
				arr[i] = '0' + arr[i];
			}
		}
	}

	return arr.join() + myDec;
}

function convertTorque(toTypeId, toTypeName, fromTypeId, fromTypeName, value) {
	var constants = new Array(1, 1/14.22, 1/1, 1/1, 1/1);
	return convert(constants, toTypeId, toTypeName, fromTypeId, fromTypeName, value);
}
