// handles data and calculations for calculating loan repayments 

current_loanamount = 5000;
current_loanterm = 240;
current_creditrating = 30;

document.getElementById('loanAmount').value = '5000';
document.getElementById('repaymentPeriod').value = '20 Years';
document.getElementById('creditRating').value = 'Good';
document.getElementById('repayment').value = 63;

	
		var loanamountslider = new Control.Slider( 'loanamounthandle', 'loanamounttrack', {
			range: 			$R( 5000, 100000 ),
			sliderValue: current_loanamount,
			onSlide:		function( value )
			
			{

			current_creditrating = GetCreditRating(value);
			current_loanamount = value;
	
		
				UpdateCalculatorFields(current_loanamount, current_loanterm, current_creditrating,document.getElementById('loanAmount'),document.getElementById('repaymentPeriod'),document.getElementById('creditRating'),document.getElementById('repayment'),document.getElementById('calculatorLink'));
	
			},
			onChange:		function( value )
			{
				//current_loanamount = value;
				//UpdateCalculatorFields(current_loanamount, current_loanterm, current_creditrating, $('loanamounttext'), $('loantermtext'), $('creditratingtext'), $('repayment'), null, null, null);
			}
		}); 
		
		
		var loantermslider = new Control.Slider( 'loantermhandle', 'loantermtrack', {
			range: 			$R( 60, 300 ),
			sliderValue:	current_loanterm,
			onSlide:		function( value )
			{
			current_creditrating = GetCreditRating(value);
				current_loanterm = value;

				UpdateCalculatorFields(current_loanamount, current_loanterm, current_creditrating,document.getElementById('loanAmount'),document.getElementById('repaymentPeriod'),document.getElementById('creditRating'),document.getElementById('repayment'),document.getElementById('calculatorLink'));
			},
			onChange:		function( value )
			{
				//current_loanamount = value;
				//UpdateCalculatorFields(current_loanamount, current_loanterm, current_creditrating, $('loanamounttext'), $('loantermtext'), $('creditratingtext'), $('repayment'), null, null, null);
			}
		}); 
		
		
		var creditratingslider = new Control.Slider( 'loancredithandle', 'loancredittrack', {
			range: 			$R(0,30),
			sliderValue:	24,
			onSlide:		function( value )
			{
				
				current_creditrating = GetCreditRating(value);
	
				UpdateCalculatorFields(current_loanamount, current_loanterm, current_creditrating, document.getElementById('loanAmount'), document.getElementById('repaymentPeriod'), document.getElementById('creditRating'),document.getElementById('repayment'),document.getElementById('calculatorLink'));
			},
			onChange:		function( value )
			{
				//current_loanamount = value;
				//UpdateCalculatorFields(current_loanamount, current_loanterm, current_creditrating, $('loanamounttext'), $('loantermtext'), $('creditratingtext'), $('repayment'), null, null, null);
			}
		}); 
	
// handles data and calculations for calculating loan repayments etc.

var current_loanamount = 15000;

var current_loanterm = 240;

var current_creditrating = CREDIT_EXCELLENT;

var current_repayment = 0;



var min_loan = 15000;

var max_loan = 100000;



var CREDIT_EXCELLENT = 3;

var CREDIT_GOOD = 2;

var CREDIT_AVERAGE = 1;

var CREDIT_POOR = 0;



var credit_text = new Array();

credit_text[CREDIT_EXCELLENT] = "Good";

credit_text[CREDIT_GOOD] = "Average";

credit_text[CREDIT_AVERAGE] = "Average";

credit_text[CREDIT_POOR] = "Poor";



var fixed_fee = new Array();

fixed_fee[CREDIT_EXCELLENT] = 908.95;

fixed_fee[CREDIT_GOOD] = 998.68;

fixed_fee[CREDIT_AVERAGE] = 998.68;

fixed_fee[CREDIT_POOR] = 1091.51;



var variable_fee = new Array();

variable_fee[CREDIT_EXCELLENT] = 0.0326;

variable_fee[CREDIT_GOOD] = 0.0422;

variable_fee[CREDIT_AVERAGE] = 0.0422;

variable_fee[CREDIT_POOR] = 0.0521;



/* These are annual - (MIR * 12) */

var rate = new Array();

rate[CREDIT_EXCELLENT] = 0.111564;

rate[CREDIT_GOOD] = 0.158112;

rate[CREDIT_AVERAGE] = 0.158112;

rate[CREDIT_POOR] = 0.191364;



// get the percentage of the loanamoutn that will be 

// charged on top as fees

function GetFeePercent($amount, $credit_rating) {

	

	$fee = fixed_fee[$credit_rating];

	$vfee = variable_fee[$credit_rating];

	

	$borrowed = $amount * (1 + $vfee) + $fee;

	$abs_fee = $borrowed - $amount;

	return Math.round(($abs_fee / $amount) * 10000) / 100;

}



