// ------------------------------------------------------------------------------------
// File Name:	commuter_calc.js
//
// Written By:	Jonathan Opie, Parking Services
//				5-31-2007
//
// Purpose:		Used by page /parking/commuterchoice/savings_calculator.html
//				to calculate cost savings by choosing to use various
//				availible alternative transportation options.
//				Accuracy based on AAA 2007 published averages and UCDHS
//				parking permit costs and commuterchoice subsidies as of
//				5-31-07.
// ------------------------------------------------------------------------------------



// ----------------------------------------------------------------
// FUNCTION validate_fields()
// Main function, called with each change to update savings info
// ----------------------------------------------------------------
function update_numbers() {
	isValid = validate_fields();
	if (isValid == true) {
 		display_savings();
	} else {
		display_error(isValid);
	}
}

// ----------------------------------------------------------------
// FUNCTION validate_fields()
// Pre-validate values entered into the availible input fields
// ----------------------------------------------------------------
function validate_fields() {
	num = document.getElementById("daysMo").value.toString().replace(/[^0-9|\.]/g,'');
	if(isNaN(num)) {
		return "Commute days per month = " + num;
	}

	num = document.getElementById("milesEa").value.toString().replace(/[^0-9|\.]/g,'');
	if(isNaN(num)) {
		return "Miles each way to work = " + num;
	}

	num = document.getElementById("carMaint").value.toString().replace(/[^0-9|\.]/g,'');
	if(isNaN(num)) {
		return "Maintenance costs (per mile) = " + num;
	}

	num = document.getElementById("carMPG").value.toString().replace(/[^0-9|\.]/g,'');
	if(isNaN(num)) {
		return "M.P.G. Average miles per gallon = " + num;
	}

	num = document.getElementById("gasCost").value.toString().replace(/[^0-9|\.]/g,'');
	if(isNaN(num)) {
		return "Gas, cost per gallon = " + num;
	} else {
		return true;
	}

}

// ----------------------------------------------------------------
// FUNCTION display_instructions()
// Display instructions as HTML
// ----------------------------------------------------------------
function display_instructions() {
	savings_est  = "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
	savings_est += "  <tbody>";
	savings_est += "	<tr>";
	savings_est += "		<td colspan=\"3\" valign=\"top\"><br><font color=\"#D9C266\"><i>Click the \"Calculate\" button above to calculate your estimated savings.</i></font></td>";
	savings_est += "	</tr>";
	savings_est += "  </tbody>";
	savings_est += "</table>";
	document.getElementById("savings").innerHTML = savings_est;
}

