﻿/* PACKER here: http://dean.edwards.name/packer/*/

var lb_lastPostcodeChecked = null;

var lb_detailedMortgageTypes = { remortgage: {ltvPercent: 95.0, id: 1}, firstTimeBuyer: {ltvPercent: 95.0, id: 2}, selfCertifyRemortgage: {ltvPercent: 85.0, id: 3}, selfCertifyOther: {ltvPercent: 85.0, id: 4}, buyToLet: {ltvPercent: 85.0, id: 5}, purchase: {ltvPercent: 95.0, id: 6}, adverseRemortgage: {ltvPercent: 80.0, id: 7}, adverseOther: {ltvPercent: 80.0, id: 8} };

/* URLs for web services*/
var lb_ajaxBrokerSearchUrl = 'apps.leadbay.co.uk/webservice/broker_search_equityrelease_webservice.aspx';
var lb_ajaxProcessLeadUrl = 'apps.leadbay.co.uk/webservice/process_lead_equityrelease_webservice.aspx';

var lb_ajaxTestBrokerSearchUrl = 'testapps.leadbay.co.uk/webservice/broker_search_equityrelease_webservice.aspx';
var lb_ajaxTestProcessLeadUrl = 'testapps.leadbay.co.uk/webservice/process_lead_equityrelease_webservice.aspx';

function clearCalculations()
{
    $('LB_AmountAvailableForRelease').innerHTML = "&nbsp;&nbsp;&pound;";
    $('LB_CashAvailable').innerHTML = "&nbsp;&nbsp;&pound;";
	$('LB_AmountAvailableForReleaseMinusOwings').innerHTML = "-&nbsp;&pound;";

	$('LB_ApproxAmountToRelease').removeClass('LB_DisplayNone'); 
	$('LB_CashAvailableSection').removeClass('LB_DisplayNone'); 
	$('LB_BelowMinimumAgeMessage').addClass('LB_DisplayNone');
    $('LB_InsufficientEquity').addClass('LB_DisplayNone');
    $('LB_InsufficientEquityNoRemortgage').addClass('LB_DisplayNone');
    
	$('LB_Step1_NextButton').disabled = true;
	$('LB_Step1_CalculateButton').disabled = false;
	$('LB_Step1_NextButton').addClass('LB_Disabled_Button');
	$('LB_Step1_CalculateButton').removeClass('LB_Disabled_Button');
}

clearCalculations();

/* ==================================================================================
   EQUITY FORM VALIDATION SETUP
   ================================================================================== */

var ltvTable = [];
ltvTable[55] = 22.0;
ltvTable[56] = 23.0;
ltvTable[57] = 24.0;
ltvTable[58] = 25.0;
ltvTable[59] = 26.0;
ltvTable[60] = 27.0;
ltvTable[61] = 28.0;
ltvTable[62] = 29.0;
ltvTable[63] = 30.0;
ltvTable[64] = 31.0;
ltvTable[65] = 39.0;
ltvTable[66] = 40.5;
ltvTable[67] = 42.0;
ltvTable[68] = 43.0;
ltvTable[69] = 44.5;
ltvTable[70] = 46.5;
ltvTable[71] = 47.5;
ltvTable[72] = 49.5;
ltvTable[73] = 51.0;
ltvTable[74] = 52.5;
ltvTable[75] = 54.0;
ltvTable[76] = 55.0;
ltvTable[77] = 56.5;
ltvTable[78] = 58.0;
ltvTable[79] = 59.0;
ltvTable[80] = 60.5;
ltvTable[81] = 62.0;
ltvTable[82] = 62.5;
ltvTable[83] = 64.0;
ltvTable[84] = 65.0;
ltvTable[85] = 66.0;

var propertyValueGreaterThanValidationData = {minValue: 74999};
var propertyValueLessThanValidationData = {maxValue: 5000000};
var amountOwingLessThanValidationData = {maxValue: 5000000};
var amountRequiredLessThanValidationData = {maxValue: function(){ return parseFloat( $('LB_AmountAvailableForRelease').innerHTML.replace(/[^0-9.]*/g, ""), 10 ) + 1; } };
var amountAvailableForRelease = null;

