// Full Magilla Calculator

// requires ajax, server script, and PEAR module for rate() function


var inc = ['core', 'event', 'cook', 'dom', 'slide'];

for (i = 0;  i < inc.length;  i++)
	document.writeln('<script type="text/javascript" src="_js/js/x/x_'+inc[i]+'.js"><'+'/script>');


var wizName = 'Auto Loan Calculator';

var steps = 5, step = 1;
var mod = false;
var qStr, lead_id;
var cWidth = 530;

var colors = {'bgRO': '#f5efe0', 'bgAct': '#FFF', 
	'aOn': '#cd5f15', 'aOff': '#315e91', 
	'borderRO': '#cbcac8', 'borderAct': '#999'};

var vals = {};

var ff = [ [], 
	['inc_salary', 'inc_other', 'inc_total', 'exp_rent', 'exp_edu', 'exp_ccard', 'exp_food', 'exp_ent', 'exp_child', 'exp_other', 'exp_total', 'inc_disc', 'auto_ins', 'auto_gas', 'auto_maint', 'auto_total', 'max_auto_paymt', 'pct_income'],

	['base_rate', 'loan_type', 'type_incrmnt', 'type_newrate', 'loan_term', 'term_incrmnt', 'term_newrate', 'fico_band', 'fico_incrmnt', 'fico_newrate', 'state', 'state_incrmnt', 'state_newrate'],

	['lsize_rate', 'lsize_paymt', 'lsize_term', 'lsize_amt', 'total_paymts', 'total_intpaid', 'solve_rate', 'solve_paymt', 'solve_term', 'solve_amt', 'total_paymts2', 'total_intpaid2', 'intpaid_diff'],

	['car_loan_amt', 'car_tradein', 'car_tradeinval', 'car_stillowed', 'car_incentives', 'car_downpaymt', 'car_proceeds', 'car_opts', 'car_fees', 'car_tax', 'car_tax_calc', 'car_dmv', 'car_dmv_calc', 'car_other', 'car_costs', 'car_avail'],

	['sum_income', 'sum_exp', 'sum_disc', 'sum_auto', 'sum_paymt', 'sum_pct', 'sum_base', 'sum_type_inc', 'sum_term_inc', 'sum_fico_inc', 'sum_state_inc', 'sum_rate', 'sum_term', 'sum_loanamt', 'sum_proceeds', 'sum_costs', 'sum_avail'] ];


var solveEls = ['rate', 'paymt', 'term', 'amt'];
var solveFor = 'amt';




// in case debugging is turned off...

function myOnLog(msg, clear) {
	msg = msg.substring(0,64);
	window.status = msg;
	setTimeout('window.status="";', 2000);
}



function initExtra() {
	f = document.mainForm;
	//f['inc_salary'].onblur = "calc(1)";
	
	qsSetup();
	
	for (n in init_vals) {
		setVal(n, init_vals[n]);
	}
	
	slideSetup();
	
	calc1(1);
	calc2(1);
	
	//xGetElementById('a_rate').style.color = '#999';
	
	lead_id = f['lead_id'].value;
	
	f['inc_salary'].select();
}





// quick way of accumulating values from form fields
//  (turns out I don't use it that much)

function sum(nstr) {
	var i, n, unknown = '', total = 0;
	var names = nstr.split(', ');
	for (i = 0;  i < names.length;  i++) {
		n = names[i];
		if (typeof f[n] != 'object') 
			unknown += n + "\n";
		else 
			total += num(f[n].value);
	}
	if (unknown != '') 
		alert("unknown:\n" + unknown);
	return total;
}






