var stages=new Array();
stages[1] = new Array('a1personal', 'a1employment', 'a1financial'); // applicant 1
stages[2] = new Array('a2personal', 'a2employment', 'a2financial'); // applicant 2

var applicant=1;
var stage=0;
/* temp */
//stage=2;

var this_applicant;
var other_applicant;

var a1age=0;
var a2age=0;
var aid;

function declare(c)
{
	if(!c.checked)
		return false;
	var msg;
	
	msg ='Declaration and credit check authorisation\n\n';
	msg+='Each Applicant, by signing below agrees with Motor Trade Finances Ltd (MTF) and acknowledges as follows:\n'
	msg+='1. MTF may disclose to a credit reporting agency any personal information about me that MTF holds including; information contained in this application; my identification;';
	msg+='the amount of credit applied for; payments which may become overdue; advice that payments are no longer overdue; any serious infringement which MTF believes I ';
	msg+='have committed. That MTF in assessing this application, any later request for a credit limit increase and monitoring my credit status may obtain from a credit reporting ';
	msg+='agency personal credit information about me including credit reports containing information about my commercial activities or commercial credit worthiness. MTF ';
	msg+='may give to and obtain from any third party, information about my personal or commercial credit arrangements including information about my credit worthiness, credit ';
	msg+='standing, credit history or credit capacity for the particular purpose for which the information is required.\n';
	msg+='2. Under the Privacy Act 1993, I have rights of access to, or correction of, any personal information about me held by MTF.\n';
	msg+='3. I have never been subject to any bankruptcy proceedings nor have I entered into any arrangement with my creditors.';
	msg+='4. I understand my application may not receive full consideration unless I supply all information requested.\n';
	msg+='5. I declare the information provided in this application is true and correct, that I am over the age of 18 years and that I have read and understood these terms.';
	if(confirm(msg))
		return true;
	return false;
}

function form_init()
{
	this_applicant = 'applicant' + applicant;
	other_applicant = 'applicant' + (parseInt((applicant % 2))+1).toString();
//	alert(other_applicant);
	// hide eveything
	el(other_applicant).style.display='none';
	el('attempt').style.display='none';

	for(var i=0;i<3;i++)
	{
		el(stages[1][i]).style.display='none';
		el(stages[2][i]).style.display='none';
	}
	// show title and first stage for current applicant
	el(this_applicant).style.display='';
	el(stages[applicant][stage]).style.display='';

	update_buttons();
	fcalc(1);
	fcalc(2);
}

window.onload = form_init;

function prev()
{
	if(applicant==1 && stage==0)
		return;

	el(stages[applicant][stage]).style.display='none';

	if(applicant==2 && stage==0)
	{
		applicant=1;
		stage=3;
	}

	--stage;
	el(stages[applicant][stage]).style.display='';
	update_buttons();
}

function next()
{
	if(applicant==2 && stage==2)
		return;

	if(!validate(false))
		return;

	el(stages[applicant][stage]).style.display='none';

	if(applicant==1 && stage==2)
	{
		applicant=2;
		stage=-1;
	}

	++stage;
	el(stages[applicant][stage]).style.display='';
	update_buttons();
}

/* update prev and next buttons visibility */
function update_buttons()
{
	this_applicant = 'applicant' + applicant;
	other_applicant = 'applicant' + (parseInt((applicant % 2))+1).toString();

	//el('btn_prev').style.display='';
	el('btn_next').style.display='';
	el('attempt').style.display='none';

	if(stage==0 && applicant==1)
	{
		//el('btn_prev').style.display='none';
	}
	if(stage==2 && applicant==2)
	{
		el('btn_next').style.display='none';
		el('attempt').style.display='';
	}
	if(stage==2 && applicant==1 && a1age >= 18)
	{
		el('btn_next').style.display='none';
		el('attempt').style.display='';
	}
	el(this_applicant).style.display='';
	el(other_applicant).style.display='none';
}

/* update the global age variables for currently active applicant */
function doage()
{
	var y,m,d;
	if(applicant==1)
	{
		d = el('a1dob_d').value;
		m = el('a1dob_m').value;
		y = el('a1dob_y').value;
		a1age=age(y,m,d);
		el('a1age').value=a1age;
	}
	else
	{
		d = el('a2dob_d').value;
		m = el('a2dob_m').value;
		y = el('a2dob_y').value;
		a2age=age(y,m,d);		
		el('a2age').value=a2age;
	}
}

