/*
 * DOM.JS
 * Contains JS for DOM manipulation on the Input and Result pages.
	* Dependency: Prototype JS library (currently using version 1.6.0.3)
	* 
	* Notes:
	* The Javascript in here is pretty verbose, as it was coded, and is maintained by, by someone who
	* is not a Javascript guru, and relies on the comments to guide him thru late-night changes!
	* As a refactoring exercise for the future, please consider:-
	* 1. A better way to do the object!=null checks
	* 2. more concise variable names
	* 3. Using a compressor or minifier.
	* 4. if this file gets big and ungainly, then splitting out code that is specific to certain instances into separate JS files
	* 5. Reducing the probable overuse of brackets!
	* 
	* Copyright 2007 - 2001 Moneio
*/

/**
 * OTHER INCOMES
 */
// This must be called first
function initializeOtherIncomes() {
	// Global Variables - How many max?
	window.OIMaxMain = 3;
	window.OIMaxJoint = 3;
	
	// Global variables - How many "Other Income"s being displayed now
	window.OIDisplayedMain = window.OIMaxMain;
	window.OIDisplayedJoint = window.OIMaxJoint;
	
	// First show all plus and minus buttons
	for(var i=1; i<=window.OIMaxMain; i++) {
		if($('addOIBtnMain'+i) != null) { $('addOIBtnMain'+i).show(); }
		if($('removeOIBtnMain'+i) != null) { $('removeOIBtnMain'+i).show(); }
	}
	for(var j=1; j<=window.OIMaxJoint; j++) {
		if($('addOIBtnJoint'+j) != null) { $('addOIBtnJoint'+j).show(); }
		if($('removeOIBtnJoint'+j) != null) { $('removeOIBtnJoint'+j).show(); }
	}
	
	// Any income without a description must go!
	if($('otherIncomeDescFieldMain2').value == '') { removeOIMain2(); }
	if($('otherIncomeDescFieldMain3').value == '') { removeOIMain3(); }
	if($('otherIncomeDescFieldJoint2').value == '') { removeOIJoint2(); }
	if($('otherIncomeDescFieldJoint3').value == '') { removeOIJoint3(); }
}

function addOIMain(OIGroup) {
	if(window.OIDisplayedMain < window.OIMaxMain) {
		window.OIDisplayedMain = window.OIDisplayedMain + 1;
		// Show next group of fields
		$('OtherIncomeGroupMain' + window.OIDisplayedMain).show();
	} 
	else {
		// All shown
		return;
	}
}

function addOIJoint(OIGroup) {
	if(window.OIDisplayedJoint < window.OIMaxJoint) {
		window.OIDisplayedJoint = window.OIDisplayedJoint + 1;
		// Show next group of fields
		$('OtherIncomeGroupJoint' + window.OIDisplayedJoint).show();
	}
	else {
		// All shown
		return;
	}
}

function clearAndHideIOGroup(groupID) {
	$('otherIncomeValueField' + groupID).value = '';    // Remove income
	$('otherIncomeDescField' + groupID).selectedIndex = 0;    // Remove drop
																// down
																// selection
	$('otherIncomeDescField' + groupID).options[0].selected = true; // This
																	// piece
																	// here for
																	// Cross-browser
																	// protection
	$('OtherIncomeGroup' + groupID).hide();  // Hide group
}

function removeOIMain(OIGroupToRemove) {

	if(window.OIDisplayedMain == 0) {
		return;
	}
	
	// Copy every OI group to previous group and remove the last OI group
	var curSrc = OIGroupToRemove + 1;
	var curDest = OIGroupToRemove;
	while (curSrc <= window.OIMaxMain) {
		copyOI('Main'+curSrc, 'Main'+curDest);
		curSrc = curSrc + 1;
		curDest = curDest + 1;
	}
	
	// REMOVE
	clearAndHideIOGroup('Main' + window.OIDisplayedMain);
	window.OIDisplayedMain = window.OIDisplayedMain - 1;
}

function removeOIJoint(OIGroupToRemove) {
	if(window.OIDisplayedJoint == 0) {
		return;
	}

	// Copy every OI group to previous group and remove the last OI group
	var curSrc = OIGroupToRemove + 1;
	var curDest = OIGroupToRemove;
	while (curSrc <= window.OIMaxJoint) {
		copyOI('Joint'+curSrc, 'Joint'+curDest);
		curSrc = curSrc + 1;
		curDest = curDest + 1;
	}
	
	// REMOVE
	clearAndHideIOGroup('Joint' + window.OIDisplayedJoint);
	window.OIDisplayedJoint = window.OIDisplayedJoint - 1;
}

function copyOI(source, dest) {
	// copyOI(Joint2, Joint1)
	$('otherIncomeDescField' + dest).selectedIndex = $('otherIncomeDescField' + source).selectedIndex;
	$('otherIncomeValueField' + dest).value = $('otherIncomeValueField' + source).value;
}

/*
 * These functions are to be used as event handlers Do not use the
 * parameterized-form directly Because the latter causes the function to be
 * invoked when you are only trying to register
 */

function addOIMain1() { addOIMain(1);}
function addOIMain2() { addOIMain(2);}
function addOIMain3() { addOIMain(3);}
function addOIJoint1() { addOIJoint(1);}
function addOIJoint2() { addOIJoint(2);}
function addOIJoint3() { addOIJoint(3);}
function removeOIMain1() { removeOIMain(1);}
function removeOIMain2() { removeOIMain(2);}
function removeOIMain3() { removeOIMain(3);}
function removeOIJoint1() { removeOIJoint(1);}
function removeOIJoint2() { removeOIJoint(2);}
function removeOIJoint3() { removeOIJoint(3);}

/**
 * EMPLOYMENTS
 */
function toggleCurEmpDetailsMain() {
	var value = $('mainAppEmpStatusField').value;
	if(value == 'E' || value == 'P' || value == 'S' || value == 'C' || value == 'M') {
		$('curEmpEmployerNameMain').show();
		$('curEmpJobDescMain').show();
		$('curEmpGrossIncomeMain').show();
		//$('curEmpNetIncomeMain').show();
		// Show these additional fields if they are present
		if($('mainAppCurEmploymentAddressContainer')!=null) { $('mainAppCurEmploymentAddressContainer').show(); }
		if($('curEmpCategoryMain')!=null) { $('curEmpCategoryMain').show(); }
		if($('curEmpPhoneNumberMain')!=null) { $('curEmpPhoneNumberMain').show(); }
		if($('curEmpIncomeFrequencyMain')!=null) { $('curEmpIncomeFrequencyMain').show(); }
		if($('curEmpIncomePaymentMethodMain')!=null) { $('curEmpIncomePaymentMethodMain').show(); }
		if($('curEmpRetirementAgeMain')!=null) { $('curEmpRetirementAgeMain').show(); }
	}
	else {
		$('curEmpEmployerNameMain').hide();
		$('curEmpJobDescMain').hide();
	 	$('curEmpGrossIncomeMain').hide();
	 	//$('curEmpNetIncomeMain').hide();
	 	// Show these additional fields if they are present
		if($('mainAppCurEmploymentAddressContainer')!=null) { $('mainAppCurEmploymentAddressContainer').hide(); }
		if($('curEmpCategoryMain')!=null) { $('curEmpCategoryMain').hide(); }
		if($('curEmpPhoneNumberMain')!=null) { $('curEmpPhoneNumberMain').hide(); }
		if($('curEmpIncomeFrequencyMain')!=null) { $('curEmpIncomeFrequencyMain').hide(); }
		if($('curEmpIncomePaymentMethodMain')!=null) { $('curEmpIncomePaymentMethodMain').hide(); }
		if($('curEmpRetirementAgeMain')!=null) { $('curEmpRetirementAgeMain').hide(); }
	}
	
	// If self-employed, also ask accountant questions
	if($('curEmpHasAccountantMain')!=null) {
		if(value == 'S' || value == 'M') {
			$('curEmpHasAccountantMain').show();
		} 
		else {
			$('mainAppCurEmpHasAccountantField').checked = false;
			$('curEmpHasAccountantMain').hide();
		}
		toggleCurEmpAccountantDetailsMain();
	}
}

function toggleCurEmpAccountantDetailsMain() {
	if($('mainAppCurEmpHasAccountantField') == null) { return; }
	
	var chkBoxHasAccountant = $('mainAppCurEmpHasAccountantField');
	if(chkBoxHasAccountant.checked) {
		if($('curEmpAccountantCompanyNameMain')!=null) { $('curEmpAccountantCompanyNameMain').show(); }
		if($('curEmpAccountantAddressMain')!=null) { $('curEmpAccountantAddressMain').show(); }
		if($('curEmpAccountantPhoneMain')!=null) { $('curEmpAccountantPhoneMain').show(); }
	} 
	else {
		if($('curEmpAccountantCompanyNameMain')!=null) { $('curEmpAccountantCompanyNameMain').hide(); }
		if($('curEmpAccountantAddressMain')!=null) { $('curEmpAccountantAddressMain').hide(); }
		if($('curEmpAccountantPhoneMain')!=null) { $('curEmpAccountantPhoneMain').hide(); }
	}
}

function toggleCurEmpAccountantDetailsJoint() {
	if($('jointAppCurEmpHasAccountantField') == null) { return; }
	
	var chkBoxHasAccountant = $('jointAppCurEmpHasAccountantField');
	if(chkBoxHasAccountant.checked) {
		if($('curEmpAccountantCompanyNameJoint')!=null) { $('curEmpAccountantCompanyNameJoint').show(); }
		if($('curEmpAccountantAddressJoint')!=null) { $('curEmpAccountantAddressJoint').show(); }
		if($('curEmpAccountantPhoneJoint')!=null) { $('curEmpAccountantPhoneJoint').show(); }
	} 
	else {
		if($('curEmpAccountantCompanyNameJoint')!=null) { $('curEmpAccountantCompanyNameJoint').hide(); }
		if($('curEmpAccountantAddressJoint')!=null) { $('curEmpAccountantAddressJoint').hide(); }
		if($('curEmpAccountantPhoneJoint')!=null) { $('curEmpAccountantPhoneJoint').hide(); }
	}
}

function toggleFirstPrevEmpDetailsMain() {
	var value = $('mainAppFirstPrevEmpStatusField').value;
	if(value == 'E' || value == 'P' || value == 'S' || value == 'C' || value == 'M') {
		$('mainAppFirstPrevEmpJobDesc').show();
		$('mainAppFirstPrevEmpEmployerName').show();
	}
	else {
		$('mainAppFirstPrevEmpJobDesc').hide();
		$('mainAppFirstPrevEmpEmployerName').hide();
	}
}

