// jquery noConflict (since using other libs)
var $j = jQuery.noConflict();

var calc = (function(){
	"use strict";
	return {
		 // Arguments: number to round, number of decimal places
		roundNumber : function(rnum, rlength){
			return Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);	
		},
		// Check if something really is numeric
		isNumeric : function(strString) {//  check for valid numeric strings	
			if (!/\D/.test(strString)) { 
				return true; //IF NUMBER
			} else if (/^\d+\.\d+$/.test(strString)) { 
				return true; //IF A DECIMAL NUMBER HAVING AN INTEGER ON EITHER SIDE OF THE DOT(.)		
			} else { 
				return false; 
			}
		},
		/* FUEL CALCULATIONS */
		calculateFuelSavings: function(avgTruckMiles, avgSteelMpg, pricePerGallon, truckCount) {
			var savings = 7/100,
				yearsToCompare = 5,
				gals_truck_year = calc.roundNumber((avgTruckMiles / avgSteelMpg), 0),
				total_gals      = calc.roundNumber((gals_truck_year * truckCount), 1),
				stl_srv_body    = calc.roundNumber((total_gals * pricePerGallon * yearsToCompare), 2),
				comp_srv_body   = calc.roundNumber((stl_srv_body - (stl_srv_body * savings)), 2),
				comp_savings    = calc.roundNumber((stl_srv_body - comp_srv_body), 2),		
				co2EmissionsCostsForSteelBody = (total_gals * 19.4) * (yearsToCompare),
				co2EmissionsCostsForCompositeBody = (total_gals * 19.4) * (0.93) * (yearsToCompare),
				compositeCo2Savings = co2EmissionsCostsForSteelBody - co2EmissionsCostsForCompositeBody;
		
			comp_savings = $j().number_format(comp_savings, {
				numberOfDecimals:	2, 
				decimalSeparator:	'.',
				thousandSeparator: ',',
				symbol: '$'
			});	
			stl_srv_body = $j().number_format(stl_srv_body,{
				numberOfDecimals:	2, 
				decimalSeparator:	'.',
				thousandSeparator: ',',
				symbol: '$'
			});	
			comp_srv_body = $j().number_format(comp_srv_body,{
				numberOfDecimals:	2, 
				decimalSeparator:	'.',
				thousandSeparator: ',',
				symbol: '$'
			});	
			gals_truck_year = $j().number_format(gals_truck_year,{
				numberOfDecimals:	2, 
				decimalSeparator:	'.',
				thousandSeparator: ',',
				symbol: '$'
			});	
			total_gals = $j().number_format(total_gals,{
				numberOfDecimals:	2, 
				decimalSeparator:	'.',
				thousandSeparator: ',',
				symbol: '$'
			});	
			co2EmissionsCostsForSteelBody = $j().number_format(co2EmissionsCostsForSteelBody,{
				numberOfDecimals:	2, 
				decimalSeparator:	'.',
				thousandSeparator: ','
			});	
			co2EmissionsCostsForCompositeBody = $j().number_format(co2EmissionsCostsForCompositeBody,{
				numberOfDecimals:	2, 
				decimalSeparator:	'.',
				thousandSeparator: ','
			});	
			compositeCo2Savings = $j().number_format(compositeCo2Savings,{
				numberOfDecimals:	2, 
				decimalSeparator:	'.',
				thousandSeparator: ','
			});	
		
			$j("#galsUsedPerTruck").html( gals_truck_year );
			$j("#totalGalsUsedPerYear").html( total_gals );
			$j("#fuelCostSteelBody").html( stl_srv_body );
			$j("#fuelCostServiceBody").html( comp_srv_body );
			$j("#compositeFuelSavings").html( comp_savings );	
			$j("#co2EmissionsSteelBody").html( co2EmissionsCostsForSteelBody + " lbs" );	
			$j("#co2EmissionsCompositeBody").html( co2EmissionsCostsForCompositeBody + " lbs" );	
			$j("#compositeCo2Savings").html( compositeCo2Savings + " lbs" );	
		},

		fuel_form_validate : function() {
			var	avgTruckMiles = $j.trim($j("#edit_avg_truck_miles").val()),
				avgSteelMpg = $j.trim($j("#edit_avg_steel_mpg").val()),
				pricePerGallon = $j.trim($j("#edit_price_per_gallon").val()),
				truckCount = $j.trim($j("#edit_truck_count").val()),
				invalidValues = false;
			$j("#error_avg_truck_miles").html("");
			$j("#error_avg_steel_mpg").html("");
			$j("#error_price_per_gallon").html("");
			$j("#edit_truck_count").html("");
			if(!calc.isNumeric(avgTruckMiles)){
				$j("#error_avg_truck_miles").html("Please enter numeric value");
				invalidValues = true;
			}
			if(!calc.isNumeric(avgSteelMpg)){
				$j("#error_avg_steel_mpg").html("Please enter numeric value");
				invalidValues = true;
			}
			if(!calc.isNumeric(pricePerGallon)){
				$j("#error_price_per_gallon").html("Please enter numeric value");
				invalidValues = true;
			}
			if(!calc.isNumeric(truckCount)){
				$j("#error_truck_count").html("Please enter numeric value");
				invalidValues = true;
			}
			if( !invalidValues ){
				calc.calculateFuelSavings( avgTruckMiles, avgSteelMpg, pricePerGallon, truckCount );
			}
		}		
	};
})();