/* Step 1*/
addValidation( [ $('LB_YoungestHomeownerAge') ], [{validator: selectHasValueValidator, validationData: null, errorMessages: ["Make a selection"]}], $('LB_YoungestHomeownerAge_Label'), $('LB_YoungestHomeownerAge_ErrorAdvice'), false, false, true, [$('LB_Step1_NextButton'), $('LB_Step1_CalculateButton')], false, 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: propertyValueGreaterThanValidationData, errorMessages: ["Must be £75,000 or over"]}, {validator: LessThanValueValidator, validationData: propertyValueLessThanValidationData, errorMessages: ["Must be under £5,000,000"]} ], $('LB_PropertyValue_Label'), $('LB_PropertyValue_ErrorAdvice'), true, true, true, [$('LB_Step1_NextButton'), $('LB_Step1_CalculateButton')], false, true, false, null, null, null, [addCommasToNumberTextbox] );
addValidation( [ $('LB_AmountOwing') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter value, e.g. £5,000"]}, {validator: ValidIntegerValidator, validationData: null, errorMessages: ["Enter valid value"]}, {validator: LessThanValueValidator, validationData: amountOwingLessThanValidationData, errorMessages: ["Must be under £5,000,000"]} ], $('LB_AmountOwing_Label'), $('LB_AmountOwing_ErrorAdvice'), true, true, true, [$('LB_Step1_NextButton'), $('LB_Step1_CalculateButton')], false, true, false, null, null, null, [addCommasToNumberTextbox] );
addValidation( [ $('LB_AmountRequiredForRelease') ], [{validator: textboxHasValueValidator, validationData: null, errorMessages: ["Enter value, e.g. £5,000"]}, {validator: ValidIntegerValidator, validationData: null, errorMessages: ["Enter valid value"]}/*, {validator: LessThanValueValidator, validationData: amountRequiredLessThanValidationData, errorMessages: ["Must be no more than the approximate amount available via equity release."]}*/ ], $('LB_AmountRequiredForRelease_Label'), $('LB_AmountRequiredForRelease_ErrorAdvice'), true, true, true, $('LB_Step1_NextButton'), false, true, false, null, null, null, [addCommasToNumberTextbox] );

/* Step 2*/
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_Step2_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_Step2_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_Step2_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_Step2_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_Step2_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_Step2_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_Step2_FinishButton'), false, false, false, null, null, null );

/* ==================================================================================
   MORTGAGE FORM EVENT SETUP
   ================================================================================== */

addEvent( $('LB_YoungestHomeownerAge'), 'onblur', function(){ clearCalculations(); } );
addEvent( $('LB_YoungestHomeownerAge'), 'onchange', function(){ clearCalculations(); } );
addEvent( $('LB_PropertyValue'), 'onkeydown', function(){ clearCalculations(); } );
addEvent( $('LB_AmountOwing'), 'onkeydown', function(){ clearCalculations(); } );

/* 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_FinishButton'), 'onclick', LB_Step2_FinishButton_Event_Click );
addEvent( $('LB_Step1_CalculateButton'), 'onclick', LB_Step1_CalculateButton_Click );

/* Monitor Postcode field for changes*/
addEvent( $('LB_Postcode'), 'onkeyup', getBrokerName );
addEvent( $('LB_Postcode'), 'onblur', getBrokerName );
addEvent( $('LB_Postcode'), 'onchange', getBrokerName );

/* ==================================================================================
   EQUITY  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};
}

/* Calculate */
function LB_Step1_CalculateButton_Click( event )
{
    var event = new Event(event);

    setCurrentControlFocus( event.target );

    if( validateMultiple( event ) )
    { 
        if(validateMinimumAgeForEquity())
            calculateAmountAvailable();   
    }  
   
}

/* Step 1*/
function LB_Step1_NextButton_Event_Click( event )
{
	var event = new Event(event);
	
	setCurrentControlFocus( event.target );

	if( validateMultiple( event ) )
	{	    
        if( validateMinimumAgeForEquity() )
        {
			if( !calculateAmountAvailable() )
			{
				return;
			}
		}

		/* Change the visible wizard step	*/
		$('LB_Step1').className = 'LB_FormStep LB_FormStepHidden';
		$('LB_Step2').className = 'LB_FormStep LB_FormStepVisible';
		
		/* 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 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_FinishButton_Event_Click( event )
{
	var event = new Event(event);
	setCurrentControlFocus( event.target );

	if( validateMultiple( event ) )
	{
		$('LB_Step2_FinishButton').disabled = true;
		$('LB_Step2_FinishButton').value = "Submitting details...";

		setTimeout('revertSubmitButton()', 20000);
		
		submitLead();
	}
	
	return false;
}

function revertSubmitButton()
{
	$('LB_Step2_FinishButton').disabled = false;
	$('LB_Step2_FinishButton').value = "Submit";
	
/*	$('LB_SubmitIndicator').style.visibility = "hidden";
	$('LB_AlphaLayer').style.visibility = "hidden";*/

	return;
}

/* ==================================================================================
   JSON AJAX EQUITY CALLBACK FUNCTIONS
   ================================================================================== */

function BrokerSearchCallback(BrokerDetails)
{
	if( BrokerDetails )
	{
		if( BrokerDetails.Error.ErrorNumber == '0' )
		{
			var BrokerText = BrokerDetails.Broker.DisplayText;
			
			BrokerText = BrokerText.replace('Based on your requirements we have selected the FSA regulated advisor ', '');
			BrokerText = BrokerText.replace(' to help you with your enquiry. Click SUBMIT to confirm that you are happy to be contacted by telephone or email and you agree to our privacy policy.', '');
			/*$('LB_BrokerName').innerHTML = BrokerText.replace(/&amp;/g, "&");*/
			$('LB_Consent').innerHTML = 'Based on your requirements we have selected the FSA regulated advisor <b><span id="LB_BrokerName" style="white-space: nowrap">' + BrokerText.replace(/&amp;/g, "&") + '</span></b> to help you with your enquiry.<br /><br />';
			$('LB_Consent').innerHTML += 'Click SUBMIT to confirm that you are happy to be contacted by telephone or email and you agree to our ' + getPrivacyPolicyText();
			$('LB_Consent').style.visibility = 'visible';
			$('LB_SessionId').value = BrokerDetails.Broker.Id;
			$('LB_Step2_FinishButton').disabled = false;
			$('LB_Step2_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_Step2').className = 'LB_FormStep LB_FormStepHidden';
				$('LB_Step3').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 EQUITY CALLOUT FUNCTIONS
   ================================================================================== */

function buildBasicQueryString()
{
	var postcode = $('LB_Postcode').value.trim().toUpperCase();

	var queryString = '?';
	
    queryString += '&Age=' + $('LB_YoungestHomeownerAge').value;
    if(validateMinimumAgeForEquity() == true)
    {
        queryString += '&Mortgage_Size=' + amountAvailableForRelease;
    }
    else
    {
        queryString += '&Mortgage_Size=' + $('LB_PropertyValue').value;
    }        
	
	queryString += '&Property_Value=' + $('LB_PropertyValue').value;
	queryString += '&Postcode=' + escape(postcode);
	queryString += '&Password=' + 'xxxx';
	queryString += '&IPAddress=fillip';
	queryString += '&AffiliateID=' + (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);
	queryString += '&FormVersion=' + getFormVersion();
    if (typeof(lb_scriptTagForm)!='undefined' && lb_scriptTagForm== true)
	    queryString += '&ScriptTag=y'
	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_Step2_FinishButton').disabled = false;
		$('LB_Step2_FinishButton').value = "Submit";
		return;
	}

	$('LB_Step2_FinishButton').disabled = true;
	$('LB_Step2_FinishButton').value = "Searching...";

	var queryString = buildBasicQueryString();

	if( lb_testing )
	{
		//remoteJson({"uri": getPageProtocol() + lb_ajaxTestBrokerSearchUrl + queryString});
		remoteJson({"uri": "http://" + lb_ajaxTestBrokerSearchUrl + queryString});
	}
	else
	{
		//remoteJson({"uri": getPageProtocol() + lb_ajaxBrokerSearchUrl + queryString});
		remoteJson({"uri": "http://" + 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 += '&BestTimeToCall=' + $('LB_BestTimeToCall').value;
	queryString += '&Other_Info=&sessionid=' + $('LB_SessionId').value;
	queryString += '&CurrentDebt=' + $('LB_AmountOwing').value;

	if( lb_testing )
	{
		//remoteJson({"uri": getPageProtocol() + lb_ajaxTestProcessLeadUrl + queryString});
		remoteJson({"uri": "http://" + lb_ajaxTestProcessLeadUrl + queryString});
	}
	else
	{
		//remoteJson({"uri": getPageProtocol() + lb_ajaxProcessLeadUrl + queryString});
		remoteJson({"uri": "http://" + lb_ajaxProcessLeadUrl + queryString});
	}
	
	return true;
}


/* ==================================================================================
   EQUITY FORM PRE-FILL FUNCTIONS
   ================================================================================== */

/* uses lb_formPrefillQueryStringParameters to get names for qs parameter values like mortgageSize, mortgageType, 
 creates an object with appropriate property names,
 then passes it to generic prefillForm function*/
function prefillFormFromQueryString()
{
    var prefillObject = {};
    operateFunctionOnAllObjectMembers(lb_formPrefillQueryStringParameters, function(obj, pty){obj[pty] = obj[pty].toLowerCase();}, 'string');
    
	if( lb_queryObject[lb_formPrefillQueryStringParameters.youngestHomeownerAge] )
	    prefillObject.youngestHomeownerAge = lb_queryObject[lb_formPrefillQueryStringParameters.youngestHomeownerAge];
	
	if( lb_queryObject[lb_formPrefillQueryStringParameters.propertyValue] )
	    prefillObject.propertyValue = lb_queryObject[lb_formPrefillQueryStringParameters.propertyValue];
	
	if( lb_queryObject[lb_formPrefillQueryStringParameters.amountOwing] )
	    prefillObject.amountOwing = lb_queryObject[lb_formPrefillQueryStringParameters.amountOwing];
	
	prefillForm(prefillObject)
}

function prefillForm(prefillObject)
{
	
	if( prefillObject.youngestHomeownerAge )
		$('LB_YoungestHomeownerAge').value = prefillObject.youngestHomeownerAge;
	
	if( prefillObject.propertyValue )
		$('LB_PropertyValue').value = prefillObject.propertyValue;
	
	if( prefillObject.amountOwing)
	    $('LB_AmountOwing').value = prefillObject.amountOwing;
	
	calculateAmountAvailable();
	    
   $('LB_Form').style.display = '';
        			
}

function createMarketingMessageElement(MarketingMessage)
{
	if(typeof(MarketingMessage) != 'undefined')
	{
        if(MarketingMessage != '')
        {
            MarketingMessage = MarketingMessage.replace(/&lt;/gi, '<').replace(/&gt;/gi, '>').replace(/&amp;/gi, '&').replace(/&quot;/gi, '"');
            $('LB_MarketingMessage').innerHTML = MarketingMessage + "<br /><br />"; 
        }   
   }      
}

/* ==================================================================================
   UTILITY FUNCTIONS - EQUITY SPECIFIC
   ================================================================================== */

var lb_homeownerAge = null;

function validateMinimumAgeForEquity()
{
    var hasEnteredAge = (selectHasValueValidator(null, [ $('LB_YoungestHomeownerAge') ], null, null).errorCode == -1);
    if(!hasEnteredAge) return false;
    
    lb_homeownerAge = $('LB_YoungestHomeownerAge').value;
    
    if( lb_homeownerAge < 55)
    {
        //can't get equity
        $('LB_ApproxAmountToRelease').addClass('LB_DisplayNone');
        $('LB_CashAvailableSection').addClass('LB_DisplayNone');
        //$('LB_Step1_CalculateButton').addClass('LB_DisplayNone');
        $('LB_BelowMinimumAgeMessage').removeClass('LB_DisplayNone');
      	$('LB_InsufficientEquity').addClass('LB_DisplayNone');
		$('LB_InsufficientEquityNoRemortgage').addClass('LB_DisplayNone');
        
        if( lb_mortgageFormFallbackHref.length > 0 )
        {
			$('LB_RemortgageLink').href = lb_mortgageFormFallbackHref;
        }
        
		$('LB_Step1_NextButton').addClass('LB_Disabled_Button');
		$('LB_Step1_NextButton').disabled = true;
        return false;
    }
   
	// Age is above minimum, so make sure that Amount To Release section is visible
	$('LB_ApproxAmountToRelease').removeClass('LB_DisplayNone'); 
	$('LB_CashAvailableSection').removeClass('LB_DisplayNone'); 
	//$('LB_Step1_CalculateButton').removeClass('LB_DisplayNone');
	$('LB_BelowMinimumAgeMessage').addClass('LB_DisplayNone'); 
	$('LB_InsufficientEquity').addClass('LB_DisplayNone');
	$('LB_InsufficientEquityNoRemortgage').addClass('LB_DisplayNone');
	$('LB_Step1_NextButton').removeClass('LB_Disabled_Button');
	$('LB_Step1_NextButton').disabled = false;
	return true; 
}

function calculateAmountAvailable()
{
    var amountOwing = getFloatFromTextbox($('LB_AmountOwing'));
    var propertyValue = getFloatFromTextbox($('LB_PropertyValue'));
	   
    // get max ltv for age of youngest homeowner  
    var ltvPercentForAge = ltvTable[$('LB_YoungestHomeownerAge').value];
        
   // Calculate amount available for equity release based upon max ltv for age of youngest homeowner
    amountAvailableForRelease = (propertyValue * (ltvPercentForAge / 100 )).toFixed(0);
    $('LB_AmountAvailableForRelease').innerHTML = '&nbsp;&nbsp;&pound;' + addCommas( amountAvailableForRelease );
    $('LB_CashAvailable').innerHTML = '&nbsp;&nbsp;&pound;' + addCommas( amountAvailableForRelease - amountOwing );
    
    if(amountOwing > 0)
        {   $('LB_AmountAvailableForReleaseMinusOwings').innerHTML = '- &pound;' + addCommas( amountOwing );    }  
    else
        {   $('LB_AmountAvailableForReleaseMinusOwings').innerHTML = '';    }  

	// Not enough equity to release? Let them know...
	if( amountAvailableForRelease - amountOwing < 1 )
	{
        $('LB_ApproxAmountToRelease').addClass('LB_DisplayNone');
        $('LB_CashAvailableSection').addClass('LB_DisplayNone');
        //$('LB_Step1_CalculateButton').addClass('LB_DisplayNone');
		$('LB_BelowMinimumAgeMessage').addClass('LB_DisplayNone');
        $('LB_InsufficientEquity').addClass('LB_DisplayNone');
        $('LB_InsufficientEquityNoRemortgage').addClass('LB_DisplayNone');

		if( lb_homeownerAge > 65 )
		{
			$('LB_InsufficientEquityNoRemortgage').removeClass('LB_DisplayNone');
			$('LB_Step1_NextButton').addClass('LB_Disabled_Button');
			$('LB_Step1_NextButton').disabled = true;
			return false;
		}
		else
		{
			$('LB_RemortgageLink').href = lb_mortgageFormFallbackHref;
			$('LB_InsufficientEquity').removeClass('LB_DisplayNone');
			$('LB_Step1_NextButton').addClass('LB_Disabled_Button');
			$('LB_Step1_NextButton').disabled = true;
			return false;
		}
	}

	$('LB_Step1_NextButton').removeClass('LB_Disabled_Button');
	$('LB_Step1_NextButton').disabled = false;
	$('LB_Step1_CalculateButton').addClass('LB_Disabled_Button');
	$('LB_Step1_CalculateButton').disabled = true;
	return true;
}