/****************************************************************************************************
  Copyright Dealer.com Websystems
	calc.js
	Calcualates standard values plus ranges
	author: SNG
	depends on Config object in carbuilder (set in top of object)
	Notes:
	History:
		created 12.29.2000
		last modified: 12.4.2006 by ScottyG, made this an object
****************************************************************************************************/

var calc = {
	calcForm : null,
	verbiage : "Call",
	defaultRate : parseFloat(Config.CalcRate),
	defaultTerm : parseInt(Config.CalcTerm, 10),
    defaultCashTrade : Config.CalcCashTrade,
    termInterval : parseInt(Config.CalcInterval, 10),
    price : 0,
	retail : 0,
	term : Config.CalcTerm,
	rate : 0,
	maxPrice : 0,
	minPrice : 0,
	moPayDiv : "detailsMonthlyPayment",

	initialize: function ( formName, affordableCalc ) {
		this.calcForm = (formName==null) ? document.forms[0]:document.forms[formName];
        this.calcForm.cash_trade.value = this.defaultCashTrade;
        var cashTrade = this.calcForm.cash_trade.value;
        if (cashTrade.indexOf("%") != -1) {
			this.price = this.normalize((this.calcForm.maxPrice.value!="")?this.calcForm.maxPrice.value:this.calcForm.price.value);
            cashTrade = Math.floor((parseFloat(this.price) * ( parseInt(calc.normalize(cashTrade), 10) / 100) ) / 100) * 100;
            this.calcForm.cash_trade.value = cashTrade;
		}
		this.calcForm.rate.value = this.defaultRate;
		this.populateTerms(this.defaultTerm);
		if(!affordableCalc) {
			this.exec();
		}
	},

	exec : function (affordableCalc) {
		if(affordableCalc) {
			this.populatePurchasingPower(this.calculatePurchasingPower());
		} else {
			if(this.calcForm) this.getTerms();
			this.populate(this.calculate(this.minPrice), this.calculate(this.maxPrice));
		}
	},

	populate : function ( minMoPay, maxMoPay ) {
		if(this.calcForm) {
			if(this.calcForm.rate.value=="" || this.calcForm.rate.value=="0.") {return;}
		//	if(parseFloat(calcForm.rate.value)<=0) {return;}
			if( minMoPay == "0.00" ) {
				if(minMoPay == maxMoPay) {//if not calculating a range
					this.calcForm.cash_trade.disabled=true;
					this.calcForm.retail.disabled=true;
					this.calcForm.rate.disabled=true;
					this.calcForm.term.disabled=true;
					if(this.calcForm.monthlypayment) {
						this.calcForm.monthlypayment.value=0;
						this.calcForm.monthlypayment.disabled=true;
					}
					this.calcForm.price.value=this.verbiage;
					this.calcForm.retail.value=this.verbiage;
					$("#" + this.moPayDiv).html(this.verbiage);
					return;
				} else {
					this.calcForm.price.value=this.verbiage;
					this.calcForm.retail.value=this.verbiage;
					$("#" + this.moPayDiv).html(this.verbiage);
				}
			} else if( this.calcForm.cash_trade.value.indexOf("-") != -1 || new Number(this.normalize(this.calcForm.cash_trade.value)) < 0 ){
				alert("Your down payment must be greater than zero.\nIf you have any questions, feel free to contact us via email.\nThank You.");
				return;
			}
			this.calcForm.cash_trade.disabled=false;
			this.calcForm.retail.disabled=false;
			this.calcForm.rate.disabled=false;
			this.calcForm.term.disabled=false;
		}
		if(maxMoPay && minMoPay != maxMoPay)
			$("#" + this.moPayDiv).html("$" + minMoPay + " - $" + maxMoPay + "/mo**");
		else
			$("#" + this.moPayDiv).html("$" + minMoPay + "/mo**");
	},

	rePopulate : function ( maxTerms )
	{
		this.clearSelector( "term" );
		this.populateTerms( maxTerms );
	},

	calculate : function (price, rate, term)
	{
		if(!price) price = this.price;
		if(!rate) rate = this.rate;
		if(!term) term = this.term;

		if( this.rate == 0 ){
			pay = new String(price/term);
		}
		else {
			var monthIntRate = rate / 12;
			var ratePlus = eval(monthIntRate+1);
			var pow = Math.pow( ratePlus, term );
			var pay = new String( ( price ) / (( 1 - (1/pow)) / monthIntRate) );
		}

		if( pay == "NaN" ) return this.verbiage;
		else if( pay<0) return 0;
		return this.format(pay);
	},

	getTerms : function () {
		if(this.calcForm.rate.value=="" ) {return;}

		// update prices and monthly payment
		if(this.calcForm.minPrice)
			this.minPrice = this.normalize(this.calcForm.minPrice.value) - this.normalize(this.calcForm.cash_trade.value);
		if(this.calcForm.maxPrice)
			this.maxPrice = this.normalize(this.calcForm.maxPrice.value) - this.normalize(this.calcForm.cash_trade.value);
		if(this.calcForm.price)
			this.price = this.normalize(this.calcForm.price.value) - this.normalize(this.calcForm.cash_trade.value);
		this.rate = this.calcForm.rate.value/100;
		this.term = this.calcForm.term.options[this.calcForm.term.selectedIndex].value;
	},

	populateTerms : function ( max, sel ) {
		var i = 0;
		while (max > 0) {
			this.calcForm.term.options[i] = new Option(max+' mo.',max);
			if ((sel) && (max == sel)) { this.calcForm.term.selectedIndex = i; }
			max -= this.termInterval;
			i++;
		}
	},

	clearSelector : function ( who ) {
	  // needs to cleanup all select objects below 'who'
	  var start = 0;
	  var end = this.calcForm.elements[who].options.length;
	  if( end < start )
		  return false;
	  for( i=end; i>=start; i-- ){
		  this.calcForm.elements[who].options[i] = null;
	  }
	},

	normalize : function ( value )
	{
	  if( value == null || value == "" ) {
		value = 0;
	  } else {
		value = value.replace(/,/, "");
		value = value.replace(/$/, "");
	  }

	  return value;
	},


	format : function ( str, hideDecimal ) {
	  var fraction;
		numerals = new String(str);
		index = numerals.indexOf(".");
		if( index != -1 ){
			fraction = numerals.substring( index, index+3 );
			numerals = numerals.substring( 0, index );
		}

		ln = numerals.length;
		beg = numerals.substring( 0, ln-3 );
		end = numerals.substring( ln-3 );
		if(hideDecimal) {
			retVal=beg+((ln>3)?",":"")+end;
		} else {
			retVal=beg+((ln>3)?",":"")+end+((fraction==null)?".00":fraction);
		}

		return retVal;
	},

	calculatePurchasingPower : function () {
		var purchasingPower;
		var monthlyPayment = this.calcForm.affordableMonthlyPayment.value;
		var cashTrade      = parseFloat( 0 + this.calcForm.cash_trade.value );
		var rate           = this.calcForm.rate.value / 1200;
		var term           = this.calcForm.term.value;

		if( rate == 0 )
			purchasingPower = ( monthlyPayment * term ) + cashTrade;
		else
			purchasingPower = monthlyPayment * ( ( 1 - ( 1 / Math.pow( 1 + rate, term ) ) ) / rate ) + cashTrade;

		return this.format( purchasingPower );
	},

	populatePurchasingPower : function ( moPay ) {
		if(this.calcForm.rate.value=="" || this.calcForm.rate.value=="0.") {return;}

		if( moPay=="NaN.00"  ) {
			this.calcForm.purchasingPower.value = 0;
			this.calcForm.purchasingPower.disabled = true;
			this.calcForm.purchasingPower.value = this.verbiage;
			return;
		} else if( this.calcForm.cash_trade.value.indexOf("-") != -1 || new Number(this.normalize(this.calcForm.cash_trade.value)) < 0 ){
			alert("Your down payment must be greater than zero.\nIf you have any questions, feel free to contact us via email.\nThank You.");
			return;
		}

		this.calcForm.purchasingPower.disabled = false;
		this.calcForm.purchasingPower.value = moPay;
	},

	doBoth : function () {
		this.exec();
		this.populatePurchasingPower( this.calculatePurchasingPower() );
	},

	runOnce : function(price, moPayDiv) {
		var prices;
		if(price.indexOf("$") != -1) {
			prices = price.replace(/[$\s,]/g,"").split("-");
			if(prices[1] == 0) prices[1] = prices[0];
		}
		oldMoPayDiv = this.moPayDiv;
		this.moPayDiv = moPayDiv;
		this.minPrice = prices[0];
		this.maxPrice = prices[1];
		this.rate = 0.069;
		this.term = 60;
		this.calcForm = null;
		this.exec();
		//this.populate( this.calculate(prices[0], 6.9, 60), this.calculate(prices[1], 6.9, 60) );
		this.moPayDiv = oldMoPayDiv;
	}
}