/*
* @Copyright (c) 2010 Ricardo Andrietta Mendes - eng.rmendes@gmail.com
* 
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
* 
* How to use it:
* var formated_value = $().number_format(final_value);
* 
* Advanced:
* var formated_value = $().number_format(final_value, 
* 													{
* 													numberOfDecimals:3,
* 													decimalSeparator: '.',
* 													thousandSeparator: ',',
* 													symbol: 'R$'
* 													});
*/
//indica que est sendo criado um plugin
jQuery.fn.extend({	//indica que est sendo criado um plugin
	number_format: function(numero, params) {//indica o nome do plugin que ser criado com os parametros a serem informados
		//parametros default
		var sDefaults = {
			numberOfDecimals: 2,
			decimalSeparator: ',',
			thousandSeparator: '.',
			symbol: ''
			},
			//funo do jquery que substitui os parametros que no foram informados pelos defaults
			options = jQuery.extend(sDefaults, params),
	
			//CORPO DO PLUGIN
			number = numero,
			decimals = options.numberOfDecimals,
			dec_point = options.decimalSeparator,
			thousands_sep = options.thousandSeparator,
			currencySymbol = options.symbol,
	
			exponent = "",
			numberstr = number.toString (),
			eindex = numberstr.indexOf ("e"),
			i = 0,
			z = 0;
		if (eindex > -1){
			exponent = numberstr.substring (eindex);
			number = parseFloat (numberstr.substring (0, eindex));
		}

		if (decimals != null){
			var temp = Math.pow (10, decimals);
			number = Math.round (number * temp) / temp;
		}
		var sign = number < 0 ? "-" : "",
			integer = (number > 0 ? 
		  Math.floor (number) : Math.abs (Math.ceil (number))).toString (),
		
		fractional = number.toString ().substring (integer.length + sign.length);
		dec_point = dec_point != null ? dec_point : ".";
		fractional = decimals != null && (decimals > 0 || fractional.length > 1) ? 
				   (dec_point + fractional.substring (1)) : "";
		if (decimals != null && decimals > 0) {
			for (i = fractional.length - 1, z = decimals; i < z; ++i) {
			  fractional += "0";
			}
		}
		
		thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
					  thousands_sep : null;
		if (thousands_sep != null && thousands_sep != "") {
			for (i = integer.length - 3; i > 0; i -= 3) {
			  integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
			}
		}
		
		if (options.symbol == '') {
			return sign + integer + fractional + exponent;
		} else  {
			return currencySymbol + ' ' + sign + integer + fractional + exponent;
		}
		//FIM DO CORPO DO PLUGIN
	}
});

$j(document).ready(function() {
	"use strict";
	/* NEWSLETTER FORM SUBMISSION */
	$j("#newsletter_form_btn").click(function(){
		$j("#newsletter_form").submit();
	});	
	
	/* FUEL CALCULATIONS */
	$j("#edit_submit").click(function(){
		calc.fuel_form_validate();
	});
	$j("#edit_submit").click();
});
/* NEWSLETTER FORM SUBMISSION */
