// <![CDATA[
var out = false;
var transition = false;

Event.observe(window, "load", function() {
	
	var mortgageExpanderElement = $('mortgage-expander');
	var mortgageCalculationsElement = $('mortgage-calculations');
	
	$("panel-control").onclick = function() {
		if (!out) {
			slideIn();
		} else {
			calculate();
		}
		return false;
	}
	
	$("panel-controller").onclick = function() {
		if (out) {
			slideOut();
			this.addClassName("show-panel");
			this.removeClassName("hide-panel");
		} else {
			slideIn();
			this.addClassName("hide-panel");
			this.removeClassName("show-panel");
		}
		return false;
	}				
});

function slideIn() {
	calculate();
	if (transition) {
		return;
	}
	
	transition = true;
	new Effect.Morph	("mortgage-expander", {
		style: { width: '750px' },
		/* style: { width: '450px' },  */
		duration: 1.5,
		afterFinish: function() {
			transition = false;
			out = true;
		}				
	});
}

function slideOut() {
	if (transition) {	
		return;
	}

	transition = true;
	new Effect.Morph("mortgage-expander", {
		style: { width: '144px' },					
		duration: 1.5,
		afterFinish: function() {
			transition = false;
			out = false;
		}
	});
}

function calculate() {
	var amount = $("amount").value.replace(",","");
	
	//This next line uses selectedIndex to work in IE, however cos the dropdown starts at 5 
	//it has to be offset by 5 - Tom 20th May 2008
	var period = $("period").selectedIndex + 5;
	var rate = $("rate").value;
	var interestOnly;
	var repaymentOnly;
	var numberOfPayments = period * 12;
	var monthlyInterestRate = rate / 1200;
	var r = Math.pow(1 + monthlyInterestRate, numberOfPayments);
	interestOnly = amount * monthlyInterestRate;
	
	repaymentOnly = Math.abs((amount * r) / ((1 + monthlyInterestRate * 0) * (1 - r) / monthlyInterestRate)); 
					
	$("interest-only").innerHTML = "<strong>Interest Only / m:</strong> &pound;" + interestOnly.toFixed(2);
	$("repayment-only").innerHTML = "<strong>Repayment Only / m:</strong> &pound;" + repaymentOnly.toFixed(2);
}
// ]]>