/* return current age, given date of birth */
function age(y,m,d)
{
	if(	y=='' ||
		m=='' ||
		d=='')
		return '';

	var now=new Date();
	var yt = now.getFullYear();
	var mt = now.getMonth() + 1;
	var dt = now.getDate();

/*	alert(y +'-'+ m +'-'+ d);
	alert(yt +'-'+ mt +'-'+ dt);
*/
	if ((mt > m) ||
        ((mt == m) &&
         (dt >= d)))
      return yt - y;
    else
      return yt - y - 1;
}
/* function checkdaysformonth()
 * 
 * Make sure you can't select weird dates like 30-feb or 29-feb-1999
 * by hiding those days depending on month / leap year.
 */
function checkdaysformonth()
{
	var pre; /* id prefix depending on active applicant */
	if(applicant==1)
		pre = 'a1';
	else
		pre = 'a2';


	var daybox = el(pre + 'dob_d');
	var monthbox = el(pre + 'dob_m');
	var yearbox = el(pre + 'dob_y');
	var day = parseInt(daybox.value, 10);
	if(isNaN(day))
		day=1;
	var month = parseInt(monthbox.value, 10);
	var year = parseInt(yearbox.value, 10);
	var max=31;

	var leap=false;
//	alert(day +'-'+ month +'-'+ year);
	switch(month)
	{
		case 2:
			if(year % 4 == 0)
				leap=true;
			if (year % 100 == 0 && year % 400 != 0)
				leap = false;
			if(leap) // if it's a leap year
				max = 29;
			else
				max = 28;
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			max=30;
	}

	/* reconstruct day box */
	daybox.options.length=max;
	for(var i=1; i <= max; i++)
	{
		daybox.options[i-1] = new Option(i,i);
	}
	if(day > max)
		day=max;
	daybox.options[day-1].selected=true;
}


/* calculate financial text boxes for applicant */
function fcalc(applicant)
{	
	var pre = 'a' + applicant + '_';
	/* calculate total assets */

	el(pre + 'assets_total').value = nval(pre + 'assets_home') + nval(pre + 'assets_vehicles') + nval(pre + 'assets_investments') +	nval(pre + 'assets_othera');
	el(pre+ 'liabilities_homeloan_balance').value= nval(pre+'assets_home') - nval(pre + ('liabilities_homeloan'));
	
	var mypayrate=1.0;
	if( val(pre+'payment')=="Weekly" )
	{
			mypayrate = 4.3;
	}
	if( val(pre+'payment')=="Fortnightly" )
	{
		mypayrate = 2.15;
	}
	
	var theirpayrate=1.0;
	if( val(pre+'otherpayment')=="Weekly" )
	{
		theirpayrate = 4.3;
	}
	
	if( val(pre+'otherpayment')=="Fortnightly" )
	{
		theirpayrate = 2.15;
	}
	
	var mypay = mypayrate * nval(pre+'income_own');
	var theirpay = theirpayrate * nval(pre+'income_partner');
	
	el(pre+'income_total').value = mypay + theirpay + nval(pre+'income_othera');
	
	
/*	el(pre + 'liabilities_total').value = 
			nval(pre + 'liabilities_homeloan')
			+ nval(pre + 'liabilities_homeloan_balance')
			+ nval(pre + 'liabilities_hp')
			+ nval(pre + 'liabilities_hp')									
			+	nval(pre + 'liabilities_othera');*/
	el(pre + 'networth_total').value = nval(pre + 'assets_total') - nval(pre + 'liabilities_total');
	
	el(pre+'liabilities_total').value = nval(pre + 'liabilities_homeloan_balance')  + nval( pre + 'liabilities_hp_left_to_pay' )
			+ nval(pre + 'liabilities_othera');
	
	el(pre + 'expenses_total').value = nval(pre + 'expenses_rent') + nval(pre + 'expenses_hp') +	nval(pre + 'expenses_creditcard') + nval(pre + 'expenses_living') + nval(pre + 'expenses_othera') + nval(pre + 'expenses_otherb') + nval(pre + 'expenses_otherc');

	

	el(pre + 'expenses_total_copy').value = nval(pre + 'expenses_total');
	el(pre + 'sub_total').value = nval(pre + 'income_total') - nval(pre + 'expenses_total_copy');
	//el(pre + 'surplus').

//	alert(applicant);
}

function dym(gbox, attr)
{
	el(gbox).value=attr;
	fcalc(1);
	fcalc(2);
}

function el(id)
{
	return document.getElementById(id);
}


function nval(id)
{
	var val;
	val = el(id).value.replace(/[^0-9\.]*/g,'')

	if(isNaN(val=parseFloat(val, 10)))
		val=0;
	el(id).value=val;
	return val;
}

function val(id)
{
	return el(id).value;
}

function trim(trim_value)
{
	if(trim_value.length < 1)
		return"";
	
	trim_value = rtrim(trim_value);
	trim_value = ltrim(trim_value);

	if(trim_value=="")
		return "";
	else
		return trim_value;
	
}