function calc1(reset) {
	
	var ffs = ff[1];  // form fields for 1st calc
	
	var i, n;
	for (i = 0;  i < ffs.length;  i++) {
		n = ffs[i];

		if (n == 'pct_income') {
			vals[n] = (reset) ? 0 : pct(f[n].value);
			f[n].value = usd(vals[n]);
		
		} else {
			vals[n] = (reset) ? ((typeof init_vals[n] != 'undefined') ? init_vals[n] : 0) : dec(f[n].value);
			f[n].value = numc(vals[n]);
		}
	}
	
	vals['inc_total'] = sum('inc_salary, inc_other');
	f['inc_total'].value = numc(vals['inc_total']);
	
	vals['exp_total'] = sum('exp_rent, exp_edu, exp_ccard, exp_food, exp_ent, exp_child, exp_other');
	f['exp_total'].value = numc(vals['exp_total']);
	
	vals['inc_disc'] = vals['inc_total'] - vals['exp_total'];
	f['inc_disc'].value = numc(vals['inc_disc']);

	vals['auto_total'] = sum('auto_ins, auto_gas, auto_maint');
	f['auto_total'].value = numc(vals['auto_total']);
	
	vals['max_auto_paymt'] = (!vals['inc_disc']) ? 0 : vals['inc_disc'] - vals['auto_total'];
	f['max_auto_paymt'].value = numc(vals['max_auto_paymt']);
	
	vals['pct_income'] = (!vals['inc_total']) ? 0 : dec(100 * (vals['max_auto_paymt'] / vals['inc_total']), 2);
	f['pct_income'].value = usd(vals['pct_income']);
	
	if (reset) {
		//f['inc_salary'].focus();
		f['inc_salary'].select();
	}
	
	// kick values forward to other calcs
	vals['lsize_paymt'] = vals['max_auto_paymt'];
	f['lsize_paymt'].value = numc(vals['lsize_paymt']);
	
	return vals['pct_income'];
}






function calc2(reset) {
	var x, y, inc, rate;

	if (reset) {
		var ffs = ff[2];  // form fields for 2nd calc
		
		var i, n;
		for (i = 0;  i < ffs.length;  i++) {
			n = ffs[i];
			
			if (f[n].type == 'select-one') {
				setVal(n, '');
			
			} else {
				f[n].value = usd(0);
			}
		}
	}
	rate = init_vals['base_rate'];
	f['base_rate'].value = usd(rate);

	
	y = val('loan_type');
	vals['loan_type'] = y;
	vals['loan_type_txt'] = numbers['loan_types'][y];
	
	x = val('loan_term');
	vals['loan_term'] = y;
	vals['loan_term_txt'] = numbers['loan_terms'][x];
	//if (!x || !y) return;
	
	inc = (y == '') ? 0 : pct(numbers['loan_rates'][y][1] - rate);
	
	f['type_incrmnt'].value = usd(inc);
	rate = rate + inc;
	f['type_newrate'].value = usd(rate);

	//myOnLog('inc: '+ inc +' ('+ typeof inc +')\nrate: '+ rate +' ('+ typeof rate +')\n');
	
	inc = (x == '' && y == '') ? 0 : pct(numbers['loan_rates'][y][x] - rate);
	
	f['term_incrmnt'].value = usd(inc);
	rate = rate + inc;
	f['term_newrate'].value = usd(rate);

	//myOnLog('inc: '+ inc +' ('+ typeof inc +')\nrate: '+ rate +' ('+ typeof rate +')\n');
	
	
	x = val('fico_band');
	inc = (x == '') ? 0 : pct(numbers['fico_rates']['National Average'][x]);
	
	f['fico_incrmnt'].value = usd(inc);
	rate = rate + inc;
	f['fico_newrate'].value = usd(rate);

	//myOnLog('inc: '+ inc +' ('+ typeof inc +')\nrate: '+ rate +' ('+ typeof rate +')\n');
	
	
	y = val('state');
	vals['state'] = y;
	inc = (y == '') ? 0 : pct(numbers['fico_rates'][y][x]);

	f['state_incrmnt'].value = usd(inc);
	rate = rate + inc;
	f['state_newrate'].value = usd(rate);
	vals['state_newrate'] = rate;

	//myOnLog('inc: '+ inc +' ('+ typeof inc +')\nrate: '+ rate +' ('+ typeof rate +')\n');
	vals['rate'] = rate;


	// kick values forward to other calcs
	vals['lsize_rate'] = pct(vals['rate']);
	f['lsize_rate'].value = usd(vals['lsize_rate']);
	
	var lt = parseInt(vals['loan_term_txt']);
	if (!isNaN(lt)) {
		vals['lsize_term'] = vals['term'] = lt;
		f['lsize_term'].value = lt;
	}
	return rate;
}



