﻿// PACKER here: http://dean.edwards.name/packer/

var lb_lastPostcodeChecked = null;

var lb_detailedMortgageTypes = { remortgage: {ltvPercent: 100.0, id: 1}, firstTimeBuyer: {ltvPercent: 110.0, id: 2}, selfCertifyRemortgage: {ltvPercent: 95.0, id: 3}, selfCertifyOther: {ltvPercent: 95.0, id: 4}, buyToLet: {ltvPercent: 95.0, id: 5}, purchase: {ltvPercent: 100.0, id: 6}, adverseRemortgage: {ltvPercent: 95.0, id: 7}, adverseOther: {ltvPercent: 95.0, id: 8} };

// URLs for web services
var lb_ajaxBrokerSearchUrl = 'www.bridgingloans.co.uk/forms/MortgageFormBrokerSearch.aspx';
var lb_ajaxProcessLeadUrl = 'www.bridgingloans.co.uk/forms/MortgageFormMailer.aspx';

var lb_ajaxTestBrokerSearchUrl = 'xxx';
var lb_ajaxTestProcessLeadUrl = 'xxx';

/* ==================================================================================
   MORTGAGE FORM VALIDATION SETUP
   ================================================================================== */

// Step 1
addValidation( [ $('LB_MortgageType') ], [{validator: radioButtonListHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_MortgageType_Label'), $('LB_MortgageType_ErrorAdvice'), false, false, true, $('LB_Step1_NextButton'), true, true, false, null, null, null );
addValidation( [ $('LB_AmountToBorrow') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter value, e.g. £225,500"]}, {validator: ValidIntegerValidator, validationData: null, errorMessages: ["Enter valid value"]}, {validator: GreaterThanValueValidator, validationData: {minValue: 24999}, errorMessages: ["Must be £25,000 or over"]}, {validator: LessThanValueValidator, validationData: {maxValue: 5000000}, errorMessages: ["Must be under £5,000,000"]} ], $('LB_AmountToBorrow_Label'), $('LB_AmountToBorrow_ErrorAdvice'), true, true, true, $('LB_Step1_NextButton'), false, true, false, null, null, null, [addCommasToNumberTextbox] );
addValidation( [ $('LB_MortgagePeriod') ], [{validator: selectHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_MortgagePeriod_Label'), $('LB_MortgagePeriod_ErrorAdvice'), false, false, true, $('LB_Step1_NextButton'), false, true, false, null, null, null );
addValidation( [ $('LB_LoanWhen') ], [{validator: selectHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_LoanWhen_Label'), $('LB_LoanWhen_ErrorAdvice'), false, false, true, $('LB_Step1_NextButton'), false, true, false, null, null, null );



// Step 2
addValidation( [ $('LB_PropertyValue') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter value, e.g. £250,000"]}, {validator: ValidIntegerValidator, validationData: null, errorMessages: ["Enter valid value"]}, {validator: GreaterThanValueValidator, validationData: {minValue: 24999}, errorMessages: ["Must be £25,000 or over"]}, {validator: LessThanValueValidator, validationData: {maxValue: 5000000}, errorMessages: ["Must be under £5,000,000"]} ], $('LB_PropertyValue_Label'), $('LB_PropertyValue_ErrorAdvice'), true, true, true, $('LB_Step2_NextButton'), false, true, false, null, null, null, [addCommasToNumberTextbox] );
addValidation( [ $('LB_FirstTimeBuyer') ], [{validator: radioButtonListHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_FirstTimeBuyer_Label'), $('LB_FirstTimeBuyer_ErrorAdvice'), false, false, true, $('LB_Step2_NextButton'), true, true, false, null, null, null );
addValidation( [ $('LB_SelfCertifyIncome') ], [{validator: radioButtonListHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_SelfCertifyIncome_Label'), $('LB_SelfCertifyIncome_ErrorAdvice'), false, false, true, $('LB_Step2_NextButton'), true, true, false, null, null, null );

// Step 2b
var lb_amountToBorrowValidator2 = addValidation( [ $('LB_AmountToBorrow2') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter value, e.g. £225,500"]}, {validator: ValidIntegerValidator, validationData: null, errorMessages: ["Enter valid value"]}, {validator: GreaterThanValueValidator, validationData: {minValue: 24999}, errorMessages: ["Must be £25,000 or over"]}, {validator: LessThanValueValidator, validationData: {maxValue: 5000000}, errorMessages: ["Must be under £5,000,000"]}, {validator: DetailedLtvValidator, validationData: $('LB_PropertyValue2'), errorMessages: ["Amount to borrow is more than ###MAXLTV###% of property value. Amend borrow amount or property value."]} ], $('LB_AmountToBorrow2_Label'), $('LB_AmountToBorrow2_ErrorAdvice'), true, true, true, $('LB_Step2b_NextButton'), false, false, false, null, null, null, [addCommasToNumberTextbox] );
addValidation( [ $('LB_PropertyValue2') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter value, e.g. £250,000"]}, {validator: ValidIntegerValidator, validationData: null, errorMessages: ["Enter valid value"]}, {validator: GreaterThanValueValidator, validationData: {minValue: 24999}, errorMessages: ["Must be £25,000 or over"]}, {validator: LessThanValueValidator, validationData: {maxValue: 5000000}, errorMessages: ["Must be under £5,000,000"]}, {validator: FireAmountToBorrowValidator, validationData: $('LB_AmountToBorrow2'), errorMessages: null} ], $('LB_PropertyValue2_Label'), $('LB_PropertyValue2_ErrorAdvice'), true, true, true, $('LB_Step2b_NextButton'), false, false, false, [lb_amountToBorrowValidator2], null, null, [addCommasToNumberTextbox] );

// Step 3
addValidation( [ $('LB_FirstName') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter first name"]}, {validator: RegexValidator, validationData: "^[-`'\\wÁáĆćÉéÍíĹĺŃńÓóŔŕŚśÚúÝýŹźÀàÈèÌìÒòÙùÂâĈĉÊêĜĝĤĥÎîĴĵÔôŜŝÛûŴŵŶŷÄäËëÏïÖöÜüŸÿßÃãẼẽĨĩÑñÕõŨũỸỹÇçĢģĶķĻļŅņŖŗŞşŢţĐđŮůǍǎČčĎďĚěǏǐĽľŇňǑǒŘřŠšŤťǓǔŽžĀāĒēĪīŌōŪūǢǣǖǘǚǜĂăĔĕĞğĬĭŎŏŬŭĊċĖėĠġİıŻżĄąĘęĮįǪǫŲųḌḍḤḥḶḷḸḹṂṃṆṇṚṛṜṝṢṣṬṭŁłŐőŰűĿŀĦħÐðÞþŒœÆæØøÅåƏə\\s]{2,50}$", errorMessages: ["Enter valid name"]}, {validator: RegexValidator, validationData: "^[\\D]{2,}$", errorMessages: ["Enter valid name"]} ], $('LB_FirstName_Label'), $('LB_FirstName_ErrorAdvice'), true, false, true, $('LB_Step3_FinishButton'), false, false, false, null, null, null );
addValidation( [ $('LB_LastName') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter last name"]}, {validator: RegexValidator, validationData: "^[-`'\\wÁáĆćÉéÍíĹĺŃńÓóŔŕŚśÚúÝýŹźÀàÈèÌìÒòÙùÂâĈĉÊêĜĝĤĥÎîĴĵÔôŜŝÛûŴŵŶŷÄäËëÏïÖöÜüŸÿßÃãẼẽĨĩÑñÕõŨũỸỹÇçĢģĶķĻļŅņŖŗŞşŢţĐđŮůǍǎČčĎďĚěǏǐĽľŇňǑǒŘřŠšŤťǓǔŽžĀāĒēĪīŌōŪūǢǣǖǘǚǜĂăĔĕĞğĬĭŎŏŬŭĊċĖėĠġİıŻżĄąĘęĮįǪǫŲųḌḍḤḥḶḷḸḹṂṃṆṇṚṛṜṝṢṣṬṭŁłŐőŰűĿŀĦħÐðÞþŒœÆæØøÅåƏə\\s]{2,50}$", errorMessages: ["Enter valid name"]}, {validator: RegexValidator, validationData: "^[\\D]{2,}$", errorMessages: ["Enter valid name"]} ], $('LB_LastName_Label'), $('LB_LastName_ErrorAdvice'), true, false, true, $('LB_Step3_FinishButton'), false, false, false, null, null, null );
addValidation( [ $('LB_EmailAddress') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter e-mail address"]}, {validator: EmailAddressValidator, validationData: null, errorMessages: ["Invalid e-mail address"]} ], $('LB_EmailAddress_Label'), $('LB_EmailAddress_ErrorAdvice'), true, false, true, $('LB_Step3_FinishButton'), false, false, false, null, null, null );
addValidation( [ $('LB_PhoneNumber') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter number"]}, {validator: UkPhoneNumberValidator, validationData: null, errorMessages: UkPhoneNumberErrorMessages} ], $('LB_PhoneNumber_Label'), $('LB_PhoneNumber_ErrorAdvice'), true, false, true, $('LB_Step3_FinishButton'), false, false, false, null, null, null );
addValidation( [ $('LB_AlternatePhoneNumber') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter number"]}, {validator: UkPhoneNumberValidator, validationData: null, errorMessages: UkPhoneNumberErrorMessages} ], $('LB_AlternatePhoneNumber_Label'), $('LB_AlternatePhoneNumber_ErrorAdvice'), true, false, true, $('LB_Step3_FinishButton'), false, false, false, null, null, null );
addValidation( [ $('LB_FirstLineAddress') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter address"]}, {validator: RegexValidator, validationData: "^[-`'&:\\.,/\\\\\\(\\)\\wÁáĆćÉéÍíĹĺŃńÓóŔŕŚśÚúÝýŹźÀàÈèÌìÒòÙùÂâĈĉÊêĜĝĤĥÎîĴĵÔôŜŝÛûŴŵŶŷÄäËëÏïÖöÜüŸÿßÃãẼẽĨĩÑñÕõŨũỸỹÇçĢģĶķĻļŅņŖŗŞşŢţĐđŮůǍǎČčĎďĚěǏǐĽľŇňǑǒŘřŠšŤťǓǔŽžĀāĒēĪīŌōŪūǢǣǖǘǚǜĂăĔĕĞğĬĭŎŏŬŭĊċĖėĠġİıŻżĄąĘęĮįǪǫŲųḌḍḤḥḶḷḸḹṂṃṆṇṚṛṜṝṢṣṬṭŁłŐőŰűĿŀĦħÐðÞþŒœÆæØøÅåƏə\\s]{2,128}$", errorMessages: ["Enter valid address"]} ], $('LB_FirstLineAddress_Label'), $('LB_FirstLineAddress_ErrorAdvice'), true, false, true, $('LB_Step3_FinishButton'), false, false, false, null, null, null );
var lb_postcodeValidator = addValidation( [ $('LB_Postcode') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter postcode"]}, {validator: PostcodeValidator, validationData: null, errorMessages: ["Enter valid postcode"]} ], $('LB_Postcode_Label'), $('LB_Postcode_ErrorAdvice'), true, false, true, $('LB_Step3_FinishButton'), false, false, false, null, null, null );
addValidation( [ $('LB_DateOfBirth_Day'), $('LB_DateOfBirth_Month'), $('LB_DateOfBirth_Year') ], [{validator: dateGroupValidator, validationData: null, errorMessages: ["Select date of birth", "Invalid date"]}, {validator: ageValidator, validationData: {minAge: 18, maxAge: 65}, errorMessages: ["Must be 18 or over", "Must be 65 or under"]} ], $('LB_DateOfBirth_Label'), $('LB_DateOfBirth_ErrorAdvice'), false, false, true, $('LB_Step3_FinishButton'), true, false, false, null, null, null );

/* ==================================================================================
   MORTGAGE FORM EVENT SETUP
   ================================================================================== */

// Mortgage Type on Step 1 - defines what is visible on Step 2
addEvent( $('LB_MortgageType'), 'onclick', mortgageTypeChange );
addEvent( $('LB_MortgageType_2'), 'onclick', mortgageTypeChange );
addEvent( $('LB_MortgageType_3'), 'onclick', mortgageTypeChange );

// Back, Next, Finish buttons
addEvent( $('LB_Step1_NextButton'), 'onclick', LB_Step1_NextButton_Event_Click );

addEvent( $('LB_Step2_BackButton'), 'onclick', LB_Step2_BackButton_Event_Click );
addEvent( $('LB_Step2_NextButton'), 'onclick', LB_Step2_NextButton_Event_Click );

addEvent( $('LB_Step2b_BackButton'), 'onclick', LB_Step2b_BackButton_Event_Click );
addEvent( $('LB_Step2b_NextButton'), 'onclick', LB_Step2b_NextButton_Event_Click );

addEvent( $('LB_Step3_BackButton'), 'onclick', LB_Step3_BackButton_Event_Click );
addEvent( $('LB_Step3_FinishButton'), 'onclick', LB_Step3_FinishButton_Event_Click );

// Monitor Postcode field for changes
addEvent( $('LB_Postcode'), 'onkeyup', getBrokerName );
addEvent( $('LB_Postcode'), 'onblur', getBrokerName );
addEvent( $('LB_Postcode'), 'onchange', getBrokerName );

function mortgageTypeChange()
{
	if( this == window )
	{
		//sessionStartPing( "MORTGAGEHTML10", "MORTGAGE" );
	}

	var propertyValueLabel = "What is the estimated value of the property you want to buy?";
	var firstTimeBuyerDivDisplay = "none";

	switch( getRadioButtonListSelectedValue('LB_MortgageType') )
	{
		case 'buy':
		{
			firstTimeBuyerDivDisplay = "";
			break;
		}

		case 'remortgage':
		{
			propertyValueLabel = "What is the estimated value of the property you want to remortgage?";
			break;
		}
	}

	$('LB_FirstTimeBuyer_Div').style.display = firstTimeBuyerDivDisplay;
	$('LB_PropertyValue2_Label').innerHTML = $('LB_PropertyValue_Label').innerHTML = propertyValueLabel;
}

/* ==================================================================================
   MORTGAGE FORM BUTTON EVENT HANDLERS
   ================================================================================== */

function findElementPosition(element)
{
	var curleft = curtop = 0;
	if (element.offsetParent)
	{
		curleft = element.offsetLeft;
		curtop = element.offsetTop;
		while (element = element.offsetParent)
		{
			curleft += element.offsetLeft;
			curtop += element.offsetTop;
		}

	}

	return {left: curleft, top: curtop};
}

// Step 1
function LB_Step1_NextButton_Event_Click( event )
{
	var event = new Event(event);
	
	setCurrentControlFocus( event.target );

	if( validateMultiple( event ) )
	{
		// Change the visible wizard step	
		$('LB_Step1').className = 'LB_FormStep LB_FormStepHidden';
		$('LB_Step3').className = 'LB_FormStep LB_FormStepVisible';

		// Update the status of this session in the database
//		sessionStepPing( "STEP2", 0 );
	}
}

// Step 2
function LB_Step2_BackButton_Event_Click( event )
{
	var event = new Event(event);
	setCurrentControlFocus( event.target );

	$('LB_Step2').className = 'LB_FormStep LB_FormStepHidden';
	$('LB_Step1').className = 'LB_FormStep LB_FormStepVisible';
}

function LB_Step2_NextButton_Event_Click( event )
{
	var event = new Event(event);
	setCurrentControlFocus( event.target );

	if( validateMultiple( event ) )
	{
		$('LB_Step2').className = 'LB_FormStep LB_FormStepHidden';

		// Copy off the values from PropertyValue and AmountToBorrow into the replica boxes on Step2b. If the
		// LTV is out of whack then we can re-present the boxes to the user and get them to adjust the values
		$('LB_PropertyValue2').value = $('LB_PropertyValue').value;
		$('LB_AmountToBorrow2').value = $('LB_AmountToBorrow').value;

		var mortgageType = getRadioButtonListSelectedValue('LB_MortgageType');
		var firstTimeBuyer = parseInt(getRadioButtonListSelectedValue('LB_FirstTimeBuyer'));
		var selfCertifyIncome = parseInt(getRadioButtonListSelectedValue('LB_SelfCertifyIncome'));
		var ltvPercent = calculateLtvPercent( getFloatFromTextbox($('LB_AmountToBorrow')), getFloatFromTextbox($('LB_PropertyValue')) );

		var detailedMortgageType = getDetailedMortgageType( mortgageType, customerHasBadCredit(), firstTimeBuyer, selfCertifyIncome, ltvPercent );

		// Re-check the Loan-To-Value now that we have ALL the information we need to make a decision (e.g. credit score)
		if( ltvPercent > detailedMortgageType.ltvPercent )
		{
			// If Loan-To-Value is now too high, then we need to show user the Property Value and Amount To Borrow and get
			// them to change one
			$('LB_LtvProblem').innerHTML = 'Amount you wish to borrow is more than ' + detailedMortgageType.ltvPercent + '% of your property value. Please amend Amount To Borrow or your Property Value.';
			$('LB_Step2b').className = 'LB_FormStep LB_FormStepVisible';

			// Update the status of this session in the database
//			sessionStepPing( "STEP2B", 0 );
		}
		else
		{
			// Otherwise, if Loan-To-Value is fine, jump to last Step (Contact Details) as normal
			$('LB_Step3').className = 'LB_FormStep LB_FormStepVisible';

			// Update the status of this session in the database
//			sessionStepPing( "STEP3", 0 );

			// We call this here in case they've gone back through the form and changed an earlier value - we now
			// need to get a new broker name for them as the type of lead might have changed
			getBrokerName(true);
		}
	}
}

// Step 2b
function LB_Step2b_BackButton_Event_Click( event )
{
	var event = new Event(event);
	setCurrentControlFocus( event.target );

	// Copy back the values from PropertyValue2 and AmountToBorrow2 into the original boxes on Step1 & 2.
	$('LB_PropertyValue').value = $('LB_PropertyValue2').value;
	$('LB_AmountToBorrow').value = $('LB_AmountToBorrow2').value;

	$('LB_Step2b').className = 'LB_FormStep LB_FormStepHidden';
	$('LB_Step2').className = 'LB_FormStep LB_FormStepVisible';
}

function LB_Step2b_NextButton_Event_Click( event )
{
	var event = new Event(event);
	setCurrentControlFocus( event.target );

	// Copy back the values from PropertyValue2 and AmountToBorrow2 into the original boxes on Step1 & 2.
	$('LB_PropertyValue').value = $('LB_PropertyValue2').value;
	$('LB_AmountToBorrow').value = $('LB_AmountToBorrow2').value;

	if( validateMultiple( event ) )
	{
		$('LB_Step2b').className = 'LB_FormStep LB_FormStepHidden';
		$('LB_Step3').className = 'LB_FormStep LB_FormStepVisible';

		// Update the status of this session in the database
//		sessionStepPing( "STEP3", 0 );

		// We call this here in case they've gone back through the form and changed an earlier value - we now
		// need to get a new broker name for them as the type of lead might have changed
		getBrokerName(true);
	}
}

// Step 3
function LB_Step3_BackButton_Event_Click( event )
{
	var event = new Event(event);
	setCurrentControlFocus( event.target );

	$('LB_Step3').className = 'LB_FormStep LB_FormStepHidden';
	$('LB_Step1').className = 'LB_FormStep LB_FormStepVisible';
}

function LB_Step3_FinishButton_Event_Click( event )
{
	var event = new Event(event);
	setCurrentControlFocus( event.target );

	if( validateMultiple( event ) )
	{
		$('LB_Step3_FinishButton').disabled = true;
		$('LB_Step3_FinishButton').value = "Submitting details...";

//		var stepPosition = findElementPosition($('LB_Step3'));

//		$('back').style.left = stepPosition.left;
//		$('back').style.top = stepPosition.top;
//		$('back').style.width = $('LB_Step3').offsetWidth;
//		$('back').style.height = $('LB_Step3').offsetHeight;
//		$('back').style.visibility = "visible";


//		$('indicator').style.left = stepPosition.left + (($('LB_Step3').offsetWidth - $('indicator').offsetWidth) / 2) + "px";
//		$('indicator').style.top = stepPosition.top + (($('LB_Step3').offsetHeight - $('indicator').offsetHeight) / 2) + "px";
//		$('indicator').style.visibility = "visible";		
		
		setTimeout('revertSubmitButton()', 20000);
		
		submitLead();
	}
	
	return false;
}

function revertSubmitButton()
{
	$('LB_Step3_FinishButton').disabled = false;
	$('LB_Step3_FinishButton').value = "Submit";
	
//	$('LB_SubmitIndicator').style.visibility = "hidden";
//	$('LB_AlphaLayer').style.visibility = "hidden";

	return;
}

/* ==================================================================================
   JSON AJAX MORTGAGE CALLBACK FUNCTIONS
   ================================================================================== */

function BrokerSearchCallback(BrokerDetails)
{
	if( BrokerDetails )
	{
		if( BrokerDetails.Error.ErrorNumber == '0' )
		{
			var BrokerText = BrokerDetails.Broker.DisplayText;
			BrokerText = BrokerText.replace('Based on your loan requirements we have selected the specialist bridging loan adviser called ', '');
			BrokerText = BrokerText.replace(' to help you with your enquiry. ', '');
			BrokerText = BrokerText.replace('Please click Submit to confirm that you are happy for them to contact you by telephone.', '');
			$('LB_BrokerName').innerHTML = BrokerText.replace(/&amp;/g, "&");
			$('LB_Consent').style.visibility = 'visible';
			$('LB_SessionId').value = BrokerDetails.Broker.Id;
			$('LB_Step3_FinishButton').disabled = false;
			$('LB_Step3_FinishButton').value = "Submit";
		}
		else
		{
			$('LB_BrokerName').innerHTML = 'ERROR ' + BrokerDetails.Error.ErrorMessage;
			$('LB_Consent').style.visibility = 'hidden';
			$('LB_SessionId').value = '';
		}
	}
}

function ProcessLeadCallback( returnData )
{
	var grossLeadPrice = 0;

	if( returnData.Lead && returnData.Lead.GrossPrice )
	{
		grossLeadPrice = returnData.Lead.GrossPrice;
	}

	switch( returnData.Error.ErrorNumber )
	{
		case '235':
		case '0':
		{
			// Update the status of this session in the database
//			sessionStepPing( "FINISH", 1, "&lp=" + grossLeadPrice );

			if( lb_redirectThankYouPage )
			{
				if( lb_leadPriceQueryStringParameterName )
				{
					if( lb_thankYouPageHref.indexOf("?") > 0 )
					{
						lb_thankYouPageHref += "&" + lb_leadPriceQueryStringParameterName + "=" + grossLeadPrice;
					}
					else
					{
						lb_thankYouPageHref += "?" + lb_leadPriceQueryStringParameterName + "=" + grossLeadPrice;
					}
				}
							
				window.location.href = lb_thankYouPageHref;
			}
			else
			{
				$('LB_Step3').className = 'LB_FormStep LB_FormStepHidden';
				$('LB_Step4').className = 'LB_FormStep LB_FormStepVisible';
			}
			
			break;
		}

		case '100':
		{
			setControlToErrorState( lb_postcodeValidator, "Enter valid UK postcode" );
			break;
		}
		
		default:
		{
			// Unknown error
			break;
		}
	}
}

/* ==================================================================================
   JSON AJAX MORTGAGE CALLOUT FUNCTIONS
   ================================================================================== */

function buildBasicQueryString()
{
	var postcode = $('LB_Postcode').value.trim().toUpperCase();

	var queryString = '?FormType=BridgingLoan&';
	
	switch( getRadioButtonListSelectedValue('LB_MortgageType') )
	{
		case 'remortgage':
		{
			queryString += 'Mortgage_Type=Residential%20property';
			break;
		}				
		case 'buyToLet':
		{
			queryString += 'Mortgage_Type=Commercial%20property';
			break;
		}
		case 'buy':
		{
			queryString += 'Mortgage_Type=Building%20plot';
			break;
		}
	}

	queryString += '&Mortgage_Size=' + $('LB_AmountToBorrow').value;
	queryString += '&Postcode=' + escape(postcode);


	return queryString;
}

function getBrokerName(overrideIdenticalPostcodeCheck)
{
	var postcode = $('LB_Postcode').value.trim().toUpperCase();

	if( lb_lastPostcodeChecked == postcode && overrideIdenticalPostcodeCheck != true )
	{
		return;
	}
	else
	{
		lb_lastPostcodeChecked = postcode;
	}

	if( postcodeTest( postcode ) != -1 )
	{
		$('LB_Consent').style.visibility = 'hidden';
		$('LB_SessionId').value = '';
		$('LB_Step3_FinishButton').disabled = false;
		$('LB_Step3_FinishButton').value = "Submit";
		return;
	}

	$('LB_Step3_FinishButton').disabled = true;
	$('LB_Step3_FinishButton').value = "Searching...";

	var queryString = buildBasicQueryString();

	if( lb_testing )
	{
		remoteJson({"uri": getPageProtocol() + lb_ajaxTestBrokerSearchUrl + queryString});
	}
	else
	{
		remoteJson({"uri": getPageProtocol() + lb_ajaxBrokerSearchUrl + queryString});
	}

	return true;
}

function submitLead()
{
	if( $('LB_SessionId').value.length < 1 || $('LB_SessionId').value == '' )
	{
		getBrokerName();
	}

	var queryString = buildBasicQueryString();
	
	queryString += '&First_Name=' + $('LB_FirstName').value;
	queryString += '&Surname=' + $('LB_LastName').value;
	queryString += '&DOBday=' + $('LB_DateOfBirth_Day').value;
	queryString += '&DOBmonth=' + $('LB_DateOfBirth_Month').value;
	queryString += '&DOByear=' + $('LB_DateOfBirth_Year').value;
	queryString += '&adr1=' + $('LB_FirstLineAddress').value;
	queryString += '&Home_Phone=' + $('LB_PhoneNumber').value;
	queryString += '&Work_Phone=' + $('LB_AlternatePhoneNumber').value;
	queryString += '&Mobile_Phone=&Email=' + $('LB_EmailAddress').value;
	queryString += '&Payment_Term=' + $('LB_MortgagePeriod').value;
	queryString += '&Loan_When=' + $('LB_LoanWhen').value;

	if( lb_testing )
	{
		remoteJson({"uri": getPageProtocol() + lb_ajaxTestProcessLeadUrl + queryString});
	}
	else
	{
		remoteJson({"uri": getPageProtocol() + lb_ajaxProcessLeadUrl + queryString});
	}
	
	return true;
}

/* ==================================================================================
   VALIDATORS - MORTGAGE SPECIFIC
   ================================================================================== */

function FireAmountToBorrowValidator( event, controls, validation, extraValidators )
{
	// Check if AmountToBorrow is filled out
	if( validation.validationData.value.length > 0 )
	{
		delayedValidate.attempt( event, extraValidators[0] );
	}
	
	return {errorCode: -1};
}

function BasicLtvValidator( event, controls, validation, extraValidators )
{
	// Check if PropertyValue is filled out
	if( validation.validationData.value.length > 0 )
	{
		var amountToBorrow = parseFloat(controls[0].value);
		var propertyValue = getFloatFromTextbox(validation.validationData);

		var loanToValuePercent = calculateLtvPercent( amountToBorrow, propertyValue );

		if( loanToValuePercent > 110.0 )
		{
			return {errorCode: 0};
		}
	}
	
	return {errorCode: -1};
}

function DetailedLtvValidator( event, controls, validation, extraValidators )
{
	// Check if PropertyValue is filled out
	if( validation.validationData.value.length > 0 )
	{
		var mortgageType = getRadioButtonListSelectedValue('LB_MortgageType');
		var firstTimeBuyer = parseInt(getRadioButtonListSelectedValue('LB_FirstTimeBuyer'));
		var selfCertifyIncome = parseInt(getRadioButtonListSelectedValue('LB_SelfCertifyIncome'));
		var ltvPercent = calculateLtvPercent( parseFloat(controls[0].value), getFloatFromTextbox(validation.validationData) );

		var detailedMortgageType = getDetailedMortgageType( mortgageType, customerHasBadCredit(), firstTimeBuyer, selfCertifyIncome, ltvPercent );

		if( ltvPercent > detailedMortgageType.ltvPercent )
		{
			return {errorCode: 0, errorMessage: validation.errorMessages[0].replace(/###MAXLTV###/, detailedMortgageType.ltvPercent) };
		}
	}
	
	return {errorCode: -1};
}


/* ==================================================================================
   UTILITY FUNCTIONS - MORTGAGE SPECIFIC
   ================================================================================== */

function calculateLtvPercent( amountToBorrow, propertyValue )
{
	return ( amountToBorrow / propertyValue ) * 100.0;
}

function customerHasBadCredit()
{
	if( $('LB_CCJ').checked || $('LB_MissedPayments').checked || $('LB_Bankrupt_IVA').checked )
	{
		return true;
	}
	
	return false;
}

// Check Visio diagram named "Mortgage Types Flowchart.vsd" for a flowchart of this
function getDetailedMortgageType( basicMortgageType, badCredit, firstTimeBuyer, selfCertifyIncome, ltvPercent )
{
	switch( basicMortgageType )
	{
		case 'buy':
			if( firstTimeBuyer )
			{
				if( badCredit && ( ltvPercent <= lb_detailedMortgageTypes.adverseOther.ltvPercent ) )
				{
					return lb_detailedMortgageTypes.adverseOther;
				}
				else
				{
					return lb_detailedMortgageTypes.firstTimeBuyer;
				}
			}
			else
			{
				if( badCredit )
				{
					return lb_detailedMortgageTypes.adverseOther;
				}
				else
				{
					if( selfCertifyIncome )
					{
						return lb_detailedMortgageTypes.selfCertifyOther;
					}
					else
					{
						return lb_detailedMortgageTypes.purchase;
					}
				}
			}

		case 'remortgage':
			if( selfCertifyIncome )
			{
				return lb_detailedMortgageTypes.selfCertifyRemortgage;
			}
			else
			{
				if( badCredit )
				{
					return lb_detailedMortgageTypes.adverseRemortgage;
				}
				else
				{
					return lb_detailedMortgageTypes.remortgage;
				}
			}

		case 'buyToLet':
			if( badCredit )
			{
				return lb_detailedMortgageTypes.adverseOther;
			}
			else
			{
				return lb_detailedMortgageTypes.buyToLet;
			}
	}
}