function toggleSecondPrevEmpDetailsMain() {
	var value = $('mainAppSecondPrevEmpStatusField').value;
	if(value == 'E' || value == 'P' || value == 'S' || value == 'C' || value == 'M') {
		$('mainAppSecondPrevEmpJobDesc').show();
		$('mainAppSecondPrevEmpEmployerName').show();
	}
	else {
		$('mainAppSecondPrevEmpJobDesc').hide();
		$('mainAppSecondPrevEmpEmployerName').hide();
	}
}

function toggleCurEmpDetailsJoint() {
	var value = $('jointAppEmpStatusField').value;
	if(value == 'E' || value == 'P' || value == 'S' || value == 'C' || value == 'M') {
		$('curEmpEmployerNameJoint').show();
		$('curEmpJobDescJoint').show();		
		$('curEmpIncomeJoint').show();
		//$('curEmpNetIncomeJoint').show();
		// Show these additional fields if they are present
		if($('curEmpAddressJointContainer')!=null) { $('curEmpAddressJointContainer').show(); }
		if($('curEmpCategoryJoint')!=null) { $('curEmpCategoryJoint').show(); }
		if($('curEmpPhoneNumberJoint')!=null) { $('curEmpPhoneNumberJoint').show(); }
		if($('curEmpIncomeFrequencyJoint')!=null) { $('curEmpIncomeFrequencyJoint').show(); }
		if($('curEmpIncomePaymentMethodJoint')!=null) { $('curEmpIncomePaymentMethodJoint').show(); }
		if($('curEmpRetirementAgeJoint')!=null) { $('curEmpRetirementAgeJoint').show(); }
	}
	else {
		$('curEmpEmployerNameJoint').hide();
		$('curEmpJobDescJoint').hide();		 
	 	$('curEmpIncomeJoint').hide();
	 	//$('curEmpNetIncomeJoint').hide();
	 	// Show these additional fields if they are present
	 	if($('curEmpAddressJointContainer')!=null) { $('curEmpAddressJointContainer').hide(); }
		if($('curEmpCategoryJoint')!=null) { $('curEmpCategoryJoint').hide(); }
		if($('curEmpPhoneNumberJoint')!=null) { $('curEmpPhoneNumberJoint').hide(); }
		if($('curEmpIncomeFrequencyJoint')!=null) { $('curEmpIncomeFrequencyJoint').hide(); }
		if($('curEmpIncomePaymentMethodJoint')!=null) { $('curEmpIncomePaymentMethodJoint').hide(); }
		if($('curEmpRetirementAgeJoint')!=null) { $('curEmpRetirementAgeJoint').hide(); }
	}
	
	// If self-employed, also ask accountant questions
	if($('curEmpHasAccountantJoint')!=null) {
		if(value == 'S' || value == 'M') {
			$('curEmpHasAccountantJoint').show();
		} 
		else {
			$('jointAppCurEmpHasAccountantField').checked = false;
			$('curEmpHasAccountantJoint').hide();
		}
		toggleCurEmpAccountantDetailsJoint();
	}
}

function toggleFirstPrevEmpDetailsJoint() {
	var value = $('jointAppFirstPrevEmpStatusField').value;
	if(value == 'E' || value == 'P' || value == 'S' || value == 'C'|| value == 'M') {
		$('jointAppFirstPrevEmpJobDesc').show();
		$('jointAppFirstPrevEmpEmployerName').show();
	}
	else {
		$('jointAppFirstPrevEmpJobDesc').hide();
		$('jointAppFirstPrevEmpEmployerName').hide();
	}
}

function toggleSecondPrevEmpDetailsJoint() {
	var value = $('jointAppSecondPrevEmpStatusField').value;
	if(value == 'E' || value == 'P' || value == 'S' || value == 'C' || value == 'M') {
		$('jointAppSecondPrevEmpJobDesc').show();
		$('jointAppSecondPrevEmpEmployerName').show();
	}
	else {
		$('jointAppSecondPrevEmpJobDesc').hide();
		$('jointAppSecondPrevEmpEmployerName').hide();
	}
}

/**
 * SECURED PROPERTY
 */

function togglePercentageOwned() {
	var chkBoxSharOwn = $('propertySharedOwnCheckboxField');
	if(chkBoxSharOwn.checked) {
		$('prop0-percnt-own-field').show();
	} else {
		$('prop0-percnt-own-field').hide();
	}
}

function toggleFloors() {
	var value = $('propertyTypeField').value;
	if(value == 'F') {
		$('propertyFloors').show();
	} else {
	 	$('propertyFloors').hide();
	}
}
function toggleCouncilDiscount() {
	var chkBox = $('prop0-council-house');
	if(chkBox.checked) {
		$('prop0-council-disc-group').show();
	} else {
		$('prop0-council-disc-group').hide();
		$('propertyCouncilDiscountField').value = '';
	}
}

function togglePropertyAddress() {
	var chkBox = $('propertyAddrSameAsCurrentCheckboxField');
	if(!chkBox.checked) {
		$('custs-appl-address-group').show();
	} else {
		$('custs-appl-address-group').hide();
	}
}

/**
 * Toggle Property details, PropertyMortgage details and PropertySecuredLoan
 * details
 */
function togglePropertyDetails() {
	var resStatus = $('mainAppResidentialStatusField').value;
	// If Residential status = HomeOwner or HomeOwnerWithMortgage
	if(resStatus == 'M' || resStatus == 'H') {
		$('securedLoanInfo').show();
	} else {
		$('securedLoanInfo').hide();
	}
}
function togglePropertyMortgageDetails() {
	var value = $('mainAppResidentialStatusField').value;
	// If Residential status = HomeOwner With Mortgage
	if(value == 'M') {
		//$('mortgageHistoryContainer').show();
		$('propertyMortgageDetailsContainer').show();
	} 
	else {
		// Remove PropertyMortgage details
		$('propertyMortgageDetailsContainer').hide();
		//$('mortgageHistoryContainer').hide();
		//$('mortgageHistoryYearsField').value = '';
		//$('mortgageHistoryMonthsField').value = '';
		$('mortgageLenderCodeField').selectedIndex = 0;
		$('mortgageLenderCodeField').options[0].selected = true;
		$('mortgageRepaymentField').value = '';
		$('mortgageOutstandingField').value = '';
	}
}
function togglePropertySecuredLoanDetails() {
	var chkBox = $('propertyHasSecLoanCheckboxField');
	if(chkBox.checked) {
		$('propertySecLoanDetailsContainer').show();
	} 
	else {
		// Remove PropertySecuredLoan details
		$('propertySecLoanDetailsContainer').hide();
		$('secLoanLenderCodeField').selectedIndex = 0;
		$('secLoanLenderCodeField').options[0].selected = true;
		$('secLoanRepaymentField').value = '';
		$('secLoanOutstandingField').value = '';
	}
}

function toggleGenderOnTitleMain() {
	var title = $('mainTitleField').value;
	if(title == 'Dr') {
		$('mainGenderContainer').show();
	} else {
		$('mainGenderContainer').hide();
	}
}

function toggleGenderOnTitleJoint() {
	var title = $('jointTitleField').value;
	if(title == 'Dr') {
		$('jointGenderContainer').show();
	} else {
		$('jointGenderContainer').hide();
	}
}

function toggleInsuranceChecked() {
	var chkBox = $('askAboutInsuranceCheckboxField');
	if (chkBox != null) {
		if(chkBox.checked) {
			$('askAboutInsuranceChecked').show();
		} else {
			$('askAboutInsuranceChecked').hide();
		}
	}
}

/**
 * DIVs with progress GIF
 */
function showWaitDiv() {
	$('waitDiv').show();
	if($('submitBtn_dis')!=null) {
		$('submitBtn').hide();
		$('submitBtn_dis').show();
	}
}
function showWaitDiv2() {
	$('waitDiv2').show();
	if($('submitBtn2_dis')!=null) {
		$('submitBtn2').hide();
		$('submitBtn2_dis').show();
	}
}
function hideWaitDiv() {
	$('waitDiv').hide();
	$('submitBtn').show();
	if($('submitBtn_dis')!=null) {
		$('submitBtn_dis').hide();
	}
}
function hideWaitDiv2() {
	$('waitDiv2').hide();
	$('submitBtn2').show();
	if($('submitBtn2_dis')!=null) {
		$('submitBtn2_dis').hide();
	}
}

/**
 * Comparison of loan products Note: This one expects a URL in a global
 * JavaScript variable named window.compareActionURL
 */
function submitForLenderCompare() {
	// Creating URL of form '/compareLenders.do ? thisPage=pagename &
	// compare-lenderCode1=y & compare-lenderCode2=y'
	// where lenderCode1 is a lender code
	// Example:
	// '/compareLenders.do?thisPage=pagename&compare-npf=y&compare-ble=y'
	var url = window.compareActionURL;
	var lenderCount = 0;
	
	// Get all check boxes on the page and check if they have IDs matching the
	// pattern "compare-*"
	var arrInput = document.getElementsByTagName("input");
	for (i=0; i<arrInput.length; i++) {
	    if (arrInput[i].type == 'checkbox') {
		    var chkBox = arrInput[i];
		    var checkBoxID = chkBox.id;
		 	if(chkBox!=null && chkBox.checked && checkBoxID!=null && checkBoxID.startsWith('compare-')) {
		 		url = url + '&' + 'compare-' + chkBox.value + '=y';
		 		lenderCount++;
		 	}
	    }
    }
	
	if(lenderCount < 2 || lenderCount > 3) {
		alert('Please select at least 2 (maximum 3) lenders to compare');
		return;
	}
	
	// Go to URL
	window.location = url;
}

function validateLoanDetailsConfirmation() {
	var chkBox1 = $('loanAmountConfirmCheckboxField');
	var chkBox2 = $('totalFeesConfirmCheckboxField');
	var chkBox3 = $('totalBorrowingConfirmCheckboxField');
	var chkBox4 = $('aprConfirmCheckboxField');
	var chkBox5 = $('monthlyRepayConfirmCheckboxField');

	if(chkBox1!=null && chkBox1.checked 
			&& chkBox2!=null && chkBox2.checked 
			&& chkBox3!=null && chkBox3.checked 
			&& chkBox4!=null && chkBox4.checked 
			&& chkBox5!=null && chkBox5.checked 
			) {
		return true;
	}
	else {
		return false;
	}
}

