/*
todo

ticker / apply
reverse calc
gap / ppp info

*/

document.observe("dom:loaded", function () {

	$$("input").invoke("observe", "keyup", mpu.fillFields.bindAsEventListener());
	$$("select").invoke("observe", "change", mpu.fillFields.bindAsEventListener());
	$$("img.MPUchecker").invoke("observe", "click", mpu.togIns);

	//$("MPUapply").observe("mouseover", function () { this.src = "img/apply-a.gif" });
	//$("MPUapply").observe("mouseout", function () { this.src = "img/apply.gif" });
	//$("MPUapply").observe("click", function () { document.location = "https://www.creditplus.co.uk/apply.html?src=PARKERS" });

	// set up form elements to mirror each other
	mpu.elementMirrors = {
		MPUcredit			: $("MPUreverseCredit"),
		MPUreverseCredit	: $("MPUcredit"),
		MPUterm				: $("MPUreverseTerm"),
		MPUreverseTerm		: $("MPUterm"),
		MPUdeposit			: $("MPUreverseDeposit"),
		MPUreverseDeposit	: $("MPUdeposit"),
		MPUgap				: $("MPUreverseGAP"),
		MPUreverseGAP		: $("MPUgap"),
		MPUppp				: $("MPUreversePPP"),
		MPUreversePPP		: $("MPUppp")
	}

	new Tip($("gaplink"), $("MPUinfoGAP"), {
		title			: 'Guaranteed Asset Protection',
		fixed			: true,
		target			: $("MPUcalcHP"),
		offset			: { x:0, y:4 },
		closeButton		: true,
		showOn			: 'click',
		hideOn			: { element: '.close' }
	});

	new Tip($("ppplink"), $("MPUinfoPPP"), {
		title			: 'Payment Protection',
		fixed			: true,
		target			: $("MPUcalcHP"),
		offset			: { x:0, y:4 },
		closeButton		: true,
		showOn			: 'click',
		hideOn			: { element: '.close' }
	});

	new Tip($("MPUreverseGAPlink"), $("MPUinfoGAP"), {
		title			: 'Guaranteed Asset Protection',
		fixed			: true,
		target			: $("MPUcalcreverse"),
		offset			: { x:0, y:4 },
		closeButton		: true,
		showOn			: 'click',
		hideOn			: { element: '.close' }
	});

	new Tip($("MPUreversePPPlink"), $("MPUinfoPPP"), {
		title			: 'Payment Protection',
		fixed			: true,
		target			: $("MPUcalcreverse"),
		offset			: { x:0, y:4 },
		closeButton		: true,
		showOn			: 'click',
		hideOn			: { element: '.close' }
	});
	mpu.globals.eventHandlers.showNormal()

	Number.prototype.toCurrency = function() {
		// index first portion in array
		var a = this.toString().split(".")[0].replace("-","").toArray();
		// pad and comma it out
		var pad = (!(a.length % 3) || a.length < 3) ? 0 : 3 - (a.length % 3);
		for (var i=0;i<pad;i++) a.unshift(null);
		// append symbol and last portion
		return ((this < 0) ? "-" : "") + "&pound;" + a.inGroupsOf(3).invoke("join","").join(",") + "." + this.toFixed(2).split(".")[1];
	}

	mpu.fillFields();

	// load ticker from remote
	//$("MPUdynamic").src = "http://www.creditplus.co.uk/utils/xsite-getsomedeals.js.asp"

});

