/**
 * Last Edit
 * By	:	Jason
 * When	:	23 May 08
 * What	:	Initial setup
 */
$(document).ready(function(){
	$("#menu ul.nav").superfish();
	if (!$('body#page3').length) {
		$("#new_car_menu ul.nav").superfish();	
	}
	$("ul.nav li").each(function() {
		if($(this).children('ul').length) {
			$(this).addClass('has_children');
		}
	});
	$('#used-car-tools>div').hide();
	$('#used-car-tools>h2').click(function () {
		$('#used-car-tools>div').not(':hidden').slideUp();
		$(this).next().slideDown();
	});
	$('#t-a-f>div').hide();
	$('#t-a-f>h2').click(function () {
		$('#t-a-f>div').not(':hidden').slideUp();
		$(this).next().slideDown();
	});
	$('#calculator_form').submit(function(){
	process_calculator_form();
	return false;
	});
	
});

// JavaScript Document

calculate_payment = function(p,r,m) {	
	return (p*(r/12)) / (1-(Math.pow((1+(r/12)),-m)))
}

roundTo = function (base,precision) {
	var m = Math.pow(10, precision);
	var a = Math.round(base * m) /m;
	return a;
}
function formatTo(base,precision) {

	var a = roundTo(base,precision);
	var s = a.toString();
	
	var decomalIndex = s.indexOf(".");
	if (precision > 0 && decimalIndex < 0) {
		decimalIndex = s.length;
		s += '.';
	}
	while (decimalIndex + precision + 1 > s.length) {
		s += '0';	
	}
	return s;
}

process_calculator_form = function() {

	var theForm = document.forms["calculator_form"];
	var amount = parseInt(theForm['amount'].value.replace(/^\$+/,""));
	var intrest = parseInt(theForm['intrest'].value.replace(/%$/,""));
	var length = parseInt(theForm['length'].value);
	var repayment = 0;
	var calculate = true;
	
	if (isNaN(amount) || amount < 1) {
		alert('The amount field must be a dollar value');	
		calculate = false;
	}
	if (isNaN(intrest) || intrest < 0.1 || intrest > 100) {
		if (calculate) alert('The intrest field must be a percent value');	
		calculate = false;
	}
	if (isNaN(length) || length < 1) {
		if (calculate) alert('Please enter the length, in number of months');	
		calculate = false;	
	}
	
	if (calculate) {
		repayment = roundTo(calculate_payment(amount,(intrest/100),length),2);
		theForm['repayment'].value = '$' + repayment;
	}
	
	

}

/*
// cusomisation options listed here, if you need them
$(document).ready(function(){
	$("ul.nav").superfish({
		hoverClass	: "sfHover",
		pathClass	: "overideThisToUse",
		delay		: 800,
		animation	: {opacity:"show"},
		speed		: "normal",
		oldJquery	: false, // set to true if using jQuery version below 1.2 
		disableHI	: false, // set to true to disable hoverIntent detection 
		onInit		: function(){},
		onBeforeShow	: function(){},
		onShow		: function(){},
		onHide		: function(){}
	});
});
*/