function closeInfoMessages() {
	$('infoMessages').hide();
}

/**
 * CONTEXT HELP WISE WORDS
 */
function createCtxtHelpMappings() {
	// This Map maps the HTML input element to it's container (and thus to its
	// context message)
	// Each container has exactly one message
	window.ctxtHelpMap = new Object();

	ctxtHelpMap.loanTermField = 'loanTermContainer';
	ctxtHelpMap.loanAmountField = 'loanAmountContainer';
	ctxtHelpMap.loanPurposeSelectField = 'loanPurposeContainer';
	ctxtHelpMap.mainHomeOwnerField = 'homeOwnerContainer';
	ctxtHelpMap.mainUKResidentFieldYes = 'ukResidentContainer';
	ctxtHelpMap.mainUKResidentFieldNo = 'ukResidentContainer';
	ctxtHelpMap.mainAppNationalityField = 'mainAppNationalityContainer';
	ctxtHelpMap.mainAppPrevNameField = 'mainAppPrevNameContainer';
	ctxtHelpMap.mainAppDOBDateField = 'mainAppDOBContainer';
	ctxtHelpMap.mainAppDOBMonthField = 'mainAppDOBContainer';
	ctxtHelpMap.mainAppDOBYearField = 'mainAppDOBContainer';
	ctxtHelpMap.mainAppTimeAtCurAddrYearsField = 'mainAppTimeAtCurAddrContainer';
	ctxtHelpMap.mainAppTimeAtCurAddrMonthsField = 'mainAppTimeAtCurAddrContainer';
	ctxtHelpMap.numberOfEmploymentsMain = 'mainAppNumberOfJobsContainer';
	ctxtHelpMap.mainAppCurEmpJobDescField = 'mainAppCurEmploymentContainer';
	ctxtHelpMap.mainAppCurEmpEmployerNameField = 'mainAppCurEmploymentContainer';
	ctxtHelpMap.mainAppEmpStatusField = 'mainAppCurEmploymentContainer';
	ctxtHelpMap.mainAppCurEmpDurYearsField = 'mainAppCurEmploymentContainer';
	ctxtHelpMap.mainAppCurEmpDurMonthsField = 'mainAppCurEmploymentContainer';
	ctxtHelpMap.mainAppCurEmpGrossIncomeField = 'mainAppCurEmploymentContainer';
	ctxtHelpMap.mainAppCurEmpNetIncomeField = 'mainAppCurEmploymentContainer';
	ctxtHelpMap.mainAppCurEmpGrossIncomeField = 'mainAppCurEmploymentContainer';
	ctxtHelpMap.addOtherIncomesCheckBoxMain = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeDescField102 = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeDescField101 = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeDescField103 = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeValueField101 = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeValueField102 = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeValueField103 = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.numberHouseholdCarsField = 'numberCarsInHouseHoldContainer';
	ctxtHelpMap.mainAppMonthlyCreditCommitmentField = 'mainAppMonthlyCreditCommitmentQuestionsContainer';
	ctxtHelpMap.jointApplicationFieldYes = 'jointApplicationContainer';
	ctxtHelpMap.jointApplicationFieldNo = 'jointApplicationContainer';
	ctxtHelpMap.jointAppDOBDateField = 'jointAppDOBContainer';
	ctxtHelpMap.jointAppDOBMonthField = 'jointAppDOBContainer';
	ctxtHelpMap.jointAppDOBYearField = 'jointAppDOBContainer';
	ctxtHelpMap.jointAppEmailField = 'jointAppEmailContainer';
	ctxtHelpMap.jointAppTimeAtCurAddrYearsField = 'jointAppTimeAtCurAddrContainer';
	ctxtHelpMap.jointAppTimeAtCurAddrMonthsField = 'jointAppTimeAtCurAddrContainer';
	ctxtHelpMap.jointAppNationalityField = 'jointAppUKCitizenContainer';
	ctxtHelpMap.numberOfEmploymentsJoint = 'jointAppNumberOfJobsContainer';
	ctxtHelpMap.jointAppCurEmpJobDescField = 'jointAppCurEmploymentContainer';
	ctxtHelpMap.jointAppCurEmpEmployerNameField = 'jointAppCurEmploymentContainer';
	ctxtHelpMap.jointAppEmpStatusField = 'jointAppCurEmploymentContainer';
	ctxtHelpMap.jointAppCurEmpDurYearsField = 'jointAppCurEmploymentContainer';
	ctxtHelpMap.jointAppCurEmpDurMonthsField = 'jointAppCurEmploymentContainer';
	ctxtHelpMap.jointAppCurEmpNetIncomeField = 'jointAppCurEmploymentContainer';
	ctxtHelpMap.jointAppCurEmpIncomeField = 'jointAppCurEmploymentContainer';
	ctxtHelpMap.jointAppPrevNameField = 'jointAppPrevNameContainer';
	ctxtHelpMap.addOtherIncomesCheckBoxJoint = 'jointAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeDescField201 = 'jointAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeDescField202 = 'jointAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeDescField203 = 'jointAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeValueField201 = 'jointAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeValueField202 = 'jointAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeValueField203 = 'jointAppAdditionalIncomeContainer';
	ctxtHelpMap.mainAppIsUKCitizenField = 'mainAppUKCitizenContainer';
	ctxtHelpMap.mainUKResidentFieldYes = 'ukResidentContainer';
	ctxtHelpMap.mainUKResidentFieldNo = 'ukResidentContainer';
	ctxtHelpMap.mainAppResidentialStatusField = 'mainAppResidentialStatusContainer';
	ctxtHelpMap.mainFirstNameField = 'mainFirstNameContainer';
	ctxtHelpMap.mainSurnameField = 'mainSurnameContainer';
	ctxtHelpMap.mainMaritalStatusField = 'mainMaritalStatusContainer';
	ctxtHelpMap.mainAppEmailField = 'mainContactsContainer';
	ctxtHelpMap.mainHomePhoneField = 'mainContactsContainer';
	ctxtHelpMap.mainWorkPhoneField = 'mainContactsContainer';
	ctxtHelpMap.mainMobilePhoneField = 'mainContactsContainer';
	ctxtHelpMap.mainMobileIsContractField = 'mainContactsContainer';
	ctxtHelpMap.mainMonthlyCouncilTaxField = 'mainCouncilTaxContainer';
	ctxtHelpMap.mainHasDependentsCheckboxField = 'mainDependantsContainer';
	ctxtHelpMap.mainDependentAge1Field = 'mainDependantsContainer';
	ctxtHelpMap.mainDependentAge2Field = 'mainDependantsContainer';
	ctxtHelpMap.mainDependentAge3Field = 'mainDependantsContainer';
	ctxtHelpMap.mainDependentAge4Field = 'mainDependantsContainer';
	ctxtHelpMap.mainDependentAge5Field = 'mainDependantsContainer';
	ctxtHelpMap.numberHouseholdTotalField = 'numberInHouseHoldContainer';
	ctxtHelpMap.numberHouseholdWorkingField = 'numberInHouseHoldContainer';
	ctxtHelpMap.mainAppFirstPrevEmpStatusField = 'mainAppFirstPrevEmploymentContainer';
	ctxtHelpMap.mainAppFirstPrevEmpJobDescField = 'mainAppFirstPrevEmploymentContainer';
	ctxtHelpMap.mainAppFirstPrevEmpEmployerNameField = 'mainAppFirstPrevEmploymentContainer';
	ctxtHelpMap.mainAppFirstPrevEmpDurYearsField = 'mainAppFirstPrevEmploymentContainer';
	ctxtHelpMap.mainAppFirstPrevEmpDurMonthsField = 'mainAppFirstPrevEmploymentContainer';
	ctxtHelpMap.mainAppBankNameField = 'mainAppBankNameContainer';
	ctxtHelpMap.mainAppAccountNumberField = 'mainAppBankDetailsContainer';
	ctxtHelpMap.mainAppSortCodeField = 'mainAppBankDetailsContainer';
	ctxtHelpMap.mainAppBankDurYearsField = 'mainAppBankDetailsContainer';
	ctxtHelpMap.mainAppBankDurMonthsField = 'mainAppBankDetailsContainer';
	ctxtHelpMap.hasCreditCardField = 'mainAppBankCardsDetailsContainer';
	ctxtHelpMap.hasChequeCardField = 'mainAppBankCardsDetailsContainer';
	ctxtHelpMap.hasStoreCardField = 'mainAppBankCardsDetailsContainer';	
	ctxtHelpMap.jointMaritalStatusCheckboxField = 'jointMaritalStatusContainer';
	ctxtHelpMap.propertyPurchaseDateDayField = 'propertyPurchaseDateContainer';
	ctxtHelpMap.propertyPurchaseDateMonthField = 'propertyPurchaseDateContainer';
	ctxtHelpMap.propertyPurchaseDateYearField = 'propertyPurchaseDateContainer';
	ctxtHelpMap.propertyCouncilNeverField = 'propertyCouncilContainer';
	ctxtHelpMap.propertyCouncilFormerField = 'propertyCouncilContainer';
	ctxtHelpMap.propertyCouncilCurrentlyField = 'propertyCouncilContainer';
	ctxtHelpMap.propertyCouncilDiscountField = 'propertyCouncilContainer';
	ctxtHelpMap.propertyTypeField = 'propertyTypeContainer';
	ctxtHelpMap.propertyNumberOfFloorsField = 'propertyTypeContainer';
	ctxtHelpMap.propertyEstValueField = 'propertyEstValueContainer';
	ctxtHelpMap.propertySharedOwnCheckboxField = 'propertySharedOwnContainer';
	ctxtHelpMap.propertyPurchasePriceField = 'propertyPurchasePriceContainer';
	ctxtHelpMap.hasMultiplePropsFieldYes = 'multiplePropertyContainer';
	ctxtHelpMap.hasMultiplePropsFieldNo = 'multiplePropertyContainer';
	ctxtHelpMap.propertyHasMortgageCheckboxField = 'propertyHasMortgageContainer';
	ctxtHelpMap.mortgageLenderCodeField = 'propertyMortgageDetailsContainer';
	ctxtHelpMap.mortgageRepaymentField = 'propertyMortgageDetailsContainer';
	ctxtHelpMap.mortgageOutstandingField = 'propertyMortgageDetailsContainer';
	ctxtHelpMap.mortgageHistoryYearsField = 'mortgageHistoryContainer';
	ctxtHelpMap.mortgageHistoryMonthsField = 'mortgageHistoryContainer';
	ctxtHelpMap.secLoanRepaymentField = 'propertySecLoanDetailsContainer';
	ctxtHelpMap.secLoanOutstandingField = 'propertySecLoanDetailsContainer';
	ctxtHelpMap.secLoanLenderCodeField = 'propertySecLoanDetailsContainer';
	ctxtHelpMap.sendNoMarketingCheckboxField = 'sendMarketingMailContainer';
	ctxtHelpMap.agreeTermsCheckboxField = 'agreeTermsContainer';
	ctxtHelpMap.usernameField = 'mainAppSignUpInfoContainer';
	ctxtHelpMap.newPassword = 'mainAppSignUpInfoContainer';
	ctxtHelpMap.newPasswordField = 'mainAppSignUpInfoContainer';
	ctxtHelpMap.confirmationPassword = 'mainAppSignUpInfoContainer';
	ctxtHelpMap.mainAppNectarCardNumberField = 'mainAppNectarCardContainer';
}

