var ns4 = (document.layers)? true:false
var ie4 = (document.all)? true:false

function btCalc_onclick() {
	var errors = '';
	if (is_empty(document.Calc.txtToWork.value)) {
		errors += ' - How many miles do you drive to and from work each day?\n';
	}
	if (is_empty(document.Calc.txtWorkDays.value)) {
		errors += ' - How many days per month do you work?\n';
	}
	if (is_empty(document.Calc.txtMilesGallon.value)) {
		errors += ' - How many miles per gallon does your car, truck or SUV average?\n';
	}
	if (is_empty(document.Calc.txtFuelCost.value)) {
		errors += ' - How much does a gallon of fuel cost?\n';
	}
	if (errors != '') {
		errors = 'The following fields are required:\n' + errors;
		alert(errors);
	} else {
		calc();
	}
}

function init() {
		document.onkeydown = pressKey
		if (ns4) document.captureEvents(Event.KEYDOWN)
}

function pressKey(e) {
		if (ns4) {var nKey=e.which; var ieKey=0}
		if (ie4) {var ieKey=event.keyCode; var nKey=0}
		if (nKey==13 || ieKey==13) {   // if "Enter" key is pressed
				document.Calc.btCalc.click();
		}
}

function checkNum(obj)  {
	var str = obj.value;
	var re = /^\d{0,5}\.?\d{0,3}$/;
	//var re2 = /[0-9]/g;
	if (! re.test(str)) {
		alert('Invalid value entered.  Please enter a number.');
		obj.select();
		return false;
	}
	else
		return true;
}

function calc() {

		var A = parseFloat(document.Calc.txtToWork.value);
		var B = parseFloat(document.Calc.txtWorkDays.value);
		var C = parseFloat(document.Calc.txtMilesGallon.value);
		var D = parseFloat(document.Calc.txtFuelCost.value);
		var E = parseFloat(document.Calc.txtParking.value);
		var F = parseFloat(document.Calc.txtMaint.value);
		if (is_empty(document.Calc.txtParking.value)) {
			E = 0;
		}
		if (is_empty(document.Calc.txtMaint.value)) {
			F = 0;
		}
		var monthlyCost = 0;
		var annualCost = 0;

		if (A <= 0) {
			alert('Please enter a positive value for Miles to work.');
			document.Calc.txtToWork.select();
			return false;
		}

		if (C <= 0) {
			alert('Please enter a positive value for Miles per gallon.');
			document.Calc.txtMilesGallon.select();
			return false;
		}

		monthlyCost = Math.round((((D / C) + F) * A * B + E) * 100) / 100;
		annualCost = Math.round((monthlyCost * 12) * 100) / 100;

		monthlyCost = monthlyCost.toString();
		annualCost = annualCost.toString();

		if (monthlyCost.length - (monthlyCost.indexOf('.') + 1) < 2)
			monthlyCost += '0';
		if (annualCost.length - (annualCost.indexOf('.') + 1) < 2)
			annualCost += '0';

		document.Calc.txtMonthly.value = monthlyCost;
		document.Calc.txtAnnual.value = annualCost;

}