var calculator = {
		months: null,
		price: null,
		rate: null,
		loan_term: null,
		custom_lt_mode: null,
		custom_month: null,
		down_payment: null,
		value_tradein: null,

		mainIndex: null,
		offset: 0,
		data: null,
		errors: null,

		process: function() {
			if (this.validate()) {
				this.calculate();
		    }
		},

		validate: function() {
			this.price = new Number(this.clean_number(jQuery("#price").val()));
			this.rate = new Number(this.clean_number(jQuery("#rate").val()));
			this.loan_term = new Number(this.clean_number(jQuery("#loan_term").val()));
			this.down_payment = new Number(this.clean_number(jQuery("#down_payment").val()));
			this.value_tradein = new Number(this.clean_number(jQuery("#value_tradein").val()));

		    if(isNaN(this.price) || this.price <= 0 ) {
		        alert(this.errors.JS_ERROR_PRICE);
		        return false;
		    }
		    if(isNaN(this.rate) || this.rate < 0 || this.rate > 100) {
		        alert(this.errors.JS_ERROR_RATE);
		        return false;
		    }
		    if ( isNaN(this.loan_term) || this.loan_term < 0  )
		    {
		        alert(this.errors.JS_ERROR_LOAN_TERM);
		        return false;
		    }
		    if ( isNaN(this.down_payment) || this.down_payment < 0 || this.down_payment >= this.price )
		    {
		        alert(this.errors.JS_ERROR_DOWN_PAYMENT);
		        return false;
		    }
		    if ( isNaN(this.value_tradein) || this.value_tradein < 0 || this.value_tradein >= this.price)
		    {
		        alert(this.errors.JS_ERROR_TRADEIN);
		        return false;
		    }
		    if ( this.value_tradein + this.down_payment >= this.price)
		    {
		        alert(this.errors.JS_ERROR_TRADEIN_DOWN_PAYMENT);
		        return false;
		    }
		    return true;
		},

		calculate: function(){
			 this.custom_month = (new Array()).concat(this.months);
			 this.mainIndex = jQuery.inArray(parseInt(this.loan_term), this.custom_month);

			 if(this.mainIndex == -1) {
				 var loan_term = parseInt(this.loan_term);
				 this.temp_index = 0;
				 var length = this.custom_month.length;

				 for(var c = 0; c < length; c++) {
					if(loan_term < this.custom_month[c]) {
						this.mainIndex = c;
						this.custom_month.splice(c, 0, loan_term);
						break;
					}
				 }
			 }

			 this.data = new Array();

			 principal = this.price - this.down_payment - (this.value_tradein == null ? 0 : this.value_tradein);
			 if(this.rate == 0) {

				 for (var i=0; i<this.custom_month.length; i++){
					 this.data[i] =  (principal / this.custom_month[i]).toFixed(0);
				 }
				 var amount = principal;

			 }
			 else{
				 mointerest = this.rate * 100 / 10000 / 12;

				 for (var i=0; i < this.custom_month.length; i++){
					 x = Math.pow(1 + mointerest, this.custom_month[i]);
					 this.data[i] =  ((principal * x * mointerest) / (x - 1)).toFixed(0);
				 }
				 var amount = principal * (((this.rate * 100) / 10000)+1);
			 }

			 jQuery(".amount-info > span").html("$" + this.number_format(this.price,0,".",","));
			 this.showResults(0);

		},

		showResults: function(newoffset){

			if(this.data == null) return false;

			var len = this.custom_month.length;
			if(newoffset == 0)
				var main = this.mainIndex ;
			else
				var main = this.mainIndex + this.offset + newoffset;

			if(main < 0 || main> (len-1)) return false;

			this.offset += newoffset;

			var prev = main>0?main-1:null;
			var next = main<(len-1)?main+1:null;

			this.showPrev(prev);
			this.showMain(main);
			this.showNext(next);
		},
		showMain: function(main)
		{
			   jQuery("td.mmain > .mbox-main").html("$" + this.data[main]);
			   jQuery("td.mmain > .mtext-main").html(this.custom_month[main] + " Months");
		},
		showPrev: function(prev)
		{
		   if(prev!=null){
			   jQuery("td.mleft > .mbox").html("$" + this.data[prev]);
			   jQuery("td.mleft > .mtext").html(this.custom_month[prev] + " Months");
		   }else{
			   jQuery("td.mleft > .mbox").html("--");
			   jQuery("td.mleft > .mtext").html("--");
		   }
		},
		showNext: function(next)
		{
		   if(next!=null){
			   jQuery("td.mright > .mbox").html("$" + this.data[next]);
			   jQuery("td.mright > .mtext").html(this.custom_month[next] + " Months");
		   }else{
			   jQuery("td.mright > .mbox").html("--");
			   jQuery("td.mright > .mtext").html("--");
		   }
		},
		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) : "");
		}

}

$(document).ready(function(){
	var CUSTOM_INT_RATE_LABEL_TEXT = null;
	$("#custom_interest_rate_switcher").click(function(){
		if($(this).text() != EXIT_CUSTOM_MODE){
			$("#rate").hide().attr("name","rate_disabled").attr("id","rate_disabled");
			$(this).before("<div class=\"custom-input-wrapper\" id=\"rate_custom_input_wrapper\"></div>");
			$("#rate_custom_input_wrapper").append("<input type=\"text\" id=\"rate\" name=\"rate\" class=\"text rate\" />").append("<span class=\"custom-input-label\">%</span>");
			$("#rate").focus();
			CUSTOM_INT_RATE_LABEL_TEXT = $(this).text();
			$(this).text(EXIT_CUSTOM_MODE);
		} else {
			$(this).text(CUSTOM_INT_RATE_LABEL_TEXT);
			$("#rate_custom_input_wrapper").remove();
			$("#rate_disabled").show().attr("name","rate").attr("id","rate");

		}
		return false;
	});
	var CUSTOM_INT_LOAN_TERM_LABEL_TEXT = null;
	$("#custom_loan_term_switcher").click(function(){
		if($(this).text() != EXIT_CUSTOM_MODE){
			calculator.custom_lt_mode = false;
			$("#loan_term").hide().attr("name","loan_term_disabled").attr("id","loan_term_disabled");
			$(this).before("<div class=\"custom-input-wrapper\" id=\"loan_term_custom_input_wrapper\"></div>");
			$("#loan_term_custom_input_wrapper").append("<input type=\"text\" id=\"loan_term\" name=\"loan_term\" class=\"text loan_term\" />").append("<span class=\"custom-input-label\">months</span>");
			$("#loan_term").focus();
			CUSTOM_INT_LOAN_TERM_LABEL_TEXT = $(this).text();
			$(this).text(EXIT_CUSTOM_MODE);
		} else {
			calculator.custom_lt_mode = true;
			$(this).text(CUSTOM_INT_LOAN_TERM_LABEL_TEXT);
			$("#loan_term_custom_input_wrapper").remove();
			$("#loan_term_disabled").show().attr("name","loan_term").attr("id","loan_term");

		}
		return false;
	});
});