function attachCtxtHelpToElements() {
	/* Attach showCtxtHelp() as event handler for input fields */
	var fields = $('inputForm').elements; 
	for(i=0; i<fields.length; i++){
		var field = fields[i];
	 	if(field.type == 'text' || field.type == 'select-one' || field.type == 'checkbox' || field.type == 'radio') {
	 		Event.observe(field, 'focus', showCtxtHelp);
	 	}
	}
	
	// Context help on hover for some paragraphs
	if($('ukResidentContainer')!=null) { $('ukResidentContainer').observe('mouseover', showCtxtHelp); }
	if($('jointApplicationContainer')!=null) { $('jointApplicationContainer').observe('mouseover', showCtxtHelp); }
	if($('mainAppUKCitizenContainer')!=null) { $('mainAppUKCitizenContainer').observe('mouseover', showCtxtHelp); }
	if($('mainAppAdditionalIncomeContainer')!=null) { $('mainAppAdditionalIncomeContainer').observe('mouseover', showCtxtHelp); }
	if($('jointAppAdditionalIncomeContainer')!=null) { $('jointAppAdditionalIncomeContainer').observe('mouseover', showCtxtHelp); }
	if($('propertyCouncilContainer')!=null) { $('propertyCouncilContainer').observe('mouseover', showCtxtHelp); }
	if($('mainDependantsContainer')!=null) { $('mainDependantsContainer').observe('mouseover', showCtxtHelp); }
	if($('mainAppMissedRepaymentsContainer')!=null) { $('mainAppMissedRepaymentsContainer').observe('mouseover', showCtxtHelp); }
	if($('mainAppCCJsContainer')!=null) { $('mainAppCCJsContainer').observe('mouseover', showCtxtHelp); }
	if($('mainAppBankruptContainer')!=null) { $('mainAppBankruptContainer').observe('mouseover', showCtxtHelp); }
	if($('propertyHasSecLoanContainer')!=null) { $('propertyHasSecLoanContainer').observe('mouseover', showCtxtHelp); }
	if($('mainAppSignUpInfoContainer')!=null) { $('mainAppSignUpInfoContainer').observe('mouseover', showCtxtHelp); }
	if($('mainAppMonthlyCreditCommitmentQuestionsContainer')!=null) { $('mainAppMonthlyCreditCommitmentQuestionsContainer').observe('mouseover', showCtxtHelp); }
	if($('agreeTermsContainer')!=null) { $('agreeTermsContainer').observe('mouseover', showCtxtHelp); }
	if($('sendMarketingMailContainer')!=null) { $('sendMarketingMailContainer').observe('mouseover', showCtxtHelp); }
	if($('multiplePropertyContainer')!=null) { $('multiplePropertyContainer').observe('mouseover', showCtxtHelp); }
}

function showCtxtHelp() {
	var invokingElementID = this.id;
	
    // Deactivate currently active container
    if($(window.curCtxtHelpContainerID) != null) {
		$(window.curCtxtHelpContainerID).removeClassName('active');
	}
	// Hide currently displayed CtxtHelp message
	if($(window.curCtxtHelpMessageID) != null) {
		$(window.curCtxtHelpMessageID).hide();
	}
	
	// CtxtHelp messages are attached to Containers (ie the 'p' or paragraph
	// element).
	// If the invoking element is itself a container, we need nothing more
	// If the invoking element is NOT a container, get its enclosing container
	// from the mapping 'ctxtHelpMap'
	if(this.tagName == 'p' || this.tagName == 'P') {
		invokingContainerID = invokingElementID;
	} else {
		invokingContainerID = window.ctxtHelpMap[invokingElementID];
	}
	
	// ID of ctxtHelp
	var ctxtHelpID = '';
	// If a ctxtHelp for the field is defined, then that's what we want to show
	ctxtHelpID = invokingElementID + 'CtxtHelp';
	// If a ctxtHelp for the field is not defined, try to show ctxtHelp of
	// enclosing container
	if($(ctxtHelpID) == null) {
		ctxtHelpID = invokingContainerID + 'CtxtHelp';
	}
	
    // If ctxtHelpID is valid
	if($(ctxtHelpID) != null) {
		// Show new
		$(invokingContainerID).addClassName('active');
		// commented Appear Effect - breaks in IE 6
		// $(ctxtHelpID).appear({ duration: 0.4 });
		$(ctxtHelpID).addClassName('contexthelp');
		$(ctxtHelpID).show();
		window.curCtxtHelpContainerID = invokingContainerID;
		window.curCtxtHelpMessageID = ctxtHelpID;
	}
}

function hideCtxtHelp() {
	// Deactivate currently active container
    if($(window.curCtxtHelpContainerID) != null) {
		$(window.curCtxtHelpContainerID).removeClassName('active');
	}
	// Hide currently displayed CtxtHelp message
	if($(window.curCtxtHelpMessageID) != null) {
		$(window.curCtxtHelpMessageID).hide();
	}
}

/**
 * GENERAL LOAN APP SCRIPTS
 */

/**
 * MAIN APPLCIANT
 */

function toggleEmploymentDetailsMain() {
	
	var yearsStr = $('mainAppCurEmpDurYearsField').value;
	var years = parseInt(yearsStr, 10);
	if(years >= 0 && years < 3) {
		$('mainAppFirstPrevEmploymentContainer').show();
		window.firstPrevEmploymentMainShown = true;
	}
	else if ($('mainAppFirstPrevEmpStatusField').value != ''){
		$('mainAppFirstPrevEmploymentContainer').show();
		window.firstPrevEmploymentMainShown = true;
	} 
	else {
		$('mainAppFirstPrevEmploymentContainer').hide();
		clearEmploymentFields('mainAppFirstPrevEmp');
		clearEmploymentFields('mainAppSecondPrevEmp');
		window.firstPrevEmploymentMainShown = false;
	}
	
	// Second prev employment only if first prev is shown
	if(window.firstPrevEmploymentMainShown) {
		
		// Total duration of both cur and first prev is less than 3
		var yearsTotal = parseInt($('mainAppCurEmpDurYearsField').value, 10) + parseInt($('mainAppFirstPrevEmpDurYearsField').value, 10);
		var monthsTotal = parseInt($('mainAppCurEmpDurMonthsField').value, 10) + parseInt($('mainAppFirstPrevEmpDurMonthsField').value, 10);
		
		var duration = yearsTotal + (monthsTotal/12);
		if(duration >= 0 && duration < 3) {
			$('mainAppSecondPrevEmploymentContainer').show();
		} 
		else if ($('mainAppSecondPrevEmpStatusField').value != ''){
			$('mainAppSecondPrevEmploymentContainer').show();
		} 
		else {
			$('mainAppSecondPrevEmploymentContainer').hide();
			clearEmploymentFields('mainAppSecondPrevEmp');
		} 
	}
	else {
		$('mainAppSecondPrevEmploymentContainer').hide();
		clearEmploymentFields('mainAppSecondPrevEmp');
	} 
}

/**
 * MAIN APPLICANT DEPENDANTS
 */

function initDependantsSection(numberOfDependants) {
	$('mainDependentAddMoreContainer').show();
	// if more dependants section has data, show it
	if(numberOfDependants > 3) {
		$('mainDependent2Container').show();
		$('mainDependent3Container').show();
	} else {
		$('mainDependent2Container').hide();
		$('mainDependent3Container').hide();
	}
}

function showMoreDependantsInput() {
	$('mainDependent2Container').show();
	$('mainDependent3Container').show();	
}
/**
 * JOINT APPLICANT
 */

function jointApplication() {
	var jointApp = $('jointApplicationFieldYes');
	if (jointApp != null) {
		return jointApp.checked;
	}
	return false;
}

function toggleJointAppDetails() {
	if(jointApplication()) {
		$('jointAppDetailsContainer').show();
	}
	else {
		$('jointAppDetailsContainer').hide();
	}
}

function toggleJointAppCheckBoxHighlight() {
	// Does applicant have a partner?
	var hasPartner = false;
	if($('mainMaritalStatusField')!=null) { 
		var maritalStat = $F('mainMaritalStatusField');
		if(maritalStat == 'M' || maritalStat == 'L' || maritalStat == 'C') { hasPartner = true; }
	}
	// Is this a joint application?
	var isJointApp = jointApplication();
	
	// Has partner but NOT applying as joint? Highlight the warning message.
	if(hasPartner && !isJointApp) {
		$('jointApplicationContainer').addClassName('highlightWarningSoft');

		// Test scenario for joint applicant details behaviour
		// Whenever you need to highlight, also automatically tick the isJoint
		// check box
		// and show the joint applicant details container
		if(window.g_showJointAppDetailsOnMaritalStatus != 'undefined' 
			&& window.g_showJointAppDetailsOnMaritalStatus != null
			&& window.g_showJointAppDetailsOnMaritalStatus == true) {
			// tick check box and show details
			window.g_showJointAppDetailsOnMaritalStatus = false;
			$('jointApplicationFieldYes').checked = true;
			toggleJointAppDetails();
		}
	} 
	else {
		$('jointApplicationContainer').removeClassName('highlightWarningSoft');
	}
	
}