// ----------------------------------------------------------------
// FUNCTION display_savings()
// Calculate and display savings information for each permit type
// ----------------------------------------------------------------
function display_savings() {
	permitCost = 36;
	ridersNow = 1;
	switch (document.getElementById('currentPermit').value) {
		case "B Permit":
			permitCost = 36;
			ridersNow = 1;
			break;
		case "C Permit":
			permitCost = 34;
			ridersNow = 1;
			break;
		case "D Permit":
			permitCost = 79;
			ridersNow = 1;
			break;
		case "2 Person Carpool Permit":
			permitCost = 18;
			ridersNow = 2;
			break;
		case "3 Person Carpool Permit":
			permitCost = 10;
			ridersNow = 3;
			break;
		case "4 Person Carpool Permit":
			permitCost = 10;
			ridersNow = 4;
			break;
		case "Motorcycle Permit":
			permitCost = 15;
			ridersNow = 1;
			break;
	}

	total_yearly_miles = get_value("milesEa") * get_value("daysMo") * 2 * 12;
	total_yearly_trans_cost = ((total_yearly_miles * ((get_value("gasCost") / get_value("carMPG")) + get_value("carMaint")))) / ridersNow;
	total_yearly_permit_cost = permitCost * 12;
	total_current_cost_yearly = total_yearly_trans_cost + total_yearly_permit_cost;
	total_current_cost_monthly = total_current_cost_yearly / 12;

		savings_est  = "";
		savings_est += "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
		savings_est += "  <tbody>";

	if (document.getElementById('currentPermit').value != "2 Person Carpool Permit") {
		new_yearly_trans_cost = ((total_yearly_miles * ((get_value("gasCost") / get_value("carMPG")) + get_value("carMaint")))) / 2;
		new_yearly_permit_cost = 18 * 12;
		new_current_cost_yearly = new_yearly_trans_cost + new_yearly_permit_cost;
		savings_est += insert_option(total_current_cost_yearly, new_current_cost_yearly, "Switch to a <a href=\"/parking/parking/employee.html#carpool\"><font color=\"#002666\"><b>2 Person Carpool</b></font></a> from a " + document.getElementById('currentPermit').value + " . . .","");
	}

	if (document.getElementById('currentPermit').value != "3 Person Carpool Permit") {
		new_yearly_trans_cost = ((total_yearly_miles * ((get_value("gasCost") / get_value("carMPG")) + get_value("carMaint")))) / 3;
		new_yearly_permit_cost = 10 * 12;
		new_current_cost_yearly = new_yearly_trans_cost + new_yearly_permit_cost;
		savings_est += insert_option(total_current_cost_yearly, new_current_cost_yearly, "Switch to a <a href=\"/parking/parking/employee.html#carpool\"><font color=\"#002666\"><b>3 Person Carpool</b></font></a> from a " + document.getElementById('currentPermit').value + " . . .","");
	}

	if (document.getElementById('currentPermit').value != "4 Person Carpool Permit") {
		new_yearly_trans_cost = ((total_yearly_miles * ((get_value("gasCost") / get_value("carMPG")) + get_value("carMaint")))) / 4;
		new_yearly_permit_cost = 10 * 12;
		new_current_cost_yearly = new_yearly_trans_cost + new_yearly_permit_cost;
		savings_est += insert_option(total_current_cost_yearly, new_current_cost_yearly, "Switch to a <a href=\"/parking/parking/employee.html#carpool\"><font color=\"#002666\"><b>4 Person Carpool</b></font></a> from a " + document.getElementById('currentPermit').value + " . . .","");
	}

	if (document.getElementById('currentPermit').value != "UCD/UCDHS Shuttle") {
		new_yearly_trans_cost = 30 * 12;
		new_yearly_permit_cost = 0;
		new_current_cost_yearly = new_yearly_trans_cost + new_yearly_permit_cost;
		savings_est += insert_option(total_current_cost_yearly, new_current_cost_yearly, "Use the <a href=\"/parking/commuterchoice/alt_trans.html#shuttle\"><font color=\"#002666\"><b>UCD/UCDHS Shuttle</b></font></a> instead of a " + document.getElementById('currentPermit').value + " . . .","*");
	}

	if (document.getElementById('currentPermit').value != "RT Bus/Lightrail") {
		new_yearly_trans_cost = 40 * 12;
		new_yearly_permit_cost = 0;
		new_current_cost_yearly = new_yearly_trans_cost + new_yearly_permit_cost;
		savings_est += insert_option(total_current_cost_yearly, new_current_cost_yearly, "Travel by <a href=\"/parking/commuterchoice/alt_trans.html#transit\"><font color=\"#002666\"><b>RT Bus/Lightrail</b></font></a> instead of a " + document.getElementById('currentPermit').value + " . . .","*");
	}
		savings_est += "  </tbody>";
		savings_est += "</table>";

	document.getElementById("savings").innerHTML = savings_est;

}

