var mpg_calculator = {
		citympg: null,
		hwympg: null,
		mileage: null,
		galon_price: null,
		newcitympg: null,
		newhwympg: null,
		
		savings: null,
		curvalue: null,
		newvalue: null,
		errors: null,
		
		process: function(){
			if ( this.validate() ) {
				this.calculate();
		    }
		},
		validate: function(){
		 
			this.citympg = new Number(this.clean_number(jQuery("#citympg").val()));
			this.hwympg = new Number(this.clean_number(jQuery("#hwympg").val()));
			this.newcitympg = new Number(this.clean_number(jQuery("#newcitympg").val()));
			this.newhwympg = new Number(this.clean_number(jQuery("#newhwympg").val()));
			this.mileage = new Number(this.clean_number(jQuery("#mileage").val()));
			this.galon_price = new Number(this.clean_number(jQuery("#galon_price").val()));
			
			if ( isNaN(this.newcitympg) || this.newcitympg < 0 || this.newcitympg > 100 || this.newcitympg == "")
		    {
		        alert(this.errors.JS_ERROR_NEWCITYMPG);
		        return false;
		    }
		    if ( isNaN(this.newhwympg) || this.newhwympg < 0 || this.newhwympg > 100 || this.newhwympg == "")
		    {
		        alert(this.errors.JS_ERROR_NEWHWYMPG);
		        return false;
		    }
			if ( isNaN(this.citympg) || this.citympg < 0 || this.citympg > 100 || this.citympg == "")
		    {
		        alert(this.errors.JS_ERROR_CITYMPG);
		        return false;
		    }
		    if ( isNaN(this.hwympg) || this.hwympg < 0 || this.hwympg > 100 || this.hwympg == "")
		    {
		        alert(this.errors.JS_ERROR_HWYMPG);
		        return false;
		    }
		    if ( isNaN(this.galon_price) || this.galon_price < 0)
		    {
		        alert(this.errors.JS_ERROR_GALON_PRICE);
		        return false;
		    }
		     
		    return true;
		},
		
		calculate: function(){
			 this.savings = new Array();
			  
			 
			 this.curvalue = (0.6/this.citympg+0.4/this.hwympg)*this.galon_price*((this.mileage/12)*12); 
			 this.newvalue = (0.6/this.newcitympg+0.4/this.newhwympg)*this.galon_price*((this.mileage/12)*12);
			 
			 this.savings[1] = (this.curvalue - this.newvalue); 
			 this.savings[5] = (this.curvalue - this.newvalue) * 5; 
			 this.savings[10] = (this.curvalue - this.newvalue) * 10;
			 this.showResults();
			 	
		},
		
		showResults: function(){
			this.showCurrentFuelSavings();
			this.showNewFuelSavings();
			this.showPrev(1);
			this.showMain(5);
			this.showNext(10);
		},
		showCurrentFuelSavings: function(key)
		{
			   jQuery(".amount-info > span").html("$" + this.curvalue.toFixed(0));
		},
		showNewFuelSavings: function(key)
		{
			   jQuery(".new-amount-info > span").html("$" + this.newvalue.toFixed(0));
		},
		showMain: function(key)
		{
			   jQuery("td.mmain > .mbox-main").removeClass("mbox-red");
			   jQuery("td.mmain > .mbox-main").html("$" + this.savings[key].toFixed(0));
			   if(this.savings[key]<0) 
				   jQuery("td.mmain > .mbox-main").addClass("mbox-red");
		},
		showPrev: function(key)
		{
			   jQuery("td.mleft > .mbox-left").removeClass("mbox-red");   
			   jQuery("td.mleft > .mbox-left").html("$" + this.savings[key].toFixed(0));
			   if(this.savings[key]<0) 
				   jQuery("td.mleft > .mbox-left").addClass("mbox-red");
		},
		showNext: function(key)
		{
			   jQuery("td.mright > .mbox-right").removeClass("mbox-red");
			   jQuery("td.mright > .mbox-right").html("$" + this.savings[key].toFixed(0));
			   if(this.savings[key]<0) 
				   jQuery("td.mright > .mbox-right").addClass("mbox-red");
		},
		clean_number: function(num)
		{
		   num = num.toString().replace(/\$|\,/g,'');
		   return num;
		},
		number_format: function( number, decimals, dec_point, thousands_sep ) {
		    // *     example 1: number_format(1234.5678, 2, '.', '');
		    // *     returns 1: 1234.57     
		 
		    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
		    var d = dec_point == undefined ? "," : dec_point;
		    var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
		    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
		 
		    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
		},
		
		_loaderWaitDisable: function() {
			$('input,select', '#searchbox_mpg_calc').attr('disabled', 'true');
		},
		_loaderDoneDisable: function() {
			$('#searchbox_mpg_calc select').removeAttr('disabled');
		},
		showMPG: function(input){
		     if((input=='') || (input==null)){
		     	jQuery("#newcitympg").val("");
		    	jQuery("#newhwympg").val("");
		    	jQuery(".mod-mpg-calculator .mpg > .left > .count").html("");
		    	jQuery(".mod-mpg-calculator .mpg > .right > .count").html("");
		    	jQuery(".mod-mpg-calculator .mpg > .left > .area").hide();
		    	jQuery(".mod-mpg-calculator .mpg > .right > .area").hide();
		    	jQuery(".mod-mpg-calculator #model-name").html("--");
		     }else{
		    	 
		    	 var year = jQuery("#year option:selected").val();
				 var make = jQuery("#make option:selected").val();
				 var model = jQuery("#model option:selected").val();
				 var trim = (jQuery("#trim option:selected").val() != "" ? jQuery("#trim option:selected").text() : "");

				 jQuery(".mod-mpg-calculator #model-name").html(year+ " " + make + " " + model + " " +trim);
				   
		    	jQuery(".mod-mpg-calculator .mpg > .left > .area").show();
		    	jQuery(".mod-mpg-calculator .mpg > .right > .area").show();
		     }
		},     	
		reload: function(el) {
			attrs = new Array();
			elInputName = el.name;
			// parsing request string 
			requestString = document.location.search;
			if(requestString.indexOf('?')==0)
			    requestString = requestString.substring(1);
			requestParams = requestString.split("&",3)


			for(i=0; i< requestParams.length; i++) {
			    kv = requestParams[i].split('=');
			    if(kv[0]!='' && kv[1]!='') {
			        attrs[kv[0]] = kv[1];
			    }
			}

			//parsing form elements
			els = this._getFormElements();
			
			els.each(function() {
			   el = jQuery(this);
			
			   if(el.attr('type')=='checkbox') {
				   attrs[el.attr('name')] = el.is(':checked')?el.val():"";
			   }
			   else {
				   if(el.attr('placeholder')==el.val()) el.val('');
				   attrs[el.attr('name')] = el.val();
			   }
			   
			})

			// binding the url
			url = document.location.pathname+'?mode=_ajax&_imod[]=Dfe_Modules_MpgCalculator_Module';
			
			for(key in attrs) {
			    url += '&'+key+'='+escape(attrs[key]);
			    if(key == elInputName) {
					break;
			    }
			}
			//console.log(url);
			
			this._request(url, function(data){
				mpg_calculator._requestComplete(data);
				mpg_calculator.showMPG(attrs['model']);
			});

			

		},
		_request: function(url, onComplete) {
			//els = searchbox._getFormElements().attr('disabled','true');
			//this._blockForm();
			$('#searchbox_mpg_calc select').attr('disabled', 'true');
			jQuery.ajaxSetup({ cache: false });
			jQuery.get(url, onComplete);
		},
		_blockForm: function() {
			jQuery("#searchbox_mpg_calc").block({css: {border: 0,background: 'none', padding: '5px', width: '45px', marginTop: '-15px'}, message: "<img src='/public/images/loading-animation.gif' />"});
		},
		_unblockForm: function() {
			//jQuery("#"+searchbox.containerID).unblock();
		},
		_getFormElements: function() {
			return jQuery("#searchbox_mpg_calc select");
		},
		_requestComplete: function(data) {
			dom = jQuery(data);
			
			//this._unblockForm();
			$('#searchbox_mpg_calc select').removeAttr('disabled');
			//searchbox._getFormElements().removeAttr('disabled');
			jQuery('#searchbox_mpg_calc').replaceWith(dom);

			jQuery(".mod-mpg-calculator .mpg > .left > .count").html(jQuery("#newcitympg").val());
	    	jQuery(".mod-mpg-calculator .mpg > .right > .count").html(jQuery("#newhwympg").val());
		}
} 