function toggleEmploymentDetailsJoint() {
	
	var yearsStr = $('jointAppCurEmpDurYearsField').value;
	var years = parseInt(yearsStr, 10);
	if(years >= 0 && years < 3) {
		$('jointAppFirstPrevEmploymentContainer').show();
		window.firstPrevEmploymentJointShown = true;
	}
	else if ($('jointAppFirstPrevEmpStatusField').value != ''){
		$('jointAppFirstPrevEmploymentContainer').show();
		window.firstPrevEmploymentJointShown = true;
	} 
	else {
		$('jointAppFirstPrevEmploymentContainer').hide();
		clearEmploymentFields('jointAppFirstPrevEmp');
		clearEmploymentFields('jointAppSecondPrevEmp');
		window.firstPrevEmploymentJointShown = false;
	}
	
	// Second prev employment only if first prev is shown
	if(window.firstPrevEmploymentJointShown) {
		
		// Total duration of both cur and first prev is less than 3
		var yearsTotal = parseInt($('jointAppCurEmpDurYearsField').value, 10) + parseInt($('jointAppFirstPrevEmpDurYearsField').value, 10);
		var monthsTotal = parseInt($('jointAppCurEmpDurMonthsField').value, 10) + parseInt($('jointAppFirstPrevEmpDurMonthsField').value, 10);
		
		var duration = yearsTotal + (monthsTotal/12);
		if(duration >= 0 && duration < 3) {
			$('jointAppSecondPrevEmploymentContainer').show();
		} 
		else if ($('jointAppSecondPrevEmpStatusField').value != ''){
			$('jointAppSecondPrevEmploymentContainer').show();
		} 
		else {
			$('jointAppSecondPrevEmploymentContainer').hide();
			clearEmploymentFields('jointAppSecondPrevEmp');
		} 
	}
	else {
		$('jointAppSecondPrevEmploymentContainer').hide();
		clearEmploymentFields('jointAppSecondPrevEmp');
	} 	
}

function clearEmploymentFields(prefix) {
	// Prefix: jointAppSecondPrevEmp, jointAppFirstPrevEmp, mainAppSecondPrevEmp
	if($(prefix+'StatusField') !=null) {
		$(prefix+'StatusField').value = '';
	}
	if($(prefix+'JobDescField') !=null) {
		$(prefix+'JobDescField').value = '';
	}
	if($(prefix+'EmployerNameField') !=null) {
		$(prefix+'EmployerNameField').value = '';
	}
	if($(prefix+'DurYearsField') !=null) {
		$(prefix+'DurYearsField').value = '';
	}
	if($(prefix+'DurMonthsField') !=null) {
		$(prefix+'DurMonthsField').value = '';
	}
}

function setPhoneToMainAppPhone() {
	if($('mainHomePhoneField') != null && $('jointHomePhoneField') != null && $('jointHomePhoneField').value == '') {
		$('jointHomePhoneField').value = $('mainHomePhoneField').value;
	}
}

function toggleMortgageRentPayment() {
	
	var resStatus = $('mainAppResidentialStatusField').value;

	if(resStatus == 'T' || resStatus == 'U' || resStatus == 'W' || resStatus == 'R') {
		// tenant or living with parents or other
		$('mainMortgageRentContainer').show();
	} else if(resStatus == 'M') {
		// Homeowner with mortgage
		$('mainMortgageRentContainer').hide();
	} else if(resStatus == 'H') {
		// Homeowner with no mortgage
		$('mainMortgageRentContainer').hide();
	} else {
		$('mainMortgageRentContainer').show();
	}
}

function toggleNumberMortOnOtherProperties() {
	var mpfy = $('hasMultiplePropsFieldYes');
	var mpfn = $('hasMultiplePropsFieldNo');
	if (mpfy != null && mpfn != null) {
		if (mpfy.checked) {
			$('numberMortOnOtherPropertiesContainer').show();
		} else if (mpfn.checked) {
			$('numberMortOnOtherPropertiesContainer').hide();
		} else {
			$('numberMortOnOtherPropertiesContainer').hide();
		}
	}
}

function toggleHomeOwnerOnlyQuestions() {
	
	var resStatus = $('mainAppResidentialStatusField').value;
	
	// The conditions are split into two IF blocks because of what we want to
	// display when
	// the customer has not selected the residential status yet.
	
	// If Tenant, Living with Parents, or Other, then do not ask these
	// Else, do ask these, even if residential status is unselected
	if(resStatus == 'T' || resStatus == 'U' || resStatus == 'R' || resStatus == 'W') {
		if($('mainAppLoyaltyCardContainer')!=null && $('mainAppLoyaltyCardField')!=null && $F('mainAppLoyaltyCardField') == '') { $('mainAppLoyaltyCardContainer').hide(); }
		if($('mainWorkPhoneContainer')!=null && $F('mainWorkPhoneField') == '') { $('mainWorkPhoneContainer').hide(); }
		if($('mainAppEmailTypeContainer')!=null) { $('mainAppEmailTypeContainer').hide(); }
	} 
	else {
		if($('mainAppLoyaltyCardContainer')!=null) { $('mainAppLoyaltyCardContainer').show(); }
		if($('mainWorkPhoneContainer')!=null) { $('mainWorkPhoneContainer').show(); }
		if($('mainAppEmailTypeContainer')!=null) { $('mainAppEmailTypeContainer').show(); }
	}
	
	// If HomeOwner or HomeOwner With Mortgage, ask these questions
	// Else, do not ask these, even if residential status is unselected
	if(resStatus == 'H' || resStatus == 'M') {
		if($('mainCouncilTaxContainer')!=null) { $('mainCouncilTaxContainer').show(); }
		if($('numberCarsInHouseHoldContainer')!=null) { $('numberCarsInHouseHoldContainer').show(); }
		if($('numberInHouseHoldContainer')!=null) { $('numberInHouseHoldContainer').show(); }
		if($('mainAppNectarCardContainer')!=null) { $('mainAppNectarCardContainer').show(); }
		if($('ukResidentContainer')!=null) { $('ukResidentContainer').show(); }
		if($('mainAppUKCitizenContainer')!=null) { $('mainAppUKCitizenContainer').show(); }
		if($('mainAppBankCardsDebitCardContainer')!=null) { $('mainAppBankCardsDebitCardContainer').show(); }
		if($('jointAppEmailTypeContainer')!=null) { $('jointAppEmailTypeContainer').show(); }
		if($('sharedOwnershipContainer')!=null) { $('sharedOwnershipContainer').show(); }
		if($('jointWorkPhoneContainer')!=null) { $('jointWorkPhoneContainer').show(); }
	} 
	else {
		if($('mainCouncilTaxContainer')!=null) { $('mainCouncilTaxContainer').hide(); }
		if($('numberCarsInHouseHoldContainer')!=null) { $('numberCarsInHouseHoldContainer').hide(); }
		if($('numberInHouseHoldContainer')!=null) { $('numberInHouseHoldContainer').hide(); }
		if($('mainAppNectarCardContainer')!=null) { $('mainAppNectarCardContainer').hide(); }
		if($('ukResidentContainer')!=null) { $('ukResidentContainer').hide(); }
		if($('mainAppUKCitizenContainer')!=null) { $('mainAppUKCitizenContainer').hide(); }
		if($('mainAppBankCardsDebitCardContainer')!=null) { $('mainAppBankCardsDebitCardContainer').hide(); }
		if($('jointAppEmailTypeContainer')!=null) { $('jointAppEmailTypeContainer').hide(); }
		if($('sharedOwnershipContainer')!=null) { $('sharedOwnershipContainer').hide(); }
		if($('jointWorkPhoneContainer')!=null && $F('jointWorkPhoneField') == '') { $('jointWorkPhoneContainer').hide(); }
	}
}

/**
 * Source code auto-completion
 */

function afterAutoCompleteSourceCode(text, li) {
	$('advsrcSuggestDescriptionSpan').innerHTML = ' ' + li.id;
	window.autoCompletedSourceDescriptionSet = true;
}

function clearAutoCompletedSourceDescription() {
	// Clear the description, if the AutoCompleter hasn't set it.
	if(!window.autoCompletedSourceDescriptionSet) {
		$('advsrcSuggestDescriptionSpan').innerHTML = '';
		window.autoCompletedSourceDescriptionSet = false;
	}
}

/**
 * LOAN AMOUNTS
 */

function setTotalLoanAmount() {
	var amount1Field = $('loanAmountField');
	var amount2Field = $('loanAmountSecondaryField');
	var amount1 = 0;
	var amount2 = 0;
	if(amount1Field != null) { amount1 = parseInt(amount1Field.value, 10); }
	if(amount2Field != null) { amount2 = parseInt(amount2Field.value, 10); }
	
	if(isNaN(''+amount1)) { amount1 = 0; }
	if(isNaN(''+amount2)) { amount2 = 0; }
	
	var amountTotal = amount1 + amount2;
	if(isNaN(''+amountTotal)) { amountTotal = 0; }
	
	// Set
	$('loan-value-total-label').innerHTML = '&pound; ' + amountTotal;
	if (amountTotal > 15000) {
		$('showSecuredScript').innerHTML = "As you have requested a loan amount for more than &pound;15,000 "
			+ "we will be looking at a secured loan. Secured loans are much like your mortgage and use the " 
			+ "equity available in your property. You can potentially get good APR's and they allow the flexibility to pay the loan back "
			+ "over longer terms which is ideal if you are looking to keep your monthly payments as low as possible." 
			+ "  A secured loan does have lender and broker fee's included which covers the cost of legal fees, valuations and processing." 
			+ "  It usually takes between 4-6 weeks to complete." 
			+ "  Once the loan is complete a charge is registered against your property. "
			+ " <strong>Is this OK?<\/strong> <input name=\"securedscript\" type=\"checkbox\" \/>";
		
	} else {
		
		$('showSecuredScript').innerHTML = "";
	}
}

/**
 * USER REGISTRATION
 */

function copyEmailAddress() {
	var applicationEmail = $('mainAppEmailField').value;
	var usernameEmail = $('usernameField').value;
	if(usernameEmail == null || usernameEmail.length < 1) {
		$('usernameField').value = applicationEmail;
	}
}

function togglePwdConfirmation() {
	if(document.getElementById('radioLogin').checked) {
		document.getElementById('spanRegister').style.display = 'none';
	} else {
		document.getElementById('spanRegister').style.display = '';
	}
}

function togglePasswordChange() {
	var checkBox = $('changePasswordChkBoxField');
	if(checkBox.checked) {
		$('passwordDiv').show();
	} else {
		$('passwordDiv').hide();
	}
}

function toggleConsumerLicense() {
	var chkBox = $('consumerLicense');
	if(chkBox.checked) {
		$('licensenumber').show();
	} else{
		$('licensenumber').hide();
	}
}