function rtrim(value)
{
	var w_space = String.fromCharCode(32);
	var v_length = value.length;
	var strTemp = "";
	if(v_length < 0)
		return"";
	
	var iTemp = v_length -1;

	while(iTemp > -1)
	{
		if(value.charAt(iTemp) != w_space)
		{
			strTemp = value.substring(0,iTemp +1);
			break;
		}
		iTemp = iTemp-1;
	}
	return strTemp;
}

function ltrim(value)
{
	var w_space = String.fromCharCode(32);
	if(v_length < 1)
		return"";
	
	var v_length = value.length;
	var strTemp = "";

	var iTemp = 0;

	while(iTemp < v_length)
	{
		if(value.charAt(iTemp) != w_space)
		{
			strTemp = value.substring(iTemp,v_length);
			break;
		}
		iTemp = iTemp + 1;
	}
	return strTemp;
}

function filled(id)
{
	if(trim(val(id)) == '')
		return false;
	return true;
}

function ww(applicant, id, label)
{
	id = 'a' + applicant + '_' + id;

//	alert(id);

	if(applicant==1)
		applicant='Applicant 1 - ';
	else
		applicant='Applicant 2 - ';


	if(!filled(id))
		return applicant+ label + '\n';

	return '';
}

function validate(all)
{
	// if (all)
	//	validate all stages
	// otherwise just the current one
	doage();
	var whatswrong='';

	if(all && a1age < 18)
		napps = 2;
	else 
		napps = 1;

	for(var i=applicant; i <= napps; i++)
	{
//		whatswrong += i + '\n';
		switch(stage)
		{
			case 0:
				whatswrong += ww(i, 'surname', 'Surname');
				whatswrong += ww(i, 'first_name', 'First name');
				if(val('a'+i+'dob_d')=='' ||
					val('a'+i+'dob_m')=='' ||
					val('a'+i+'dob_y')=='')
				whatswrong += 'Applicant '+i+' - Date of Birth\n';
				whatswrong += ww(i, 'address_cur_street_no', 'Current Address - Street No');
				whatswrong += ww(i, 'address_cur_street', 'Current Address - Street');
				whatswrong += ww(i, 'address_cur_town_or_city', 'Current Address - Town Or City');
				
				whatswrong += ww(i, 'address_cur_own_or_rent_or_other', 'Current Address - Own Or Rent Or Other');
				whatswrong += ww(i, 'address_cur_how_long', 'Current Address - How Long');
				if(nval('a'+i+'_address_cur_how_long') < 3)
				{
					whatswrong += ww(i, 'address_prev_street_no', 'Previous Address - Street No');
					whatswrong += ww(i, 'address_prev_street', 'Previous Address - Street');
					whatswrong += ww(i, 'address_prev_town_or_city', 'Previous Address - Town Or City');

					whatswrong += ww(i, 'address_prev_own_or_rent_or_other', 'Previous Address - Own Or Rent Or Other');
					whatswrong += ww(i, 'address_prev_how_long', 'Previous Address - How Long');
				}
				
				whatswrong += ww(i, 'phone_home', 'Phone Home');
				whatswrong += ww(i, 'bank_account', 'Bank Account');
				if(el('a'+i+'_agree_to_declaration_and_credit_check').checked != true)
					whatswrong += 'Applicant '+i+' - You must agree to a credit check\n';
				if(!all)
					break;
			case 1:
				whatswrong += ww(i, 'employer_cur_name', 'Current Employer - Name');
				whatswrong += ww(i, 'employer_cur_phone_number', 'Current Employer - Phone');
				whatswrong += ww(i, 'employer_cur_position', 'Current Employer - Position');
				whatswrong += ww(i, 'employer_cur_how_long', 'Current Employer - How Long');
				if(nval('a'+i+'_employer_cur_how_long') < 3)
				{
					whatswrong += ww(i, 'employer_prev_name', 'Previous Employer - Name');
					whatswrong += ww(i, 'employer_prev_phone_number', 'Previous Employer - Phone');
					whatswrong += ww(i, 'employer_prev_position', 'Previous Employer - Position');
					whatswrong += ww(i, 'employer_prev_how_long', 'Previous Employer - How Long');
				}
				if(el('a'+i+'_agree_to_declaration_and_credit_check').checked != true)
					whatswrong += 'Applicant '+i+' - You must agree to a credit check\n';
				if(!all)
					break;
		}	
	}
	if(whatswrong.length != 0)
	{
		alert('The following fields still need to be filled in:\n\n' + whatswrong);
		return false;
	}
	return true;
}