// amount .financeamt :text
// interest rate .interestRate select
//term .term select
//payment schedule .payment select
//balloon   .balloon select



var calculator=function()
{
	var amount,sel_interest,min_interest,max_interest,av_interest,term,schedule,balloon,cashPrice,cashDeposit,tradeIn;
	var errorList=new Array();
		
	onload=function()
	{
		//console.warn("loading finance calculator onload");
		if (document.getElementById("calculate_button"))
		{
			 //configCalculator();

		}
	};
	
	
	configCalculator=function()
	{
		//console.debug("loading finance calculator configcalculator");
		$("#calculate_button").click(function(){calculate(); return false;});
		$("#interestCalculator .submit :submit").click(function(){saveFields(); });
		$("form .cashprice :text").blur(function(){calculateFinanceAmount();});
		$("form .cashdeposit :text").blur(function(){calculateFinanceAmount();});
		$("form .tradedeposit :text").blur(function(){calculateFinanceAmount();});
	};
	this.configCalculator=configCalculator;
		
	var collectData=function()
	{
		cashPrice=getCashPrice();
		cashDeposit=getCashDeposit();
		tradeIn=getTradeIn();
		amount=getAmount();
		sel_interest=getInterest($("form .interestRate select")[0].selectedIndex);
		min_interest=getInterest(1);
		max_interest=getInterest($("form .interestRate select")[0].length-1);
		av_interest=getInterest(Math.ceil( $("form .interestRate select")[0].length/2 ) );
		term=getTerm();
		schedule=getSchedule();
		balloon=getBalloon();
		//console.warn("balloon %="+balloon);
		balloon=amount*balloon/100;
		//console.warn("balloon amount="+balloon);
	};
	this.collectData=collectData;
	
	var getInterest=function(index)
	{
		//console.debug("interest index="+index);
		var list=$("form .interestRate select")[0];
		var interest=list.options[index].text.replace(/[^0-9\.]/g,"")/1;
		collectErrors(list);
		return interest;
	};
	this.getInterest=getInterest;
	
	var getTerm=function()
	{
		var list=$("form .term select")[0];
		var term=list.options[list.selectedIndex].text.replace(/[^0-9\.]/g,"")/1;
		term=term*12;
		collectErrors(list);
		return term;
	};
	
	
	
	var getCashPrice=function()
	{
		var amount=$("form .cashprice :text").val()
		if (amount && amount/1)
		{
			amount=amount.replace(/[^0-9\.]/g,"")/1;
			amount=(amount)?amount:0;
			collectErrors($("form .cashprice :text")[0]);
		}
		else
		{
			amount=0;
		}
		
		return amount;
	};


	var getCashDeposit=function()
	{
		var amount=$("form .cashdeposit :text");
		
		if (amount && amount/1)
		{
			amount=amount.replace(/[^0-9\.]/g,"")/1;
			amount=(amount)?amount:0;
			collectErrors($("form .cashdeposit :text")[0]);
		}
		else
		{
			amount=0;
		}
		return amount;
	};


	var getTradeIn=function()
	{
		var amount=$("form .tradedeposit :text").val();
		if (amount && amount/1)
		{
			amount=amount.replace(/[^0-9\.]/g,"")/1;
			amount=(amount)?amount:0;
			collectErrors($("form .financeamt :text")[0]);
		}
		else
		{
			amount=0;
		}
		return amount;
	};

	var getAmount=function()
	{
		var amount=$("form .financeamt :text").val().replace(/[^0-9\.]/g,"")/1;
		amount+=365; //establishment fee
		collectErrors($("form .financeamt :text")[0]);
		return amount;
	};
	
	var getSchedule=function()
	{
		var list=$("form .payment select")[0];
		var schedule=list.selectedIndex;
		collectErrors(list);
		return schedule;
	};
	
	var getBalloon=function()
	{
		var list=$("form .balloon select")[0];
		var balloon=list.options[list.selectedIndex].text.replace(/[^0-9\.]/g,"")/1;
		collectErrors(list);
		return balloon;
	};
	
	var getBalloonIndex=function()
	{
		var list=$("form .balloon select")[0];
		var balloonindex=list.selectedIndex;
		collectErrors(list);
		return balloonindex;
	};
	
	var calculate=function(interest)
	{
		//console.warn("calculate and display the interest");
		collectData();
		//calculate min interest
		var min_pay=calculatePayment(min_interest);
		$("#min-interest").html(min_interest);
		$("#min-pay").html(min_pay);
		//calculate average interest
		var av_pay=calculatePayment(av_interest);
		$("#av-interest").html(av_interest);
		$("#av-pay").html(av_pay);
		//calculate max interest
		var max_pay=calculatePayment(max_interest);
		$("#max-interest").html(max_interest);
		$("#max-pay").html(max_pay);
		//calculate chosen interest
		var sel_pay=calculatePayment(sel_interest);
		$("#sel-interest").html(sel_interest);
		$("#sel-pay").html(sel_pay);
		window.scrollBy(0,500);
	}
	this.calculate=calculate;
	
	var calculateFinanceAmount=function()
	{
		cashPrice=getCashPrice();
		cashDeposit=getCashDeposit();
		tradeIn=getTradeIn();
		
		var totalAmount=cashPrice-(cashDeposit+tradeIn);
		totalAmount=(totalAmount>0)?totalAmount:0;
		$("form .financeamt :text").val(totalAmount).attr("readonly", (totalAmount>0) );

	}
	this.calculateFinanceAmount=calculateFinanceAmount;
	
	var calculatePayment=function(interest)
	{
		
		var pmt_value;
		
		var calc_amount=-amount;
		
		
		if (schedule==1)
		{
			$("span.paymentPeriod").html("Weekly");
		}
		else if (schedule==2)
		{
			$("span.paymentPeriod").html("Fortnightly");		
		}
		else if (schedule==3)
		{
			$("span.paymentPeriod").html("Monthly");		
		}
		

   		rate = interest/(12 * 100);
   		//console.warn("repayment calculated for "+interest);
   		//console.debug("amount="+calc_amount);
   		//console.debug("rate="+rate);
   		//console.debug("balloon="+balloon);
   		//console.debug("term="+term);
   		if ( rate == 0 )    // Interest rate is 0
   		{
      		pmt_value = - (balloon + calc_amount)/term;
   		}
   		else 
   		{
       		var x = Math.pow(1 + rate,term);
       		pmt_value = -( (rate * (balloon + x * calc_amount))/(-1 + x)) ;
   		}
   		if ( schedule == 1)  //weekly repayment
   		{
			pmt_value = pmt_value/4.33
   		}
   		pmt_value="$"+dollarize(pmt_value,2);
   		//console.debug("pmt_value="+pmt_value);
   		return pmt_value;
   	};
   	this.calculatePayment=calculatePayment;
	
	reportErrors=function()
	{
		var i=0,field;
		$("fieldset input").css("background","");
		$("fieldset select").css("background","");
		for (i=0;i<errorList.length; i++ )
		{
			field=errorList[i];
			field.css("background","#FFDDDD");
		}
		alert("You need to enter correct values into the highlighted fields");
	};
	
	collectErrors=function(field)
	{
		errorList.push(field);
	};
	
	dollarize=function(expr, decplaces) {
		var str = "" + Math.round (eval(expr) * Math.pow(10,decplaces))
		while (str.length <= decplaces) {
			str = "0" + str
		}
		var decpoint = str.length - decplaces
		return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
	};
	
	var saveFields=function()
	{
		//console.debug("save fields");
		//save description
		var description=$("#interestCalculator .description :checked").val();
		description=(description>=1)? description : 0;
		writeCookie("description",description);
		
		//save year
		var year=$("#interestCalculator .year :text").val();
		writeCookie("year",year);
		//save condition
		var condition=$("#interestCalculator .condition :checked").val();
		writeCookie("condition",condition);

		//save cashprice
		writeCookie("cashPrice",cashPrice);
		//save cashdeposit
		writeCookie("cashDeposit",cashDeposit);
		//save tradein
		writeCookie("tradeIn",tradeIn);
		
		//save price
		writeCookie("loanAmount",amount-365);//remove establishment fee
		//save balloon
		writeCookie("balloon",getBalloonIndex());
		//sav term
		writeCookie("term",term/12);//revert from months to years
		
		//sav repayment
		writeCookie("repayment",schedule);	
	};
			
	writeCookie=function(key,value)
	{
		var pageKey,date,expires,stringValue;
 		pageKey=key;
 		stringValue=value;
 		date = new Date();
 		date.setTime(date.getTime()+(1*60*60*1000)); //1 hour duration
 		expires = "; expires="+date.toGMTString();
 		document.cookie = pageKey+"="+stringValue+expires+"; path=/;";
	};
	
	readCookie=function(key)
	{
		var pageKey,cookie,i,c,returnValue=false;
 		pageKey=key;
 		cookie= document.cookie.split(';');
 		for (i=0;i<cookie.length;i++){
 			c = cookie[i];
 			while (c.charAt(0)==' ') c = c.substring(1,c.length);
 			if (c.indexOf(pageKey) == 0){
 				returnValue= c.substring(pageKey.length+1,c.length);
 				break;
 			}
	 	}
 		return returnValue;
	};
	this.saveFields=saveFields;
	
	dollarize=function(expr, decplaces) {
		var str = "" + Math.round (eval(expr) * Math.pow(10,decplaces))
		while (str.length <= decplaces) {
			str = "0" + str
		}
		var decpoint = str.length - decplaces
		return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
	};
	
	
	//onload();
}

//$(window).ready(function(){

	var calc=new calculator();
	

//});
