/**
	* DOM.JS
	* Contains JS for DOM manipulation on the Input and Result pages.
	* Dependency: Prototype JS library (currently using version 1.6.0.3)
	* Copyright Moneio 2009
*/

/**
 * OTHER INCOMES
 */
// This must be called first
function initializeOI() {
	// 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 only registering
 */

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();
	}
	else {
		$('curEmpEmployerNameMain').hide();
		$('curEmpJobDescMain').hide();
	 	$('curEmpGrossIncomeMain').hide();
	 	$('curEmpNetIncomeMain').hide();
	}
	
	// If self-employed, also ask accountant questions
	if($('curEmpHasAccountantMain')!=null) {
		if(value == 'S' || value == 'M') {
			$('curEmpHasAccountantMain').show();
		} 
		else {
			$('mainAppCurEmpHasAccountantField').checked = false;
			$('curEmpHasAccountantMain').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();
	}
	else {
		$('curEmpEmployerNameJoint').hide();
		$('curEmpJobDescJoint').hide();		 
	 	$('curEmpIncomeJoint').hide();
	 	$('curEmpNetIncomeJoint').hide();
	}
	
	// If self-employed, also ask accountant questions
	if($('curEmpHasAccountantJoint')!=null) {
		if(value == 'S' || value == 'M') {
			$('curEmpHasAccountantJoint').show();
		} 
		else {
			$('jointAppCurEmpHasAccountantField').checked = false;
			$('curEmpHasAccountantJoint').hide();
		}
	}
}

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') { // Show details
		$('propertyFloors').show();
	} else { // Hide details
	 	$('propertyFloors').hide();
	}
}
function toggleCouncilDiscount() {
	var chkBox = $('prop0-council-house');
	if(chkBox.checked) { // Show
		$('prop0-council-disc-group').show();
	} else { // Remove
		$('prop0-council-disc-group').hide();
		$('propertyCouncilDiscountField').value = '';
	}
}

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

/**
 * SECURED PROPERTY MORTGAGE AND SECURED LOAN
 */
function removePropertyMortgage() { 
	$('propertyMortgageDetailsContainer').hide();
	$('stat0-mort-hist-group').hide();
	$('mortgageHistoryYearsField').value = '';
	$('mortgageHistoryMonthsField').value = '';
	$('mortgageLenderCodeField').selectedIndex = 0;
	$('mortgageLenderCodeField').options[0].selected = true; // Cross-browser protection
	$('mortgageRepaymentField').value = '';
	$('mortgageOutstandingField').value = '';
}

function removePropertySecuredLoan() { 
	$('propertySecLoanDetailsContainer').hide();
	$('secLoanLenderCodeField').selectedIndex = 0;
	$('secLoanLenderCodeField').options[0].selected = true; // Cross-browser protection
	$('secLoanRepaymentField').value = '';
	$('secLoanOutstandingField').value = '';
}

function togglePropertyMortgage2() {
	var value = $('mainAppResidentialStatusField').value;
	// Residential status = Home-owner with Mortgage
	if(value == 'M') {
		$('stat0-mort-hist-group').show(); // Show duration
		$('propertyMortgageDetailsContainer').show();
	} else {
		removePropertyMortgage();
	}
}

function togglePropertySecuredLoan() {
	var chkBox = $('propertyHasSecLoanCheckboxField');
	if(chkBox.checked) { // Show
		$('propertySecLoanDetailsContainer').show();
	} else {
		removePropertySecuredLoan();
	}
}

/**
 * TOGGLE SECURED LOAN INFO
 */
function showSecuredLoanInfo() { 
	$('securedLoanInfo').show();
}

function removeSecuredLoanInfo() {
	$('securedLoanInfo').hide();
}

function toggleSecuredLoanInfo() {
	var chkBox = $('showSecuredLoanInfoCheckboxField');
	if(chkBox.checked) {
		showSecuredLoanInfo();
	} else {
		removeSecuredLoanInfo();
	}
}

function toggleSecuredLoanInfo2() {
	var resStatus = $('mainAppResidentialStatusField').value;
	if(resStatus == 'M' || resStatus == 'H') {
		showSecuredLoanInfo();
	} else {
		removeSecuredLoanInfo();
	}
}

function toggleTerm() {
	if(window.termFormVisible == 1) {
		$('loanTermForm').hide();
		window.termFormVisible = 0;
	} else {
		$('loanTermForm').show();
		window.termFormVisible = 1;
	}
}

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 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();
	}
}

