// PACKER here: http://dean.edwards.name/packer/

var lb_lastPostcodeChecked = null;
var lb_basicLoanType;
var lb_speakToDebtSpecialist = "0";

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 = 'loans.leadbay.co.uk/webservice/broker_search_advanced_webservice.aspx';
var lb_ajaxProcessLeadUrl = 'loans.leadbay.co.uk/webservice/process_lead_advanced_webservice.aspx';

var lb_ajaxTestBrokerSearchUrl = 'testloans.leadbay.co.uk/webservice/broker_search_advanced_webservice.aspx';
var lb_ajaxTestProcessLeadUrl = 'testloans.leadbay.co.uk/webservice/process_lead_advanced_webservice.aspx';

/* ==================================================================================
   FORM VALIDATION SETUP
   ================================================================================== */

// Step 1
addValidation( [ $('LB_AmountToBorrow') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter value, e.g. £12,500"]}, {validator: ValidIntegerValidator, validationData: null, errorMessages: ["Enter valid value"]}, {validator: GreaterThanValueValidator, validationData: {minValue: 249}, errorMessages: ["Must be £250 or over"]}, {validator: LessThanValueValidator, validationData: {maxValue: 1000000}, errorMessages: ["Must be £1,000,000 or under"]} ], $('LB_AmountToBorrow_Label'), $('LB_AmountToBorrow_ErrorAdvice'), true, true, true, $('LB_Step1_NextButton'), false, true, false, null, null, null, [addCommasToNumberTextbox] );
addValidation( [ $('LB_LoanDuration') ], [{validator: selectHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_LoanDuration_Label'), $('LB_LoanDuration_ErrorAdvice'), false, false, true, $('LB_Step1_NextButton'), false, true, false, null, null, null );
addValidation( [ $('LB_LoanPurpose') ], [{validator: selectHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_LoanPurpose_Label'), $('LB_LoanPurpose_ErrorAdvice'), false, false, true, $('LB_Step1_NextButton'), false, true, false, null, null, null );
addValidation( [ $('LB_ResidentialStatus') ], [{validator: selectHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_ResidentialStatus_Label'), $('LB_ResidentialStatus_ErrorAdvice'), false, false, true, $('LB_Step1_NextButton'), false, true, false, null, null, null );
addValidation( [ $('LB_MonthlyIncome') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter value, e.g. £1,500"]}, {validator: ValidIntegerValidator, validationData: null, errorMessages: ["Enter valid value"]}, {validator: LessThanValueValidator, validationData: {maxValue: 50000}, errorMessages: ["Enter valid value"]} ], $('LB_MonthlyIncome_Label'), $('LB_MonthlyIncome_ErrorAdvice'), true, true, true, $('LB_Step1_NextButton'), false, true, false, null, null, null, [addCommasToNumberTextbox] );
addValidation( [ $('LB_EmploymentStatus') ], [{validator: selectHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_EmploymentStatus_Label'), $('LB_EmploymentStatus_ErrorAdvice'), false, false, true, $('LB_Step1_NextButton'), false, true, false, null, null, null );

// Step 2
addValidation( [ $('LB_LoanType') ], [{validator: radioButtonListHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_LoanType_Label'), $('LB_LoanType_ErrorAdvice'), false, false, true, $('LB_Step2_NextButton'), true, true, false, null, null, null );

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_MortgageBalance') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter balance, e.g. £158,500"]}, {validator: ValidIntegerValidator, validationData: null, errorMessages: ["Enter valid balance"]}, {validator: GreaterThanValueValidator, validationData: {minValue: 999}, errorMessages: ["Must be £1,000 or over"]}, {validator: LessThanValueValidator, validationData: {maxValue: 5000000}, errorMessages: ["Must be under £5,000,000"]} ], $('LB_MortgageBalance_Label'), $('LB_MortgageBalance_ErrorAdvice'), true, true, true, $('LB_Step2_NextButton'), false, true, false, null, null, null, [addCommasToNumberTextbox] );

addValidation( [ $('LB_VehiclePurchaseType') ], [{validator: selectHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_VehiclePurchaseType_Label'), $('LB_VehiclePurchaseType_ErrorAdvice'), false, false, true, $('LB_Step2_NextButton'), false, true, false, null, null, null );

addValidation( [ $('LB_DebtAmount') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter amount, e.g. £25,000"]}, {validator: ValidIntegerValidator, validationData: null, errorMessages: ["Enter valid amount"]}, {validator: GreaterThanValueValidator, validationData: {minValue: 249}, errorMessages: ["Must be £250 or over"]}, {validator: LessThanValueValidator, validationData: {maxValue: 1000000}, errorMessages: ["Must be under £1,000,000"]} ], $('LB_DebtAmount_Label'), $('LB_DebtAmount_ErrorAdvice'), true, true, true, $('LB_Step2_NextButton'), false, true, false, null, null, null, [addCommasToNumberTextbox] );
addValidation( [ $('LB_DebtsToMoreThanOneCompany') ], [{validator: radioButtonListHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_DebtsToMoreThanOneCompany_Label'), $('LB_DebtsToMoreThanOneCompany_ErrorAdvice'), false, false, true, $('LB_Step2_NextButton'), true, true, false, null, null, null );
addValidation( [ $('LB_RentMortgagePayment') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter amount, e.g. £570"]}, {validator: ValidIntegerValidator, validationData: null, errorMessages: ["Enter valid amount"]}, {validator: LessThanValueValidator, validationData: {maxValue: 10000}, errorMessages: ["Must be under £10,000"]} ], $('LB_RentMortgagePayment_Label'), $('LB_RentMortgagePayment_ErrorAdvice'), true, true, true, $('LB_Step2_NextButton'), false, true, false, null, null, null, [addCommasToNumberTextbox] );
addValidation( [ $('LB_LivingArrangement') ], [{validator: selectHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_LivingArrangement_Label'), $('LB_LivingArrangement_ErrorAdvice'), false, false, true, $('LB_Step2_NextButton'), false, true, 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_Step2_NextButton'), true, false, false, null, null, null );
addValidation( [ $('LB_AdverseCredit') ], [{validator: radioButtonListHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_AdverseCredit_Label'), $('LB_AdverseCredit_ErrorAdvice'), false, false, true, $('LB_Step2_NextButton'), true, true, false, null, null, null );

// Step 3
addValidation( [ $('LB_FirstName') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter first name"]}, {validator: RegexValidator, validationData: "^[-`'\\wÁáCcÉéÍíLlNnÓóRrSsÚúÝýZzÀàÈèÌìÒòÙùÂâCcÊêGgHhÎîJjÔôSsÛûWwYyÄäËëÏïÖöÜüŸÿßÃã??IiÑñÕõUu??ÇçGgKkLlNnRrSsTtÐdUuAaCcDdEeIiLlNnOoRrŠšTtUuŽžAaEeIiOoUu??uuuuAaEeGgIiOoUuCcEeGgIiZzAaEeIiOoUu????????????????????LlOoUu??HhÐðÞþŒœÆæØøÅå??\\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ÁáCcÉéÍíLlNnÓóRrSsÚúÝýZzÀàÈèÌìÒòÙùÂâCcÊêGgHhÎîJjÔôSsÛûWwYyÄäËëÏïÖöÜüŸÿßÃã??IiÑñÕõUu??ÇçGgKkLlNnRrSsTtÐdUuAaCcDdEeIiLlNnOoRrŠšTtUuŽžAaEeIiOoUu??uuuuAaEeGgIiOoUuCcEeGgIiZzAaEeIiOoUu????????????????????LlOoUu??HhÐðÞþŒœÆæØøÅå??\\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ÁáCcÉéÍíLlNnÓóRrSsÚúÝýZzÀàÈèÌìÒòÙùÂâCcÊêGgHhÎîJjÔôSsÛûWwYyÄäËëÏïÖöÜüŸÿßÃã??IiÑñÕõUu??ÇçGgKkLlNnRrSsTtÐdUuAaCcDdEeIiLlNnOoRrŠšTtUuŽžAaEeIiOoUu??uuuuAaEeGgIiOoUuCcEeGgIiZzAaEeIiOoUu????????????????????LlOoUu??HhÐðÞþŒœÆæØøÅå??\\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 );

/* ==================================================================================
   FORM EVENT SETUP
   ================================================================================== */

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

var myTips;

function formStartup()
{
	$('LB_AdverseCredit_TooltipImage').title = "Adverse Credit :: Answer \"Yes\" if you have any of the following:<ul><li>Mortgage arrears</li><li>Defaults</li><li>County Court Judgements (CCJs)</li><li>Bankruptcy</li><li>Individual Voluntary Agreement (IVA)</li><li>House repossession</li></ul>";
	$('LB_MonthlyIncome_TooltipImage').title = "Monthly Income :: Total income you receive in your bank account each month (after tax), either from your work or benefits received";
	$('LB_MortgageBalance_TooltipImage').title = "Mortgage Balance :: Total amount you still owe before your mortgage is fully paid off";
	$('LB_DebtAmount_TooltipImage').title = "Total Money Owed :: Value of all debts you owe, not just the ones you wish to consolidate. This includes: loans, credit and store cards, car loans, overdrafts and student loans";
	$('LB_DebtsToMoreThanOneCompany_TooltipImage').title = "Number Of Companies Owed :: Select 'Yes' if you owe money to 3 or more companies, e.g. banks (overdrafts), credit and store card companies, loan companies etc";
	myTips = new Tips($$('.LB_ToolTip'), {className: "LB_ToolTip", maxTitleChars: 1000});

	if( this == window )
	{
		sessionStartPing( "LOANSHTML10", "LOAN" );
	}
}

/* ==================================================================================
   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_Step2').className = 'LB_FormStep LB_FormStepVisible';

		// Make all the option elements hidden by default
		$('LB_PropertyInformation_Labels_Row').style.display = 'none';
		$('LB_PropertyInformation_Values_Row').style.display = 'none';
		$('LB_LoanType_Label_Row').style.display = 'none';
		$('LB_LoanType_Options_Row').style.display = 'none';
		$('LB_LoanType_Break_Row').style.display = 'none';
		$('LB_MortgageBalance_Label_Cell').style.display = 'none';
		$('LB_MortgageBalance_Cell').style.display = 'none';
		$('LB_VehiclePurchaseType_Label_Row').style.display = 'none';
		$('LB_VehiclePurchaseType_Row').style.display = 'none';

		$('LB_Debt_Label_Row_1').style.display = 'none';
		$('LB_Debt_Row_1').style.display = 'none';
		$('LB_Debt_Label_Row_2').style.display = 'none';
		$('LB_Debt_Row_2').style.display = 'none';

		// Update the status of this session in the database
		sessionStepPing( "STEP2", 0 );

		if( $('LB_EmploymentStatus').value == "0" )
		{
			// Unemployed loan
			lb_basicLoanType = "6";
			$('LB_Step2_Headline').innerHTML = "Unemployed loans";
			return;
		}
		
		if( $('LB_ResidentialStatus').value.indexOf('HOMEOWNER') >= 0 )
		{
			lb_basicLoanType = "1";
			$('LB_Step2_Headline').innerHTML = "Homeowner loans";

			// Make the property information entry visible (property value and mortgage balance)
			$('LB_PropertyInformation_Labels_Row').style.display = '';
			$('LB_PropertyInformation_Values_Row').style.display = '';

			// Decide whether the user sees the option of selecting secured vs unsecured loan type		
			if( getIntegerFromTextbox( $('LB_AmountToBorrow') ) >= 25000 || getIntegerFromTextbox( $('LB_LoanDuration') ) > 8 || $('LB_ResidentialStatus').value == "HOMEOWNEROUTRIGHT" )
			{
				// loan type = not visible
			}
			else
			{
				$('LB_LoanType_Label_Row').style.display = '';
				$('LB_LoanType_Options_Row').style.display = '';
				$('LB_LoanType_Break_Row').style.display = '';
			}
			
			if( $('LB_ResidentialStatus').value == "HOMEOWNERMORTGAGED" )
			{
				// mortgage balance = not visible
				$('LB_MortgageBalance_Label_Cell').style.display = 'block';
				$('LB_MortgageBalance_Cell').style.display = 'block';
			}
			
			return;
		}

		// Vehicle
		if( $('LB_LoanPurpose').value == "4" )
		{
			//TODO: Change MIN AGE on the date selector
			lb_basicLoanType = "3";
			$('LB_Step2_Headline').innerHTML = "Car loans";
			$('LB_VehiclePurchaseType_Label_Row').style.display = '';
			$('LB_VehiclePurchaseType_Row').style.display = '';
			return;
		}

		var amountToBorrow = getIntegerFromTextbox($('LB_AmountToBorrow'));
		var monthlyNetIncome = getIntegerFromTextbox($('LB_MonthlyIncome'));
		var yearlyNetIncome = monthlyNetIncome * 12;

		// Debt
		if( $('LB_LoanPurpose').value == "1" && (amountToBorrow > (yearlyNetIncome * 0.5)) )
		{
			lb_basicLoanType = "4";
			$('LB_Step2_Headline').innerHTML = "Debt consolidation loans";
			$('LB_Debt_Label_Row_1').style.display = '';
			$('LB_Debt_Row_1').style.display = '';
			$('LB_Debt_Label_Row_2').style.display = '';
			$('LB_Debt_Row_2').style.display = '';
			return;
		}

		if( $('LB_ResidentialStatus').value.indexOf("TENANT") >= 0 || $('LB_ResidentialStatus').value == "LIVINGWITHPARENTS" || $('LB_ResidentialStatus').value == "OTHER" )
		{
			// unsecured loan
			lb_basicLoanType = "2";
			$('LB_Step2_Headline').innerHTML = "Tenant loans";
			return;
		}
	}
}

// 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';
	
		if( (getIntegerFromTextbox($('LB_AmountToBorrow')) > (getIntegerFromTextbox($('LB_MonthlyIncome')) * 12 * 0.5)) && getRadioButtonListSelectedValue('LB_DebtsToMoreThanOneCompany') == "YES" )
		{
			$('LB_Step2b').className = 'LB_FormStep LB_FormStepVisible';

			// Update the status of this session in the database
			sessionStepPing( "STEP2B", 0 );
		}
		else
		{
			$('LB_Step3').className = 'LB_FormStep LB_FormStepVisible';
			getBrokerName(true);

			// Update the status of this session in the database
			sessionStepPing( "STEP3", 0 );
		}
	}
}

// Step 2b
function LB_Step2b_BackButton_Event_Click( event )
{
	var event = new Event(event);
	setCurrentControlFocus( event.target );

	lb_speakToDebtSpecialist = "0";

	$('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 );

	lb_speakToDebtSpecialist = "1";

	$('LB_Step2b').className = 'LB_FormStep LB_FormStepHidden';
	$('LB_Step3').className = 'LB_FormStep LB_FormStepVisible';

	getBrokerName(true);

	// Update the status of this session in the database
	sessionStepPing( "STEP3", 0 );
}

// 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_Step2').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...";
		
		setTimeout('revertSubmitButton()', 20000);
		submitLead();
	}
	
	return false;
}

function revertSubmitButton()
{
	$('LB_Step3_FinishButton').disabled = false;
	$('LB_Step3_FinishButton').value = "Submit";
	
	return;
}

/* ==================================================================================
   JSON AJAX 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 an FSA regulated broker called ', '');
			BrokerText = BrokerText.replace(' to help you with your enquiry. ', '');
			BrokerText = BrokerText.replace('Please click OK to confirm that you are happy for them to contact you by telephone.', '');
			BrokerText = "Based on your loan requirements we have selected a specialist adviser called <b>" + BrokerText.replace(/&amp;/g, "&") + "</b> to help you with your enquiry.<br /><br />Please click <b>SUBMIT</b> to confirm that you are happy for them to contact you by telephone/e-mail.";

			$('LB_Consent').innerHTML = BrokerText;
			$('LB_Consent').style.visibility = 'visible';
			$('LB_SessionId').value = BrokerDetails.Broker.Id;
			$('LB_Step3_FinishButton').disabled = false;
			$('LB_Step3_FinishButton').value = "Submit";


			// Update the status of this session in the database
			sessionStepPing( "STEP3BROKERFOUND", 0 );
		}
		else
		{
			$('LB_Consent').style.visibility = 'hidden';
			$('LB_Consent').innerHTML = 'ERROR ' + BrokerDetails.Error.ErrorMessage;
			$('LB_SessionId').value = '';

			$('LB_Step3_FinishButton').disabled = false;
			$('LB_Step3_FinishButton').value = "Submit";

			// Update the status of this session in the database
			sessionStepPing( "STEP3BROKERERROR", 0 );
		}
	}
}

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';
				createMarketingMessageElement(returnData.Lead.BrokerMarketingMessage);
			}
			
			break;
		}

		case '100':
		{
			setControlToErrorState( lb_postcodeValidator, "Enter valid UK postcode" );
			break;
		}
		
		default:
		{
			// Unknown error
			break;
		}
	}
}

/* ==================================================================================
   JSON AJAX CALLOUT FUNCTIONS
   ================================================================================== */

function buildBasicQueryString()
{
	var postcode = $('LB_Postcode').value.trim().toUpperCase();

	var queryString = '?';

	queryString += 'strMortgageBalance=' + (getIntegerFromTextbox( $('LB_MortgageBalance') ) > 0 ? getIntegerFromTextbox($('LB_MortgageBalance')) : "0");
	queryString += '&strPropertyValue=' + (getIntegerFromTextbox( $('LB_PropertyValue') ) > 0 ? getIntegerFromTextbox($('LB_PropertyValue')) : "0");
	queryString += '&strLoanType=' + lb_basicLoanType;
	queryString += '&strBadCredit=' + (getRadioButtonListSelectedValue('LB_AdverseCredit') == "1" ? "1" : "0");
	queryString += '&strLoanSize=' + getIntegerFromTextbox($('LB_AmountToBorrow'));
	queryString += '&strMonthlyIncome=' + getIntegerFromTextbox($('LB_MonthlyIncome'));
	queryString += '&strMortgage=' +  ($('LB_ResidentialStatus').value == "HOMEOWNERMORTGAGED" ? "1" : "0");
	queryString += '&strEmploymentStatus=' + $('LB_EmploymentStatus').value;
	queryString += '&strPostcode=' + escape(postcode);
	queryString += '&strPaymentTerm=' + $('LB_LoanDuration').value;
	queryString += '&strHomeOwner=' + ($('LB_ResidentialStatus').value.indexOf('HOMEOWNER') >= 0 ? "1" : "0");
	queryString += '&strOweMoney=' + ($('LB_DebtsToMoreThanOneCompany').value == "YES" ? "1" : "0");
	queryString += '&CarDealer=' + ($('LB_VehiclePurchaseType').value.length <= 0 ? "2" : $('LB_VehiclePurchaseType').value);
	queryString += '&DOBDay=' + $('LB_DateOfBirth_Day').value;
	queryString += '&DOBMonth=' + $('LB_DateOfBirth_Month').value;
	queryString += '&DOBYear=' + $('LB_DateOfBirth_Year').value;
	queryString += '&LoanSecurity=' + (getRadioButtonListSelectedValue('LB_LoanType') == "1" ? "1" : "2");
	queryString += '&strDebtToConsolidate=' + (getIntegerFromTextbox( $('LB_DebtAmount') ) > 0 ? getIntegerFromTextbox($('LB_DebtAmount')) : "0");
	queryString += '&strRentMortgagePayment=' + (getIntegerFromTextbox( $('LB_RentMortgagePayment') ) > 0 ? getIntegerFromTextbox($('LB_RentMortgagePayment')) : "0");
	queryString += '&strFamilyType=' + ($('LB_LivingArrangement').value.length <= 0 ? "1" : $('LB_LivingArrangement').value);
	queryString += '&strSpeakDebtSpecialist=' + lb_speakToDebtSpecialist;
	queryString += '&strPassword=' + 'xxxx';
	queryString += '&strIPAddress=fillip';
	queryString += '&strAffiliateID=' + (lb_testing ? lb_testAffiliateId : lb_affiliateId);
	queryString += '&ajax=y&filladdress=1';
	queryString += '&PageHref=' + escape(window.location.href);
	queryString += '&TrackingCode='
	if(typeof(lb_trackingCode) != 'undefined')
	    queryString += escape(lb_trackingCode.toUpperCase());
    queryString += '&Keywords='
	if(typeof(lb_keywords) != 'undefined')
	    queryString += escape(lb_keywords);

	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 += '&Title=&First_Name=' + $('LB_FirstName').value;
	queryString += '&Surname=' + $('LB_LastName').value;
	queryString += '&adr1=' + $('LB_FirstLineAddress').value;
	queryString += '&adr2=&town=&county=';
	queryString += '&Home_Phone=' + $('LB_PhoneNumber').value;
	queryString += '&Work_Phone=' + $('LB_AlternatePhoneNumber').value;
	queryString += '&Mobile_Phone=&Email=' + $('LB_EmailAddress').value;
	queryString += '&Other_Info=&FillIP=1&sessionid=' + $('LB_SessionId').value;

	if( lb_testing )
	{

		remoteJson({"uri": getPageProtocol() + lb_ajaxTestProcessLeadUrl + queryString});
	}
	else
	{
		remoteJson({"uri": getPageProtocol() + lb_ajaxProcessLeadUrl + queryString});
	}
	
	return true;
}


function createMarketingMessageElement(MarketingMessage)
{
    if(typeof(MarketingMessage) != 'undefined')
   {
        if(MarketingMessage != '')
        {
            MarketingMessage = MarketingMessage.replace(/&lt;/gi, '<').replace(/&gt;/gi, '>').replace(/&amp;/gi, '&').replace(/&quot;/gi, '"');
            $('LB_Step4').innerHTML = '<tr><td class="LB_Headline">Finished</td></tr><tr><td class="LB_FormStepContent"><br /><br />Thank you for your enquiry.<br /><br />Your adviser will be in touch with you shortly.<br /><br /><br /></td></tr></table><tr><td class="LB_Headline">Finished</td></tr><tr><td class="LB_FormStepContent"><br /><br />Thank you for your enquiry.<br /><br />Your adviser will be in touch with you shortly.<br /><br />' + MarketingMessage +'<br><br /></td></tr>';
        }   
   }      
}

/* ==================================================================================
   VALIDATORS - LOANS SPECIFIC
   ================================================================================== */



/* ==================================================================================
   UTILITY FUNCTIONS - LOANS SPECIFIC
   ================================================================================== */