function valValid(varName) {
	return (typeof vals[varName] != 'undefined' && vals[varName] > 0);
}


function calc3(reset) {
	
	var ffs = ff[3];  // form fields for 3rd calc
	
	// check that we have the vals we need from previous calcs

	if (!valValid('lsize_paymt')) {
		alert('You need to complete the Loan Payment calculator before starting this one.');
		goTo(1);
		return false;
	}
	if (!valValid('lsize_term') || !valValid('state_newrate')) {
		alert('You need to complete the Interest Rate calculator before starting this one.');
		goTo(2);
		return false;
	}
	
	
	if (reset) {
		vals['lsize_paymt'] = vals['max_auto_paymt'];
		f['lsize_paymt'].value = numc(vals['lsize_paymt']);

		vals['lsize_rate'] = pct(vals['rate']);
		f['lsize_rate'].value = usd(vals['lsize_rate']);
	
		vals['lsize_term'] = parseInt(vals['loan_term_txt']);
		vals['term'] = vals['lsize_term'];
		f['lsize_term'].value = vals['lsize_term'];
	}
	

	
	// now do the calculations based on above values
	
	vals['lsize_amt'] = -presentValue(vals['lsize_rate'] / 1200, vals['lsize_term'], vals['lsize_paymt']);
	f['lsize_amt'].value = numc(vals['lsize_amt']);
	
	
	vals['total_paymts'] = -futureValue(vals['lsize_rate'] / 1200, vals['lsize_term'], vals['lsize_paymt']);
	f['total_paymts'].value = numc(vals['total_paymts']);
	
	
	vals['total_intpaid'] = vals['total_paymts'] - vals['lsize_amt'];
	f['total_intpaid'].value = numc(vals['total_intpaid']);


	//if (reset || !valValid('solve_amt')) {
		resetSolved();
	//}
	chooseSolveVar(solveFor);



	return vals['lsize_amt'];
}



function newSolveVals() {
	vals['solve_rate'] = pct(f['solve_rate'].value);
	f['solve_rate'].value = usd(vals['solve_rate']);
	
	vals['solve_paymt'] = dec(f['solve_paymt'].value);
	f['solve_paymt'].value = numc(vals['solve_paymt']);

	vals['solve_term'] = dec(f['solve_term'].value);
	f['solve_term'].value = vals['solve_term'];

	vals['solve_amt'] = dec(f['solve_amt'].value);
	f['solve_amt'].value = numc(vals['solve_amt']);

	return false;
}



function c3dh(on) {
	if (on) {
		xShow('calc3dh');
		if (!valValid('solve_rate')) {
			resetSolved();
			chooseSolveVar(solveFor);
		}
	} else {
		xHide('calc3dh');
	}
	return false;
}



function resetSolved() {
	vals['solve_rate'] = vals['lsize_rate'];
	f['solve_rate'].value = usd(vals['solve_rate']);
	
	vals['solve_paymt'] = vals['lsize_paymt'];
	f['solve_paymt'].value = numc(vals['solve_paymt']);

	vals['solve_term'] = vals['lsize_term'];
	f['solve_term'].value = vals['solve_term'];

	vals['solve_amt'] = vals['lsize_amt'];
	f['solve_amt'].value = numc(vals['solve_amt']);
	
	
	vals['total_paymts2'] = vals['total_paymts'];
	f['total_paymts2'].value = numc(vals['total_paymts']);

	vals['total_intpaid2'] = vals['total_intpaid'];
	f['total_intpaid2'].value = numc(vals['total_intpaid']);

	vals['intpaid_diff'] = 0;
	f['intpaid_diff'].value = 0;

	return false;
}