// allow adjusting of positions of credit ratings

function GetCreditRating($trackvalue) {

	//return Math.round(value / 10);

	if ($trackvalue < 8) {

		return CREDIT_POOR;

	} else if ($trackvalue < 19) {

		return CREDIT_AVERAGE;

	} else {

		return CREDIT_EXCELLENT;

	}

}



// portion of the EffectiveRate function

function EffectiveRateTest($months, $repayment, $guessrate) {

	var sum = 0;

	for (var i = 1; i <= $months; i++) {

		sum = sum + ($repayment / Math.pow(1 + $guessrate, i));

	}

	return sum;

}



// function to calculate effective rate

function EffectiveRate($months, $repayment, $loanamount, $minrate, $maxrate, $accuracy) {

	var max_iterations = 200;

	var iteration = 0;

	

	// do a first test

	var rate = ($maxrate + $minrate) / 2;

	var calculated_amount = EffectiveRateTest($months, $repayment, rate);

	

	while (!(

		   (calculated_amount - $accuracy) < $loanamount &&

			(calculated_amount + $accuracy) > $loanamount)

		   && iteration < max_iterations) {

		

		

		if (calculated_amount < $loanamount) {

			$maxrate = rate;			

		} else if (calculated_amount > $loanamount) {

			$minrate = rate;			

		}

		if ($maxrate == $minrate) {

			//alert("bad guess");

			return rate; // failed

		}

		

		rate = ($maxrate + $minrate) / 2;

		calculated_amount = EffectiveRateTest($months, $repayment, rate);

		iteration = iteration + 1;

	}

			

	if (iteration >= max_iterations) {

		//alert("max iterations");

		return rate; // failed

	}

	

	return rate;

}



// (PV * IR) / (1 - Math.pow(1 + IR, -NP))

function PMT($amount, $term, $credit_rating) {

	$rate = rate[$credit_rating] / 12;

	$fee = fixed_fee[$credit_rating];

	$vfee = variable_fee[$credit_rating];

	

	$borrowed = $amount * (1 + $vfee) + $fee;

	$x = 1 - Math.pow(1 + $rate, -$term);

	

	$payment = ($borrowed * $rate) / $x;

	return Math.round($payment * 100) / 100;

}



function APR($rate) {

	$apr_unrounded = Math.pow(1 + $rate, 12) - 1;

	return Math.round($apr_unrounded * 1000) / 10;	

}



function YearMonths($months) {

	remainder = $months % 12;

	years = ($months - remainder) / 12;

	if (remainder == 0) {

		return years + " years";

	} else {

		return years + " years " + remainder + " months";

	}

}



function UpdateCalculatorFields($amount, $term, $credit_rating, $amount_control, $term_control, $creditrating_control, $repayment_control,$href_control) {
	
	$amount = Math.round($amount / 1000) * 1000;

	$term = Math.round($term);

	var repayment = PMT($amount, $term, $credit_rating);

	var total = Math.round(repayment * $term * 100) / 100;

	var rate = EffectiveRate($term, repayment, $amount, 0.0, 0.02, 0.0000001);

	var apr = APR(rate);
	

	if ($amount_control != null) {

		$amount_control.value = $amount.toFixed(0);

	}

	if ($term_control != null) {

		$term_control.value = YearMonths($term);

	}

	if ($creditrating_control != null) {

		$creditrating_control.value = credit_text[$credit_rating];

	}

	if ($repayment_control != null) {

		$repayment_control.value = "" + repayment.toFixed(0);

		current_repayment = repayment.toFixed(0)	

	}

}

function UpdateFastCalculatorFields($amount, $term, $credit_rating, $amount_control, $term_control, $creditrating_control, $repayment_control, $totalrepayment_control, $effectiverate_control, $apr_control) {

	

	$amount = Math.round($amount / 1000) * 1000;

	$term = Math.round($term);

	

	var repayment = PMT($amount, $term, $credit_rating);

	var total = Math.round(repayment * $term * 100) / 100;



	if ($amount_control != null) {

		$amount_control.innerHTML = "&pound;" + $amount.toFixed(0);

	}

	if ($term_control != null) {

		$term_control.innerHTML = YearMonths($term);

	}

	if ($creditrating_control != null) {

		$creditrating_control.innerHTML = credit_text[$credit_rating];

	}

	if ($repayment_control != null) {

		$repayment_control.innerHTML = "Your repayment = <b>&pound;" + repayment.toFixed(0) + "</b>";

		current_repayment = repayment.toFixed(0)			

	}

	if ($totalrepayment_control != null) {

		$totalrepayment_control.innerHTML = "&pound;" + total.toFixed(2);

	}	

}