$(function() {		
	function calculate($event) {
		$event.preventDefault();
		this.clearOutput();
		this.opening = [];
		this.repayment = [];
		this.interest = [];
		this.closing = [];
		this.balance = parseFloat($("#how_much").val());
		this.currentApr = parseFloat($("#current_apr").val());
		if (isNaN(this.balance) || isNaN(this.currentApr) || this.balance <= 0) {
			this.showInputError();
			return false;
		}
		if(this.balance > 20000)
		{
			showBalanceTooHighError();
			return false;
		}
		
		this.apr = this.currentApr / 100;
		this.air = ((Math.pow(this.apr + 1, (1 / 12))) - 1) * 12;
		this.mir = this.air / 12;
		this.closing[-1] = this.balance;
		this.currentSaving = 0;
		for (var i = 0; i < this.months; i++) {
			this.opening[i] = this.closing[i - 1];
			this.repayment[i] = -(Math.max(this.minimumPayment, this.opening[i] * this.minimumRate));
			this.interest[i] = this.opening[i] * this.mir;
			this.closing[i] = this.opening[i] + this.repayment[i] + this.interest[i];
			this.currentSaving += this.interest[i];
		}
		$("#output").text("You could save £" 
						  + Math.max(this.currentSaving, 0).toFixed(2)
						  + " over twelve months if you transfer your balance to the ASDA Reward Credit Card™ (This does not include your Balance Transfer handling fee of 2.99%)*");
		return false;
	}
	
	function showInputError() {
		$("#output").text("Please enter your existing rate and the amount you wish to transfer");
	}
	
	function showBalanceTooHighError()
	{
		$("#output").text("Please enter a lower balance transfer amount");
	}
	
	function clearOutput() {
		$("#output").text(String.fromCharCode(160));
	}
	
	var Calculator = {
		// properties: default values
		months: 12,
		minimumPayment: 5,
		minimumRate: 0.03,
		// user input
		balance: 0,
		currentApr: 0,
		// working values
		apr: 0,
		air: 0,
		mir: 0,
		opening: [],
		repayment: [],
		interest: [],
		closing: [],
		// methods
		calculate: calculate,
		showInputError: showInputError,
		clearOutput: clearOutput
	};
	
	function go($event) {
		Calculator.calculate($event);
	}
	
	$("#calculate").click(go);
	
	$("#calculator").submit(go)
	
	Calculator.clearOutput();
});