function chooseSolveVar(param) {
	var e, varName, hi = false;
	
	for (var i = 0;  i < solveEls.length;  i++) {
		e = solveEls[i];
		varName = 'solve_'+e;
		
		//if (e == param && e != 'rate') {
		if (e == param) {
			xGetElementById('a_'+e).style.color = colors['aOn'];
			ffProtect(varName, 1);
		} else {
			//xGetElementById('a_'+e).style.color = (e == 'rate') ? '#999' : colors['aOff'];
			xGetElementById('a_'+e).style.color = colors['aOff'];
			ffProtect(varName, 0);
			if (!hi && !f[varName].readOnly) {
				//f[varName].select();
				hi = true;
			}
		}
	}
	solveFor = param;
	myOnLog('solveFor: ' + solveFor);
	return param;
}






function chooseNums(set) {
	if (set == 'new') {
	} else {
	}
	return set;
}









// the one trick here is that rate() requires an ajax call, 
//  so can't just call a function to return a result.
//  Need to call it once to trigger getting the value,
//   then call again once value arrives

function c3solve(param, value) {
	
	// pick up new values from form fields
	if (arguments.length < 2) 
		newSolveVals();
	
	
	if (solveFor == 'rate') {
		if (arguments.length < 2) {
			rate(vals['solve_term'], -vals['solve_paymt'], vals['solve_amt']);
			return false;
		} else {
			vals['solve_rate'] = pct(1200 * value);
			f['solve_rate'].value = usd(vals['solve_rate']);
		}
	
	} else if (solveFor == 'paymt') {
		vals['solve_paymt'] = dec(-payment(vals['solve_rate'] / 1200, vals['solve_term'], vals['solve_amt']));
		f['solve_paymt'].value = numc(vals['solve_paymt']);

	
	} else if (solveFor == 'term') {
		vals['solve_term'] = dec(periods(vals['solve_rate'] / 1200, -vals['solve_paymt'], vals['solve_amt']));
		f['solve_term'].value = numc(vals['solve_term']);
		
	
	} else if (solveFor == 'amt') {
		vals['solve_amt'] = dec(-presentValue(vals['solve_rate'] / 1200, vals['solve_term'], vals['solve_paymt']));
		f['solve_amt'].value = numc(vals['solve_amt']);
		
	
	} else if (solveFor == 'fv') {
		vals['total_paymts2'] = dec(-futureValue(vals['solve_rate'] / 1200, vals['solve_term'], vals['solve_paymt'], vals['solve_amt']));
		f['total_paymts2'].value = numc(vals['total_paymts2']);
	}

	
	if (solveFor != 'fv') {
		vals['total_paymts2'] = dec(-futureValue(vals['solve_rate'] / 1200, vals['solve_term'], vals['solve_paymt']));
		f['total_paymts2'].value = numc(vals['total_paymts2']);
	}
	
	vals['total_intpaid2'] = vals['total_paymts2'] - vals['solve_amt'];
	f['total_intpaid2'].value = numc(vals['total_intpaid2']);
	
	
	vals['intpaid_diff'] = vals['total_intpaid2'] - vals['total_intpaid'];
	f['intpaid_diff'].value = numc(vals['intpaid_diff']);
	
	var spanEl = xGetElementById('ipDiff');
	spanEl.innerHTML = (vals['intpaid_diff'] < 0) ? 'Decrease' : 'Increase';
	
	return vals['intpaid_diff'];
}






function ffProtect(varName, on) {
	//var el = xGetElementById('ff_'+varName);
	var el = f[varName];
	if (typeof el != 'object') 
		return -1;
	
	if (on) {
		el.style.backgroundColor = colors['bgRO'];
		el.style.borderColor = colors['borderRO'];
		el.readOnly = true;
	
	} else {
		el.style.backgroundColor = colors['bgAct'];
		el.style.borderColor = colors['borderAct'];
		el.readOnly = false;
	}
	return on;
}