// ----------------------------------------------------------------
// FUNCTION insert_option()
// Return yearly and monthly savings formatted as HTML
// ----------------------------------------------------------------
function insert_option(currentYearlyCost, newYearlyCost, optionTitle, disclaimerMark) {
		if (currentYearlyCost - newYearlyCost >= 0) {
			savingsText = " Savings";
		} else {
			savingsText = "<font color=\"#660000\"> Increase</font>";
		}
		return_val  = "	<tr>";
		return_val += "		<td colspan=\"5\" valign=\"top\"><br><font color=\"#002666\">" + optionTitle + "</font></td>";
		return_val += "	</tr>";
		return_val += "	<tr>";
		return_val += "		<td><img height=\"1\" src=\"/parking/map/images/XXXXXX.gif\" width=\"20\"></td>";
		return_val += "		<td valign=\"top\" align=\"right\"><nobr>" + formatCurrency(currentYearlyCost - newYearlyCost) + "</nobr></td>";
		return_val += "		<td><img height=\"1\" src=\"/parking/map/images/XXXXXX.gif\" width=\"10\"></td>";
		return_val += "		<td valign=\"top\"><nobr>Yearly" + savingsText + "<small>" + disclaimerMark + "</small></nobr></td>";
		return_val += "		<td width=\"100%\"></td>";
		return_val += "	</tr>";
		return_val += "	<tr>";
		return_val += "		<td></td>";
		return_val += "		<td valign=\"top\" align=\"right\"><nobr>" + formatCurrency((currentYearlyCost - newYearlyCost) / 12) + "</nobr></td>";
		return_val += "		<td></td>";
		return_val += "		<td valign=\"top\"><nobr>Monthly" + savingsText + "<small>" + disclaimerMark + "</small></nobr></td>";
		return_val += "		<td width=\"100%\"></td>";
		return_val += "	</tr>";
		return return_val;
}

// ----------------------------------------------------------------
// FUNCTION display_error()
// Display error message as HTML
// ----------------------------------------------------------------
function display_error(errorText) {
	savings_est  = "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
	savings_est += "  <tbody>";
	savings_est += "	<tr>";
	savings_est += "		<td colspan=\"3\" valign=\"top\"><br><font color=\"#D9C266\"><i>ERROR: One or more of the values entered above is invalid (" + errorText + ")</i></font></td>";
	savings_est += "	</tr>";
	savings_est += "  </tbody>";
	savings_est += "</table>";
	document.getElementById("savings").innerHTML = savings_est;
}


// ----------------------------------------------------------------
// FUNCTION get_value()
// returns the abs numeric value of the supplied object (input field)
// ----------------------------------------------------------------
function get_value(object_name) {
	object_ref = document.getElementById(object_name);
	object_ref = object_ref.value.replace(/[^0-9|.]/, "");
	return parseFloat(object_ref);
}

// ----------------------------------------------------------------
// FUNCTION formatCurrency()
// formats number as currency eg: $x.xx
// ----------------------------------------------------------------
function formatCurrency(num) {
	num = num.toString().replace(/[^0-9|\.\-]/g,'');	//replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

// ----------------------------------------------------------------
// FUNCTION formatNumber()
// formats price field to specified number of significant digits 
// with trailing zeros
// ----------------------------------------------------------------
function formatNumber(prefix, objectName, sigDigits, blankDefault) {
	var nums = new Array();
	var numstring = '';

	//	get number
	num = objectName.value;
	num = num.toString().replace(/[^0-9|\.]/g,'');
	if (num == ".") {
		num = "0";
	}
	if (num == '' || num == blankDefault) {
		objectName.value = blankDefault;
	} else {
		num = parseFloat(num);
	
		// make sure number is a valid number
		if(!isNaN(num)) {
			// reduce to 'digits' significant digits
			num = Math.floor(num * Math.pow(10,sigDigits));
			num = num / Math.pow(10,sigDigits);
		
			// convert to string
			numstring = num.toString();
			
			result = numstring.search(/\./g);
			if (result == -1) {
				// whole number, don't split
				nums[0] = numstring;
				nums[1] = "";
			} else {
				// split
				nums = numstring.split(".");
			}
			
			// pad significant zeros to 'digit' digits
			while(nums[1].length < sigDigits) {
				nums[1] = nums[1] + '0';
			}
	
			if (sigDigits == 0) {
				objectName.value = prefix + nums[0];
			} else {
				objectName.value = prefix + nums[0] + '.' + nums[1];
			}
		}
	}
}