var SavingsCalculator = Class.create();
SavingsCalculator.prototype = {

mpgSelect : null,
ppgSelect : null,
moneySavedElem : null,
gallonsSavedElem : null,

// Initializer.
//
initialize : function() {

	this.mpgSelect = $( 'afmCalcTab_mpg' );
	this.ppgSelect = $( 'afmCalcTab_ppg' );
	this.moneySavedElem = $( 'afmCalcTab_moneySaved' );
	this.gallonsSavedElem = $( 'afmCalcTab_gallonsSaved' );

	// Get the values specified in the URL.
	var url = window.location.href;
	var urlParams = url.toQueryParams();

	var selectedIndex;

	// Setup miles per gallon dropdown.
	selectedIndex = 0;
	this.mpgSelect.remove( 0 );
	for( var i = 10; i <= 60; i += 2 ) {
		this.addOption( this.mpgSelect, this.formatAsMPG( i ), i );
		if ( i == urlParams.afmCalcTab_mpg ) this.mpgSelect.selectedIndex = selectedIndex;
		selectedIndex++;
	} // End for.

	// Setup price per gallon dropdown.
	selectedIndex = 0;
	this.ppgSelect.remove( 0 );
	for( var i = 1.5; i <= 4.00; i += 0.25 ) {
		this.addOption( this.ppgSelect, this.formatAsDollar( i ), i );
		if ( i == urlParams.afmCalcTab_ppg ) this.ppgSelect.selectedIndex = selectedIndex;
		selectedIndex++;
	} // End for.

	Event.observe( 'afmCalcTab_mpg', 'change', this.onCalculate.bind( this ), false );
	Event.observe( 'afmCalcTab_ppg', 'change', this.onCalculate.bind( this ), false );

	this.onCalculate();

}, // End initialize().

addOption : function( selectObj, name, value ) {

	selectObj.options[ selectObj.options.length ] = new Option( name, value );

}, // End addOption().

formatAsMPG : function( val ) {

	var mpg = val.toString();

	if( val < 10 ) mpg = "0" + mpg;

	return mpg + " MPG";

}, // End formatAsMPG().

formatAsDollar : function( val ) {

	var dollar = val.toString();

	if ( dollar.indexOf( "." ) < 0 ) {
		dollar += ".00";
	}

	if ( dollar.indexOf( "." ) == dollar.length - 2 ) {
		dollar += "0";
	}

	return "$" + dollar;

}, // End formatAsDollar().

onCalculate : function() {

	var mpg = this.mpgSelect.options[ this.mpgSelect.selectedIndex ].value;
	var ppg = this.ppgSelect.options[ this.ppgSelect.selectedIndex ].value;

	if ( ppg > 0 && mpg > 0 ) {

		var gallons = 2600 / ( mpg * 1.04 );
		var savings = gallons * ppg;

		this.moneySavedElem.innerHTML = "$" + parseInt( savings ) + " per set of&nbsp;four&nbsp;tires"
		this.gallonsSavedElem.innerHTML = parseInt( gallons ) + " per set of&nbsp;four&nbsp;tires";

	} // End if.

} // End onCalculate().

} // End class SavingsCalculator.

var savingsCalculator = new SavingsCalculator();