function calc4(reset) {
	
	var ffs = ff[4];  // form fields for 4th calc
	
	if (!valValid('lsize_paymt')) {
		alert('You need to complete the Loan Payment calculator before starting this one.');
		goTo(1);
		return false;
	}
	if (!valValid('lsize_term') || !valValid('state_newrate')) {
		alert('You need to complete the Interest Rate calculator before starting this one.');
		goTo(2);
		return false;
	}
	if (!valValid('lsize_amt')) {
		alert('You need to complete the Loan Principal calculator before starting this one.');
		goTo(3);
		return false;
	}

	vals['car_loan_amt'] = vals['lsize_amt'];
	f['car_loan_amt'].value = numc(vals['car_loan_amt']);
	
	var i, n;
	for (i = 0;  i < ffs.length;  i++) {
		n = ffs[i];
		if (typeof f[n] == 'object' && !f[n].readOnly) {
			f[n].value = (reset == '1') ? 0 : numc(f[n].value);
			//f[n].value = 0;
		}
	}
	
	
	vals['car_tradein'] = pct(f['car_tradeinval'].value) - pct(f['car_stillowed'].value);
	f['car_tradein'].value = numc(vals['car_tradein']);
	
	vals['car_proceeds'] = sum('car_loan_amt, car_tradein, car_incentives, car_downpaymt');
	f['car_proceeds'].value = numc(vals['car_proceeds']);
	
	
	
	vals['tax_rate'] = numbers['tax_rates'][vals['state']];
	
	var el = xGetElementById('car_tax_span');
	el.innerHTML = '(' + vals['state'] + ' = ' + usd(vals['tax_rate']) + '%)';

	vals['car_tax_calc'] = vals['car_proceeds'] * (vals['tax_rate'] / 100);
	f['car_tax_calc'].value = numc(vals['car_tax_calc']);

	
	
	vals['dmv_rate'] = 1.3;
	el = xGetElementById('car_dmv_span');
	el.innerHTML = '(' + usd(vals['dmv_rate']) + '%)';
	
	vals['car_dmv_calc'] = vals['car_proceeds'] * (vals['dmv_rate'] / 100);
	f['car_dmv_calc'].value = numc(vals['car_dmv_calc']);



	vals['car_costs'] = sum('car_opts, car_fees, car_tax_calc, car_dmv_calc');
	f['car_costs'].value = numc(vals['car_costs']);


	vals['car_avail'] = vals['car_proceeds'] - vals['car_costs'];
	f['car_avail'].value = numc(vals['car_avail']);

	
	return vals['car_avail'];
}






function calc5(reset) {
	
	f['sum_income'].value    = numc(vals['inc_total']);
	f['sum_exp'].value       = numc(vals['exp_total']);
	f['sum_disc'].value      = numc(vals['inc_disc']);
	f['sum_auto'].value      = numc(vals['auto_total']);
	
	f['sum_paymt'].value     = numc(vals['max_auto_paymt']);
	f['sum_pct'].value       =  usd(vals['pct_income']);
	
	f['sum_base'].value      =  usd(f['base_rate'].value);
	f['sum_type_inc'].value  =  usd(f['type_incrmnt'].value);
	f['sum_term_inc'].value  =  usd(f['term_incrmnt'].value);
	f['sum_fico_inc'].value  =  usd(f['fico_incrmnt'].value);
	f['sum_state_inc'].value =  usd(f['state_incrmnt'].value);

	f['sum_rate'].value      =  usd(vals['lsize_rate']);
	f['sum_term'].value      =  numc(vals['lsize_term']);
	f['sum_loanamt'].value   =  numc(vals['lsize_amt']);
	
	f['sum_proceeds'].value  = numc(vals['car_proceeds']);
	f['sum_costs'].value     = numc(vals['car_costs']);
	f['sum_avail'].value     = numc(vals['car_avail']);
	
	return false;
}