var mpu = {
	globals: {
		eventHandlers: {
			showReverse: function () {		// show reverse calc page
				$("calcswitch").innerHTML = "How much per month?";

				// change event handler
				$("calcswitch").stopObserving("click", mpu.globals.eventHandlers.showReverse);
				$("calcswitch").observe("click", mpu.globals.eventHandlers.showNormal);
							
				// hide all other pages
				$$("#MPUcalc table").invoke("setStyle", { display: "none" });
				// show reverse
				$("MPUcalcreverse").setStyle({ display: "block" });
			},
			showNormal: function () {
				$("calcswitch").innerHTML = "How much can I afford?"

				// change event handler
				$("calcswitch").stopObserving("click", mpu.globals.eventHandlers.showNormal)
				$("calcswitch").observe("click", mpu.globals.eventHandlers.showReverse)
							
				// hide all other pages
				$$("#MPUcalc table").invoke("setStyle", { display: "none" });
				// show reverse
				$("MPUcalcHP").setStyle({ display: "block" })
			}
		}
	},
	flashBorder: function (element) {
		element = $(element)
		if (element) { 
			if (element.flashTimer) { clearTimeout(element.flashTimer) }

			if (element.flashCount % 2 != 1) {
				element.style.borderColor = "red"
				element.style.borderStyle = "solid"
			} else {
				element.style.borderColor = ""
				element.style.borderStyle = ""
			}
			
			if (!element.flashCount) {
				element.flashCount = 1	
				element.flashTimer = setTimeout(function () { mpu.flashBorder(element) }, 500)
			} else {
				if (element.flashCount < 5) {
					element.flashCount = element.flashCount +1
					element.flashTimer = setTimeout(function () { mpu.flashBorder(element) }, 500)
				} else {
					element.flashCount = null
					element.flashTimer = null
				}
			}
		}
		return element;
	},
	evaluate: function () {

		fields = {
			base		: parseFloat($F("MPUcredit")) || 0,
			term		: parseInt($F("MPUterm")) || 0,
			amount		: parseFloat($F("MPUprice")) || 0,
			deposit		: parseFloat($F("MPUdeposit")) || 0,
			ppp			: ($("MPUppp").src.indexOf("un") < 0) ? 1 : 0,
			gap			: ($("MPUgap").src.indexOf("un") < 0) ? 1 : 0,
			// reverse stuff
			budget		: parseFloat($F("MPUreverseMonthlyBudget"))
		};

		fields.loanAmount		= fields.amount - fields.deposit;
		fields.interestPA		= (fields.loanAmount/100) * fields.base;
		fields.interestTotal	= fields.interestPA * (fields.term/12);
		fields.totalToPay		= fields.loanAmount + fields.interestTotal;
		fields.monthlyPayment	= fields.totalToPay / fields.term;
		
		fields.pppMonthly		= (fields.ppp) ? (fields.monthlyPayment/100) * 9 : 0;
		fields.gapMonthly		= (fields.gap) ? 250 / fields.term : 0;
		
		fields.totalMonthly		= fields.monthlyPayment + fields.pppMonthly + fields.gapMonthly;
		fields.totalToPayInc	= fields.totalToPay + fields.pppMonthly + fields.gapMonthly;


		// reverse calc don't understand this.. (a description not a direction)
		fields.amountToSpend = (function () {
			var pct = 100 / (fields.base + 100);
			var val = (fields.budget || 0) * fields.term;
			for (var i=0;i<fields.term/12;i++) val = val * pct
			return val;
		})() + fields.deposit;

		if (fields.ppp) fields.amountToSpend -= ((fields.budget / 100) * 9) * fields.term || 0;
		if (fields.gap) fields.amountToSpend -= (250 / fields.term) * fields.term;


		return fields;
	},
	togIns: function () {
		this.src = "http://usedcars.go-motoring.co.uk/images/" + ((this.src.indexOf("un") < 0) ? "uncheck.gif" : "check.gif");
		// mirror this
		var target = mpu.elementMirrors[this.id]
		if (target) target.src = this.src
		
		mpu.fillFields();
	},
	fillFields: function (event) {

		// check for errors and report if present
		var wrong = $$("#mpu input").findAll(function (el) { return !el.length && isNaN($F(el)) });

		if (wrong.length) {
			$("MPUmonthlyGAPPPP").innerHTML			= "";
			$("MPUmonthlyPayment").innerHTML		= "";
			$("MPUtotalToPay").innerHTML			= "";
			$("MPUreverseAmountToSpend").innerHTML	= "";
			
			wrong.each(function (el) { mpu.flashBorder(el) });
			return false;
		}

		// match fields across pages
		if (event && event.element().id) {
			var el = event.element();
			var target = mpu.elementMirrors[el.id];		// get element to mirror to
			if (target) target.value = el.value;		// match values
		}
		
		var data = mpu.evaluate();
		
		
		var tempPppGapMonthy = String(data.pppMonthly + data.gapMonthly);		
		tempPppGapMonthy = tempPppGapMonthy.substring(0, tempPppGapMonthy.indexOf('.')+3);		
		tempPppGapMonthy = "&pound;" + tempPppGapMonthy;
		
		var tempTotalMonthly = String(data.totalMonthly);
		tempTotalMonthly = tempTotalMonthly.substring(0, tempTotalMonthly.indexOf('.')+3);		
		tempTotalMonthly = "&pound;" + tempTotalMonthly;		
		
		var tempTotalToPayInc = String(data.totalToPayInc);
		tempTotalToPayInc = tempTotalToPayInc.substring(0, tempTotalToPayInc.indexOf('.')+3);		
		tempTotalToPayInc = "&pound;" + tempTotalToPayInc;	
		
		var tempAmountToSpend = String(data.amountToSpend);
		tempAmountToSpend = tempAmountToSpend.substring(0, tempAmountToSpend.indexOf('.')+3);		
		tempAmountToSpend = "&pound;" + tempAmountToSpend;	

		// output
		$("MPUxMonthlyPayments").innerHTML		= data.term + " Monthly Payments of:";
		$("MPUmonthlyGAPPPP").innerHTML			= tempPppGapMonthy;
		$("MPUmonthlyPayment").innerHTML		= tempTotalMonthly;
		$("MPUtotalToPay").innerHTML			= tempTotalToPayInc;
		$("MPUreverseAmountToSpend").innerHTML	= tempAmountToSpend;
	},
	cpTicker: function (timer) {
		var randomnumber=Math.floor(Math.random()*20) + 1
		for (var i=1; i<=20; i++) {
			setTimeout(function(i,randomnumber) {	
				if (!$("s" + i)) return false	// short out if nutty
				if (i==randomnumber) {
					var myText = new TypingText(document.getElementById("s" + i),60,"_", mpu.cpTicker.bind(this,4500));
					myText.run();
					$("s" + i).style.display = "inline"
				}
				else {
					$("s" + i).style.display = "none"
				}
			}.bind(this,i,randomnumber),timer)
		}
	}
};