function submitForLenderCompare() {
	// Validate
	// Set lendercodes into URL
	// Creating URL of form '/compareLenders.do ? thisPage=pagename & checkBox1=value & checkBox2=value'
	// where checkbox1 = name of a ticked checkbox, value = check box value (lender code)
	var url = window.compareActionURL;
	var lenderCount = 0;
	for(i=0;i<20;i++) {
		var chkBox = $('compare-'+i);
		if(chkBox!=null && chkBox.checked) {
			url = url + '&' +'compare-' + i + '=' + chkBox.value;
			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.mainUKResidentField = 'ukResidentContainer';
	ctxtHelpMap.mainAppNationalityField = 'mainAppNationalityContainer';
	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 = 'mainAppCurEmpNetIncomeField';
	ctxtHelpMap.mainAppCurEmpGrossIncomeField = 'mainAppCurEmpGrossIncomeField';
	ctxtHelpMap.addOtherIncomesCheckBoxMain = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeDescField102 = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeDescField101 = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeDescField103 = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeValueField101 = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeValueField102 = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.otherIncomeValueField103 = 'mainAppAdditionalIncomeContainer';
	ctxtHelpMap.isJointAppCheckboxField = 'jointApplicationContainer';
	ctxtHelpMap.jointAppDOBDateField = 'jointAppDOBContainer';
	ctxtHelpMap.jointAppDOBMonthField = 'jointAppDOBContainer';
	ctxtHelpMap.jointAppDOBYearField = 'jointAppDOBContainer';
	ctxtHelpMap.jointAppEmailField = 'jointAppEmailContainer';
	ctxtHelpMap.jointAppTimeAtCurAddrYearsField = 'jointAppTimeAtCurAddrContainer';
	ctxtHelpMap.jointAppTimeAtCurAddrMonthsField = 'jointAppTimeAtCurAddrContainer';
	ctxtHelpMap.numberOfEmploymentsJoint = 'jointAppNumberOfJobsContainer';
	ctxtHelpMap.jointAppCurEmpJobDescField = 'jointAppCurEmploymentContainer';
	ctxtHelpMap.jointAppCurEmpEmployerNameField = 'jointAppCurEmploymentContainer';
	ctxtHelpMap.jointAppEmpStatusField = 'jointAppCurEmploymentContainer';
	ctxtHelpMap.jointAppCurEmpDurYearsField = 'jointAppCurEmploymentContainer';
	ctxtHelpMap.jointAppCurEmpDurMonthsField = 'jointAppCurEmploymentContainer';
	ctxtHelpMap.jointAppCurEmpIncomeField = 'jointAppCurEmploymentContainer';
	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.mainUKResidentField = '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.showSecuredLoanInfoCheckboxField = 'doSearchSecLoansContainer';
	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.hasMultiplePropsCheckboxField = 'multiplePropertyContainer';
	ctxtHelpMap.propertyHasMortgageCheckboxField = 'propertyHasMortgageContainer';
	ctxtHelpMap.mortgageLenderCodeField = 'propertyMortgageDetailsContainer';
	ctxtHelpMap.mortgageRepaymentField = 'propertyMortgageDetailsContainer';
	ctxtHelpMap.mortgageOutstandingField = 'propertyMortgageDetailsContainer';
	ctxtHelpMap.sendNoMarketingCheckboxField = 'sendMarketingMailContainer';
	ctxtHelpMap.agreeTermsCheckboxField = 'agreeTermsContainer';
	ctxtHelpMap.usernameField = 'mainAppSignUpInfoContainer';
	ctxtHelpMap.newPassword = 'mainAppSignUpInfoContainer';
	ctxtHelpMap.confirmationPassword = 'mainAppSignUpInfoContainer';
}

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);
	 	}
	}
}

function showCtxtHelp() {
	var invokingElementID = this.id;
	
	// 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 = ID of enclosing container plus 'CtxtHelp' suffix
	var ctxtHelpID = invokingContainerID + 'CtxtHelp';
	
    // If ctxtHelpID is valid, and is not already being displayed
	if($(ctxtHelpID) != null && window.curCtxtHelpMessageID != ctxtHelpID) {
	
	    // Deactivate currently active container
	    if($(window.curCtxtHelpContainerID) != null) {
			$(window.curCtxtHelpContainerID).removeClassName('active');
		}
		// Hide currently displayed CtxtHelp message
		if($(window.curCtxtHelpMessageID) != null) {
			$(window.curCtxtHelpMessageID).hide();
		}
		// Show new
		$(invokingContainerID).addClassName('active');
		// commented Appear Effect - breaks in IE 6
		// $(ctxtHelpID).appear({ duration: 0.4 });
		$(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
 */
// For Support CustomerReferenceBar
function showCustomerNameDynamic () {
	var title = $F('mainTitleField');
	var firstname = $F('mainFirstNameField');
	var surname = $F('mainSurnameField');
	$('customerNameSpan').firstChild.data = title + ". " + firstname + " " + surname;		
}

/**
 * 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 toggleJointAppDetails() {
	var chkBox = $('isJointAppCheckboxField');
	if(chkBox.checked) {
		$('jointAppDetailsContainer').show();
	}
	else {
		$('jointAppDetailsContainer').hide();
	}
}

function toggleJointAppCheckBoxHighlight() {
	var maritalStat = $('mainMaritalStatusField').value;
	if(maritalStat == 'M' || maritalStat == 'L' || maritalStat == 'C') {
		$('jointApplicationContainer').addClassName('highlight');
		$('maritalStatusMessageForJointApp').show();
		$('genericMessageForJointApp').hide();
	} else {
		$('jointApplicationContainer').removeClassName('highlight');
		$('maritalStatusMessageForJointApp').hide();
		$('genericMessageForJointApp').show();
	}
}

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;;
	var searshSecuredChkBox = $('showSecuredLoanInfoCheckboxField');

	if(resStatus == 'T' || resStatus == 'U' || resStatus == 'W') {
		// tenant or living with parents
		$('mainMortgageRentContainer').show();
	} else if(resStatus == 'M' && (searshSecuredChkBox.value == 'Y' || searshSecuredChkBox.checked)) {
		// Has mortgage, and is searching secured
		$('mainMortgageRentContainer').hide();
	} else if(resStatus == 'H') {
		// Homeowner with no mortgage
		$('mainMortgageRentContainer').hide();
	} else {
		// Has mortgage and is not searching secured
		$('mainMortgageRentContainer').show();
	}
}

/**
 * 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;
}

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