function toggleFSA() {
	var chkBox = $('directlyAuthorized');
	if(chkBox.checked) {
		$('fsaNumber').show();
	} else{
		$('fsaNumber').hide();
	}
}
function toggleNetworkName() {
	var chkBox = $('appointedRep');
	if(chkBox.checked) {
		$('networkname').show();
	} else{
		$('networkname').hide();
	}
}
function togglePermAttr() {
	var value = $('userRoleSelectField').value;
	if(value == 'LENDER_AGENT') {
		$('permissionAttributesContainer').show();
	} else {
		$('permissionAttributesContainer').hide();
	}
}

/**
 * HELP
 */

function hideHelp(callerID) {
  document.getElementById(callerID).style.visibility = "hidden";
}
function showHelp(callerID) {
	// hide currently visible
	if($(window.currentHelpID) !=null) {
		$(window.currentHelpID).style.visibility = "hidden";
	}
	// show new
	document.getElementById(callerID).style.visibility = "visible";
	window.currentHelpID = callerID;
}

/**
 * TEXT AREA CHARACTER LIMITER
 */

/**
 * textFieldID: ID of input field counterFieldID: ID of field to display
 * remainder count, will be ignored if sent as 'none'
 */
function textAreaCharacterLimit(textFieldID, counterFieldID, maxChars) {
	if ($(textFieldID).value.length > maxChars)
		$(textFieldID).value = $(textFieldID).value.substring(0, maxChars);
	else if ($(counterFieldID) != null)
		$(counterFieldID).value = maxChars - $(textFieldID).value.length;
}

/**
 * POP-UP
 */

function popup(mylink, windowname) {
	if (! window.focus) { 
		return true; 
	}
	var href;
	if (typeof(mylink) == 'string') {
		href=mylink;
	} else {
		href=mylink.href;
	}
	
	newPopupWindow = window.open(href, windowname, 'width=600,height=400,scrollbars=yes,menubar=no');
	
	if(newPopupWindow == null || typeof(newPopupWindow)=="undefined") {
		alert('Unable to open link in new pop-upwindow! This is most likely because your pop-up blocker prevented it.');
	}
	
	if (window.focus) {
		newPopupWindow.focus()
	}
	return false;
}

function popupLarge(mylink, windowname) {
	if (! window.focus) { 
		return true; 
	}
	var href;
	if (typeof(mylink) == 'string') {
		href=mylink;
	} else {
		href=mylink.href;
	}
	
	newPopupWindow = window.open(href, windowname, 'width=850,height=600,scrollbars=yes,menubar=no');
	
	if(newPopupWindow == null || typeof(newPopupWindow)=="undefined") {
		alert('Unable to open link in new pop-upwindow! This is most likely because your pop-up blocker prevented it.');
	}
	
	if (window.focus) {
		newPopupWindow.focus()
	}
	return false;
}

function popupWide(mylink, windowname) {
	if (! window.focus) { 
		return true; 
	}
	var href;
	if (typeof(mylink) == 'string') {
		href=mylink;
	} else {
		href=mylink.href;
	}
	
	newPopupWindow = window.open(href, windowname, 'width=720,height=400,scrollbars=yes,menubar=no');
	
	if(newPopupWindow == null || typeof(newPopupWindow)=="undefined") {
		alert('Unable to open link in new pop-upwindow! This is most likely because your pop-up blocker prevented it.');
	}
	
	if (window.focus) {
		newPopupWindow.focus()
	}
	return false;
}

/**
 * Can call this on click (on say, a hyperlink) to confirm/validate if we want
 * to proceed.
 */
function confirmCall() {
	answer = confirm ("Go Here?");
	if(answer!=0) {
		return true;
	} else {
		return false;
	}
}

/**
 * toggle display/hide all accepts on results page
 */
function toggleAllAccepts() {
	if(window.allAcceptsShown=='no') {
		if ($('allAcceptsContainer') != null) { $('allAcceptsContainer').show();}
		window.allAcceptsShown = 'yes';
		if($('allAcceptsLinkText')!=null) { $('allAcceptsLinkText').innerHTML = 'Hide'; }
	}
	else {
		if ($('allAcceptsContainer') != null) { $('allAcceptsContainer').hide();}
		window.allAcceptsShown = 'no';
		if($('allAcceptsLinkText')!=null) { $('allAcceptsLinkText').innerHTML = 'Show'; }
	}
}

/**
 * toggle display/hide all declines on results page
 */
function toggleAllDeclines() {
	if(window.allDeclinesShown=='no') {
		if($('allDeclinesContainer') != null) { $('allDeclinesContainer').show(); }
		window.allDeclinesShown = 'yes';
		if($('allDeclinesLinkText') != null) { $('allDeclinesLinkText').innerHTML = 'Hide'; }
	}
	else {
		if($('allDeclinesContainer') != null) { $('allDeclinesContainer').hide(); }
		window.allDeclinesShown = 'no';
		if($('allDeclinesLinkText') != null) { $('allDeclinesLinkText').innerHTML = 'Show'; }
	}
}

Array.prototype.has = function() {
	var	i = arguments.length,
	result = [];
	while(i)
	result.push(this.indexOf(arguments[--i]) !== -1);
	return result.every(function(e){return e});
};

/**
 * Screening questions functions for the Support Iris instance
 */
function checkScreeningQuestionsForSupport() {
	// Have the screening questions been answered correctly for Support
	// instance?
	// Then show the rest of the loan app form
	var screeningQPassed = true;
	var advsourcecode = "";
	if($('advsrcSuggest') != null)
		advsourcecode = $F('advsrcSuggest');
	
	// Certain source codes can accept tenants
	var sourceCodeAcceptsTenants = false;
	if(advsourcecode == 'MONNHS' || advsourcecode == 'NHSP'|| advsourcecode == 'BACTHK') { 
		sourceCodeAcceptsTenants = true; 
	}
	
	// Several source codes can enquire about LV insurance
	var validSources = ['000300','000W15','00W300','GFRFIN','GLSELC','GMINDE','MEDIAB','MSNLON','NPW01','OFINFR',
                    'OFLLOA','OFREED','OFREEF','RAF500',
                    'THOM01','THOM02','THOM03','THOM04','THOM05','THOM06','THOM07','THOM08',
                    'THOM1','THOM2','THOMW','WEBMAG','WEBSEN','YELL1','YELL2','YELL3',
                    'YELL4','YELLMS','00W158','000158','200001','000044','BANWEB','DMAWEB',
                    'EMA003','GOOGLE','LOANSW','MAGWEB','MEDIAT','MROI14', 'MONTLW',
                    'OOFWEB','OONWEB','PPCTEL','PPRWEB','RADWEB','SENWEB','TELWEB','TV',
                    'TVWEB','WSMS1','XBRAND','XFRFIN','XFRFUK','XGMS1','YBR1','YFINFR','YFREED','ZSNFFI'];
	if (validSources.has(advsourcecode)) {
		$('askAboutInsuranceContainer').show();
	} else {
		$('askAboutInsuranceContainer').hide();
	}
	
	// 1. Homeowner - Fail if unselected, tenant, living with parents. Tenants
	// are only allowed some source codes!
	if($('mainAppResidentialStatusField') != null) {
		var homeownerStatus = $('mainAppResidentialStatusField').value;
		if(homeownerStatus == '') {
			screeningQPassed = false; 
		} 
		if((homeownerStatus == 'T' || homeownerStatus == 'U' || homeownerStatus == 'W' || homeownerStatus == 'R') && !sourceCodeAcceptsTenants) { 
			screeningQPassed = false; 
		}	
	} 
	// 2. UK Resident - Fail if not checked
	if($('mainUKResidentFieldYes') != null && !$('mainUKResidentFieldYes').checked) {
		screeningQPassed = false; 
	} 
	// 3. Shared ownership - Fail if checked. Allow if this source code accepts
	// tenants
	if($('sharedOwnershipField') != null && $('sharedOwnershipField').checked && !sourceCodeAcceptsTenants) {
		screeningQPassed = false; 
	}
	
	// If Fail, hide rest of the form
	if(screeningQPassed) {
		$('mainLoanAppQuestions').show();
		$('submitBtn').show();
		if($('submitBtn2') != null) {  $('submitBtn2').show();  }
	} 
	else {
		$('mainLoanAppQuestions').hide();
		$('submitBtn').hide();
		if($('submitBtn2') != null) {  $('submitBtn2').hide();  }
	}
}

function registerScreeningQuestionsForSupport() {
	// Register these form elements to trigger the screening questions check
	if($('mainAppResidentialStatusField')!=null) { 
		$('mainAppResidentialStatusField').observe('change', checkScreeningQuestionsForSupport); }
	if($('mainUKResidentFieldYes')!=null) { 
		$('mainUKResidentFieldYes').observe('click', checkScreeningQuestionsForSupport); }
	if($('mainUKResidentFieldNo')!=null) { 
		$('mainUKResidentFieldNo').observe('click', checkScreeningQuestionsForSupport); }
	if($('sharedOwnershipField')!=null) { 
		$('sharedOwnershipField').observe('click', checkScreeningQuestionsForSupport); }
	if($('advsrcSuggest')!=null) { 
		$('advsrcSuggest').observe('change', checkScreeningQuestionsForSupport); }
	if($('advsrcSuggest')!=null) { 
		$('advsrcSuggest').observe('blur', checkScreeningQuestionsForSupport); }
}

/**
 * Screening questions functions for the BHL instance
 */