function calc6(reset) {
	return false;
}







function qsSetup() {
	//window.focus();
	
	qStr = location.search.substring(1);
	
	if (qStr.indexOf('=') != -1) {
		var vars = qStr.split('&');
		var tmp, v;
		for (var i = 0;  (v = vars[i]);  i++) {
			tmp = v.split('=');
			f[tmp[0]].value = tmp[1];
		}
	}
	//f['lead_id'].value = ''; // lead_id = xGetCookie('lead_id');
}



function slideSetup() {
	for (var i = 1;  i <= steps;  i++) {
		xMoveTo('step'+ i, 0, 0);  // cWidth, 0);
		xHide('step'+ i);
	}
	//xMoveTo('step'+ step, 0, 0);
	
	xShow('step'+ step);
}




function goTo(s) {
	if (step == s)
		return;
	
	if (s == 6) {
/*	
		if (confirm('Are you sure you want to close the Auto Loan Calculator?')) {
			ax_log('GQ');
			setTimeout('window.close()', 200);
		} else {
			ax_log('GQCANCEL');
		}
*/

		if (!is_popup || typeof(is_popup) != 'object') {		
			window.location = 'quotestep1.html';
		} else {
			if (!is_popup.closed) {
				opener.location = 'quotestep1.html';
			} else {
				window.open('quotestep1.html','_blank');
			}
			setTimeout('window.close()', 400);
		}
			
		return false;
	}
	
	if (step > s) {
		backTo(s);
		return;
	}
	xSlideTo('step'+ step, -1 * cWidth, 0, 400);
	setTimeout("xHide('step"+ step +"')", 400);
	
	step = s;
	xMoveTo('step'+ step, cWidth, 0);
	xShow('step'+ step);
	xSlideTo('step'+ step, 0, 0, 500);
	mod = true;
	
	if (s > 2) {
		var foo = eval('calc'+s);
		foo();
	}
	ax_log(s);
}



function backTo(s) {
	xSlideTo('step'+ step, cWidth, 0, 400);
	setTimeout("xHide('step"+ step +"')", 400);
	
	step = s;
	xMoveTo('step'+ step, -1 * cWidth, 0);
	xShow('step'+ step);
	xSlideTo('step'+ step, 0, 0, 400);
	//updateStat();
	mod = true;

	if (s > 2) {
		var foo = eval('calc'+s);
		foo();
	}
	ax_log(s);
}






function ax_log(step) {
	//var params = 'tag=' + lead_id;
	var params = 'tag=' + f['lead_id'].value;
	params += '&p=' + page_name;
	params += '&u=' + page_uniqid;
	params += '&e=CALC_' + step;
	params += '&i=';

	var x = new ajax();
	x.onComplete = whaddayawantmetodo;
	x.submit('_log.php', params);
}

function whaddayawantmetodo(txt, xml) {
	//alert('ax_log: ' + txt);
	return true;
}






// invoked by zip text element keyup, and possibly form onsubmit in case of error

var lastZip;

function loadCityState(zip) {
	zip += '';
	zip = zip.replace(/\D/g, "");
	
	if (!zip.match(/^\d{5}$/)) return;
	
	if (zip != lastZip || f['state'].value == '') {
		lastZip = zip;
		
		var params = 'z=' + zip;

		var x = new ajax();
		x.onComplete = enterCityState;
		x.submit('_zip.php', params);
	}
}

function enterCityState(msg, xml) {
	var resObj, dataObj;
	
	if (msg.substring(0,2) != '{ ') {
		alert('problems with loadCityState');
		return;
	}
	eval('resObj = ' + msg + ';');
	
	with (resObj) {
		if (err != 0) {
			alert(msg);
		
		} else {
			setVal('state', res['state']);
			f['city'].value  = res['city'];
			document.getElementById('citySpan').innerHTML  = res['city'];
			document.getElementById('stateSpan').innerHTML = ', ' + res['state'];
		}
	}
}