function checkScreeningQuestionsForBHL() {
	// Screening questions specific to BHL product
	var screeningQPassed = true;
	var code = 0;
	// First hide all screening failed messages
	for(var i=1; i<=10; i++) {
		if($('screeningFailedMsg'+i)!=null) {  $('screeningFailedMsg'+i).hide(); }
	}

	// Now check screening questions
	// 1. Residential status - Fail if not Homeowner with Mortgage
	if($('mainAppResidentialStatusField') != null) {
		if($F('mainAppResidentialStatusField') != 'M') { 
			screeningQPassed = false; 
			if($('screeningFailedMsg1')!=null) {  $('screeningFailedMsg1').show(); }
		}	
	} 
	// 2. UK Resident - Fail if not checked
	if($('mainUKResidentFieldYes') != null && !$('mainUKResidentFieldYes').checked) {
		screeningQPassed = false; 
		if($('screeningFailedMsg2')!=null) {  $('screeningFailedMsg2').show(); }
	} 
	// 3. Shared ownership - Fail if checked.
	if($('sharedOwnershipField') != null && $('sharedOwnershipField').checked) {
		screeningQPassed = false; 
		if($('screeningFailedMsg3')!=null) {  $('screeningFailedMsg3').show(); }
	}
	// 4. Must be Barclays customer
	if($('mainAppBankNameField')!=null && $F('mainAppBankNameField') != 'BARC') {
		screeningQPassed = false; 
		if($('screeningFailedMsg4')!=null) {  $('screeningFailedMsg4').show(); }
	}
	// 5. Total loan value less than 10K
	if($('loanAmountField')!=null && $('loanAmountSecondaryField')!=null) {
		var amount1Field = $('loanAmountField');
		var amount2Field = $('loanAmountSecondaryField');
		var amount1 = 0;
		var amount2 = 0;
		if(amount1Field != null) { amount1 = parseInt(amount1Field.value, 10); }
		if(amount2Field != null) { amount2 = parseInt(amount2Field.value, 10); }
		if(isNaN(''+amount1)) { amount1 = 0; }
		if(isNaN(''+amount2)) { amount2 = 0; }
		var amountTotal = amount1 + amount2;
		if(isNaN(''+amountTotal)) { amountTotal = 0; }
		if(amountTotal < 10000) {
			screeningQPassed = false;
			if($('screeningFailedMsg5')!=null) {  $('screeningFailedMsg5').show(); }
		}
	}
	// 6. Married and applying in single
	if($('mainMaritalStatusField')!=null) {
		if($F('mainMaritalStatusField') == 'M' && !jointApplication()) {
			screeningQPassed = false;
			if($('screeningFailedMsg6')!=null) {  $('screeningFailedMsg6').show(); }
		}
	}

	// Show/hide screening failed messages
	if(screeningQPassed) {
		$('screeningFailedMessagesContainer').hide();
	} else {
		$('screeningFailedMessagesContainer').show();
	}
}

function registerScreeningQuestionsForBHL() {
	// Register these form elements to trigger the screening questions check
	if($('mainAppResidentialStatusField')!=null) { 
		$('mainAppResidentialStatusField').observe('change', checkScreeningQuestionsForBHL); }
	if($('mainUKResidentFieldYes')!=null) { 
		$('mainUKResidentFieldYes').observe('click', checkScreeningQuestionsForBHL); }
	if($('mainUKResidentFieldNo')!=null) { 
		$('mainUKResidentFieldNo').observe('click', checkScreeningQuestionsForBHL); }
	if($('sharedOwnershipField')!=null) { 
		$('sharedOwnershipField').observe('click', checkScreeningQuestionsForBHL); }
	if($('jointApplicationFieldYes')!=null) { 
		$('jointApplicationFieldYes').observe('click', checkScreeningQuestionsForBHL); }
	if($('jointApplicationFieldNo')!=null) { 
		$('jointApplicationFieldNo').observe('click', checkScreeningQuestionsForBHL); }
	if($('mainAppBankNameField')!=null) { 
		$('mainAppBankNameField').observe('change', checkScreeningQuestionsForBHL); }
	if($('loanAmountField')!=null) { 
		$('loanAmountField').observe('keyup', checkScreeningQuestionsForBHL); }
	if($('loanAmountSecondaryField')!=null) { 
		$('loanAmountSecondaryField').observe('keyup', checkScreeningQuestionsForBHL); }
	if($('mainMaritalStatusField')!=null) { 
		$('mainMaritalStatusField').observe('change', checkScreeningQuestionsForBHL); }
}
/**
 * Functions specific to the BHL instance. These should eventually move to a
 * separate file?
 */
function toggleQuestionsForTelephoneApps() {
	// Check
	if($('mainMonthlyOutgoingsContainer')==null) { return; }
	
	var advsourcecode = "";
	if($('advsrcSuggest') != null)
		advsourcecode = $F('advsrcSuggest');

	// If the source code is a telephone source code, show monthly outgoings
	// questions
	if(advsourcecode == 'BPHONE') { 
		$('mainMonthlyOutgoingsContainer').show(); 
	} else { 
		$('mainMonthlyOutgoingsContainer').hide(); 
	}
}

function registerQuestionsForTelephoneApps() {
	$('advsrcSuggest').observe('change', toggleQuestionsForTelephoneApps);
	$('advsrcSuggest').observe('blur', toggleQuestionsForTelephoneApps);	
}

function toggleQuestionsForTLWPanelOnly() {
	if($('considerTLWPanelField')==null) { return; }

	// Ask these questions only if TLW panel has been opted for
	if($('considerTLWPanelField').checked) {
		$('mainDependantsContainer').show();
		$('numberInHouseHoldContainer').show();
		//$('numberCarsInHouseHoldContainer').show();
		$('mainAppNectarCardContainer').show();
	} 
	else {
		$('mainDependantsContainer').hide();
		$('numberInHouseHoldContainer').hide();
		//$('numberCarsInHouseHoldContainer').hide();
		$('mainAppNectarCardContainer').hide();
	}
}

function registerQuestionsForTLWPanelOnly() {
	if($('considerTLWPanelField')==null) { return; }
	$('considerTLWPanelField').observe('click', toggleQuestionsForTLWPanelOnly);
}

function setCursorAfterAddressOp (addressCategory){
	if(addressCategory == 'cust0' || addressCategory == 'prev0' || addressCategory == 'prev1'){
		location.href = '#mainAppDetailsH3';
	} else if(addressCategory == 'custx' || addressCategory == 'preva' || addressCategory == 'prevb'){
		location.href = '#jointAppDetailsH3';
	} else if(addressCategory == 'custs'){
		location.href = '#propertyDetailsH3';
	} else {
		// Scroll up to location in the Template JSPs.
		// This is required when we show Moneio forms in iFrames
		// UPDATE: Do not scroll to top on the Input page - Moneyextra reloads
		// the page for every resize.
		// This cause jump to top on clicking on any element on the page - they
		// should fix this
		// location.href = '#pageTop';
	}
	// 2. Set focus on the correct button
	if(addressCategory == 'cust0' && $('mainAppCurAddressEditBtn') != null) { $('mainAppCurAddressEditBtn').focus(); }
	if(addressCategory == 'prev0' && $('mainAppFirstPrevAddressEditBtn') != null) { $('mainAppFirstPrevAddressEditBtn').focus(); }
	if(addressCategory == 'prev1' && $('mainAppSecondPrevAddressEditBtn') != null) { $('mainAppSecondPrevAddressEditBtn').focus(); }
	if(addressCategory == 'custx' && $('jointAppCurAddressEditBtn') != null) { $('jointAppCurAddressEditBtn').focus(); }
	if(addressCategory == 'preva' && $('jointAppFirstPrevAddressEditBtn') != null) { $('jointAppFirstPrevAddressEditBtn').focus(); }
	if(addressCategory == 'prevb' && $('jointAppSecondPrevAddressEditBtn') != null) { $('jointAppSecondPrevAddressEditBtn').focus(); }
	if(addressCategory == 'custs' && $('propertyAddressEditBtn') != null) { $('propertyAddressEditBtn').focus(); }
}

function showCustomerNameDynamic () {
	var title = $F('mainTitleField');
	var firstname = $F('mainFirstNameField');
	var surname = $F('mainSurnameField');
	$('customerNameSpan').innerHTML = title + ". " + firstname + " " + surname;
}
function registerCustomerNameDynamic() {
	if($('mainTitleField')!=null && $('mainFirstNameField')!=null && $('mainSurnameField')!=null) {
		$('mainTitleField').observe('change', showCustomerNameDynamic);
		$('mainFirstNameField').observe('change', showCustomerNameDynamic);
		$('mainSurnameField').observe('change', showCustomerNameDynamic);
		$('mainTitleField').observe('keyup', showCustomerNameDynamic);
		$('mainFirstNameField').observe('keyup', showCustomerNameDynamic);
		$('mainSurnameField').observe('keyup', showCustomerNameDynamic);
	}
}

function toggleSecuredSpecificPropertyQuestions() {
	// Sanity
	if($('prop0HasOtherOwnersFieldYes') == null 
			|| $('prop0HasOtherOwnersFieldNo') == null  
			|| $('addOtherOwnersToAppFieldYes') == null
			|| $('addOtherOwnersToAppFieldNo') == null
			|| $('input3SubmitBtn') == null) {
		return;
	}
	
	// First, reset everything
	$('input3SubmitBtn').show();
	if($('linkToAddJointAppDetails') != null ) { $('linkToAddJointAppDetails').hide(); }
	if($('notAddingOtherOwnersToAppErrorMessage') != null ) { $('notAddingOtherOwnersToAppErrorMessage').hide(); }
	if($('hasOtherOwnersAlreadyJointApplication') != null ) { $('hasOtherOwnersAlreadyJointApplication').hide(); }
	
	// Next, check first question - does property have other owners?
	if($('prop0HasOtherOwnersFieldYes').checked) {
		
		// Show next question - do you want to add other owners on to loan
		// application?
		$('addOtherOwnersToAppContainer').show();
		
		// Check answer to this question
		if($('addOtherOwnersToAppFieldYes').checked) {
			// Answer Yes. If already joint, just show message. Else show link
			// to add joint, but cannot proceed without adding
			if(window.gr_isJointApplication != 'undefined' && window.gr_isJointApplication == "true") {
				if($('hasOtherOwnersAlreadyJointApplication') != null ) { $('hasOtherOwnersAlreadyJointApplication').show(); }
			} else {
				if($('linkToAddJointAppDetails') != null ) { $('linkToAddJointAppDetails').show(); }
				$('input3SubmitBtn').hide();
			}
		} 
		else if($('addOtherOwnersToAppFieldNo').checked) {
			// Answer No. Show sorry, "can't proceed with secured" message,
			// cannot proceed.
			if($('notAddingOtherOwnersToAppErrorMessage') != null ) { $('notAddingOtherOwnersToAppErrorMessage').show(); }
			$('input3SubmitBtn').hide();
		} 
		else {
			// No answer selected - cannot proceed
			$('input3SubmitBtn').hide();
		}
	} 
	else {
		$('addOtherOwnersToAppContainer').hide();
		$('addOtherOwnersToAppFieldYes').checked = false;
		$('addOtherOwnersToAppFieldNo').checked = false;
	
		// No radio button selected - cannot proceed
		if(!$('prop0HasOtherOwnersFieldNo').checked) { 
			$('input3SubmitBtn').hide();
		}
	}
}

function registerSecuredSpecificPropertyQuestions() {
	if($('prop0HasOtherOwnersFieldYes') != null) { $('prop0HasOtherOwnersFieldYes').observe('click', toggleSecuredSpecificPropertyQuestions); }
	if($('prop0HasOtherOwnersFieldNo') != null) { $('prop0HasOtherOwnersFieldNo').observe('click', toggleSecuredSpecificPropertyQuestions); }
	if($('addOtherOwnersToAppFieldYes') != null) { $('addOtherOwnersToAppFieldYes').observe('click', toggleSecuredSpecificPropertyQuestions); }
	if($('addOtherOwnersToAppFieldNo') != null) { $('addOtherOwnersToAppFieldNo').observe('click', toggleSecuredSpecificPropertyQuestions); }
}

function setupInput2OnLoadForBase() {
	
	// * * JOINT APPLICATION? * *
	toggleJointAppDetails();
	$('jointApplicationFieldYes').observe('click', toggleJointAppDetails);
	$('jointApplicationFieldNo').observe('click', toggleJointAppDetails);
	
	// * * HOMEOWNER-ONLY QUESTIONS * *
	toggleHomeOwnerOnlyQuestions();
	$('mainAppResidentialStatusField').observe('change', toggleHomeOwnerOnlyQuestions);
	
	// Enable Source-Suggest
	if($('advsrcSuggest')!=null) { $('advsrcSuggest').observe('change', clearAutoCompletedSourceDescription); }
	
	// * * OTHER INCOMES * *
	initializeOtherIncomes();
	
	// * * EMPLOYMENTS * *
	initializeEmployments();
	
	// * * PROPERTY * *
	toggleFloors();
	$('propertyTypeField').observe('change', toggleFloors);
	// Secured Property address
	//togglePropertyAddress();
	//$('propertyAddrSameAsCurrentCheckboxField').observe('click', togglePropertyAddress);
	// Secured loan info based on residential status
	togglePropertyDetails();
	$('mainAppResidentialStatusField').observe('change', togglePropertyDetails);
	// Mortgage
	togglePropertyMortgageDetails();
	$('mainAppResidentialStatusField').observe('change', togglePropertyMortgageDetails);
	// Secured loan on property
	togglePropertySecuredLoanDetails();
	$('propertyHasSecLoanCheckboxField').observe('click', togglePropertySecuredLoanDetails);
	// Mortgage rent payment
	toggleMortgageRentPayment();
	$('mainAppResidentialStatusField').observe('change', toggleMortgageRentPayment);	
	// Multiple properties
	toggleNumberMortOnOtherProperties();
	$('hasMultiplePropsFieldYes').observe('click', toggleNumberMortOnOtherProperties);
	$('hasMultiplePropsFieldNo').observe('click', toggleNumberMortOnOtherProperties);
	
	// * * APPLICANT INFO * *
	
	// Gender
	toggleGenderOnTitleJoint();
	$('jointTitleField').observe('change', toggleGenderOnTitleJoint); 
	toggleGenderOnTitleMain();
	$('mainTitleField').observe('change', toggleGenderOnTitleMain);
	
	// Default joint applicant phone to main applicant phone
	setPhoneToMainAppPhone();

	// * * GENERAL * *
	
	// Recommend joint application if applicant has partner but is NOT applying
	// jointly
	toggleJointAppCheckBoxHighlight();
	$('mainMaritalStatusField').observe('change', toggleJointAppCheckBoxHighlight);
	$('jointApplicationFieldYes').observe('click', toggleJointAppCheckBoxHighlight);
	$('jointApplicationFieldNo').observe('click', toggleJointAppCheckBoxHighlight);

	toggleInsuranceChecked();
	if ($('askAboutInsuranceCheckboxField') != null) {
	    $('askAboutInsuranceCheckboxField').observe('click', toggleInsuranceChecked);
    }

    // Wait div on submit
	hideWaitDiv();
	$('submitBtn').observe('click', showWaitDiv);
	
	// * * CONTEXT HELP AND WISE WORDS * *
	
	// Create the map required for ctxtHelp messages
	createCtxtHelpMappings();
	// Which ContextHelp message is currently displayed
	window.curCtxtHelpMessageID;
	// Which container's ContextHelp is currently displayed
	window.curCtxtHelpContainerID;
	// To each element, attach an event handler to display ctxtHelp messages
	attachCtxtHelpToElements();
}

function initializeEmployments() {
	
	// Main applicant employments
	toggleEmploymentDetailsMain();
	toggleCurEmpDetailsMain();
	toggleFirstPrevEmpDetailsMain();
	toggleSecondPrevEmpDetailsMain();
	toggleCurEmpAccountantDetailsMain();
	
	// Joint applicant employments
	toggleEmploymentDetailsJoint();
	toggleCurEmpDetailsJoint();
	toggleFirstPrevEmpDetailsJoint();
	toggleSecondPrevEmpDetailsJoint();
	toggleCurEmpAccountantDetailsJoint();

	// Main Applicant Employment - show previous employment based on duration
	// set in current and previous
	$('mainAppCurEmpDurYearsField').observe('blur', toggleEmploymentDetailsMain);
	$('mainAppCurEmpDurMonthsField').observe('blur', toggleEmploymentDetailsMain);
	$('mainAppFirstPrevEmpDurYearsField').observe('blur', toggleEmploymentDetailsMain);
	$('mainAppFirstPrevEmpDurMonthsField').observe('blur', toggleEmploymentDetailsMain);
	$('mainAppEmpStatusField').observe('change', toggleCurEmpDetailsMain);
	$('mainAppFirstPrevEmpStatusField').observe('change', toggleFirstPrevEmpDetailsMain);
	$('mainAppSecondPrevEmpStatusField').observe('change', toggleSecondPrevEmpDetailsMain);
	if($('mainAppCurEmpHasAccountantField')!=null) { 
		$('mainAppCurEmpHasAccountantField').observe('click', toggleCurEmpAccountantDetailsMain);  
	}

	// Joint Applicant Employment - show previous employment based on duration
	// set in current and previous
	$('jointAppCurEmpDurYearsField').observe('blur', toggleEmploymentDetailsJoint);
	$('jointAppCurEmpDurMonthsField').observe('blur', toggleEmploymentDetailsJoint);
	$('jointAppFirstPrevEmpDurYearsField').observe('blur', toggleEmploymentDetailsJoint);
	$('jointAppFirstPrevEmpDurMonthsField').observe('blur', toggleEmploymentDetailsJoint);
	$('jointAppEmpStatusField').observe('change', toggleCurEmpDetailsJoint);
	$('jointAppFirstPrevEmpStatusField').observe('change', toggleFirstPrevEmpDetailsJoint);
	$('jointAppSecondPrevEmpStatusField').observe('change', toggleSecondPrevEmpDetailsJoint);
	if($('jointAppCurEmpHasAccountantField')!=null) { 
		$('jointAppCurEmpHasAccountantField').observe('click', toggleCurEmpAccountantDetailsJoint);
	}
}
function setupInput2OnLoadForSupport() {
	
	// Do the base set up first
	setupInput2OnLoadForBase();
	
	// On change of any of the name fields, update the Name shown in the
	// customerInformationBar
	registerCustomerNameDynamic();

	// Calculate total loan amount
	setTotalLoanAmount();
	if($('loanAmountField') !=null) { $('loanAmountField').observe('keyup', setTotalLoanAmount); }
	if($('loanAmountSecondaryField') != null) { $('loanAmountSecondaryField').observe('keyup', setTotalLoanAmount); }
}

function setupInput2OnLoadForBHL() {
	
}

function checkShortAppForm()
{
	var homephone = $('mainHomePhoneField').value;
	var workphone = $('mainWorkPhoneField').value;
	var mobilephone = $('mainMobilePhoneField').value;

	if(homephone == '' && workphone == '' && mobilephone == '')
	{
		alert("Please enter a contact telephone number");
		return false;
	}
	
	if(!assessRequirementQuestions())
	{
		alert("Please check mandatory fields");
		return false;
	}
	return true;
}


function checkRequirements()
{
	// Attach listeners to every form element we care about
	attachListenersToShortForm();

	// Validate current form contents
	assessRequirementQuestions();
}

function attachListenersToShortForm()
{
	$('mainUKResidentFieldYes').observe('click', assessRequirementQuestions);
	$('mainUKResidentFieldNo').observe('click', assessRequirementQuestions);
	$('mainHomeIncomeFieldYes').observe('click', assessRequirementQuestions);
	$('mainHomeIncomeFieldNo').observe('click', assessRequirementQuestions);
	$('mainMinimumAgeFieldYes').observe('click', assessRequirementQuestions);
	$('mainMinimumAgeFieldNo').observe('click', assessRequirementQuestions);
	$('mainMinimumAgeFieldYes').observe('click', assessRequirementQuestions);
	$('mainMinimumAgeFieldNo').observe('click', assessRequirementQuestions);
	$('isHomeownerFieldYes').observe('click', assessRequirementQuestions);
	$('isHomeownerFieldNo').observe('click', assessRequirementQuestions);
	
	// * * JOINT APPLICATION? * *
	toggleJointAppDetails();
	$('jointApplicationFieldYes').observe('click', toggleJointAppDetails);
	$('jointApplicationFieldNo').observe('click', toggleJointAppDetails);
}

function assessRequirementQuestions() 
{
	var passed = true;
	
	/* Must be resident in the UK for three years */
	var ukResy = $('mainUKResidentFieldYes');
	var ukRes = $('mainUKResidentFieldNo');
	if (ukResy != null && ukRes != null) {
		if (ukRes.checked) {
			passed = false;
		} 
	}

	/* regular household income */
	var regHouseIncY = $('mainHomeIncomeFieldYes');
	var regHouseIncN = $('mainHomeIncomeFieldNo');
	if(regHouseIncY != null && regHouseIncN != null){
		if (regHouseIncN.checked) {
			passed = false;
		}
	}
	
	/* over 24 years old */
	var over24y = $('mainMinimumAgeFieldYes');
	var over24 = $('mainMinimumAgeFieldNo');
	if (over24y != null && over24 != null) {
		if (over24.checked) {
			passed = false;
		}
	}	

	/* a homeowner */
	var homeownerY = $('isHomeownerFieldYes');
	var homeownerN = $('isHomeownerFieldNo');
	if (homeownerY != null && homeownerN != null) {
		if (homeownerN.checked) {
			passed = false;			
		} 
	}

	if(passed)
	{			
		$('declineShortAppScript').hide();
	}		
	else
	{
		$('declineShortAppScript').show();
	}
	
	return passed;
}
