var xmlDataFile = xmlDataFileRef;

//var chelseaMinLoan = 25001;
//var chelseaMaxLoan = 1000000;
var chelseaMaxLTV = 90;
var chelseaMaxTerm = 35;
var chelseaSVR = "5.79%";

var ltvTier1 = 60;
var ltvTier2 = 70;
var ltvTier3 = 75;
var ltvTier4 = 80;
var ltvTier5 = 85;
var ltvTier6 = 90;
var ltvTier7 = 100;

var loadingAnimationTimeoutLength = 2000;

// FORM
var customerType;
var buyerType;
var mortgageType;
var propertyValue;
var depositValue;
var mortgageTerm;
var customerLTV;
var customerLoan = 0;

var displayAllOnLoad = false;

var firstTime = true;

var hash = '';
// if any hash exists when the page is loaded, remove it
$(document).ready(function() {
						   
	$('#formContainer').show();					   
						   
	/*if (location.hash == '#changing-deal' || location.hash == "#additional-lending") {
		// do nothing
	}	
	else if (location.hash != '' ) {		
		window.location.hash = '';
	}*/
	
	if (location.hash == '#full-product-range') {
		displayAllOnLoad = true;
	}
	
	xmlLoader();
	
});

var productPageURL;
$(function(){

	$('.modifyFormButton').live('click', function() {
	  
		$('#formContainer').scrollTo();
		return false;
	  
	});
	
	$('.productSelectionLink').live('click', function() {
	  	productPageURL = $(this).attr('href');
		resetView();
		$(".leavingPageNotification").show();
		$(".leavingPageNotificationContainer").fadeIn(500);	
		Cufon.replace('.leavingPageNotification h2');		
		$('.moveToProductPageLink').attr('href', productPageURL);
		$('.leavingPageNotificationContainer').bgiframe();
		return false;
	});
	
	$(".leavingPageNotificationContainer, .stayOnMortgageFinderLink").click(function() {									 
		$(".leavingPageNotificationContainer").fadeOut(500);
		$(".leavingPageNotification").hide();
		return false;
	});
	
	
	$('.moveToProductPageLink').live('click', function() {
	  	productPageURL = $(this).attr('href');
		productTrack = productPageURL.substring(productPageURL.lastIndexOf('/') + 1);
		
		mortgageFinderDetailsLinkTracker(productPageURL, productTrack);		
	});
	
	
});

var fullListViewed = 0;

function retrieveQuerystringValue(productAvailability) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == productAvailability) {
			return pair[1];
		}
	}
} 

var pageViewHashValue;
$(function(){	 
		   
	// Get the change in # value and apply the tabs-selected class to the corresponding tab
	$(window).bind( 'hashchange', function(){
								   
		pageViewHashValue = location.hash;
		
		//resetView();
		
		// if hash empty display nothing
		if (pageViewHashValue == '' || pageViewHashValue == '#') {			
			// VIEW 1
			$('#resultsView').hide();
			// VIEW 2
			$('#fullRangeView').hide();
			// VIEW 3
			$('#typeRangeView').hide();
			// VIEW 4
			$('#compareView').hide();
			// INTRO COPY			
			$('#introCopyContainer').show();
			// SEARCH FORM
			$('#formContainer').show();
			// PROMO
			$('#promoContainer').show();
			// EXISTING BORROWER CHANGING DEAL
			$('#changingDealView').hide();
			// EXISTING BORROWER ADDITIONAL LENDING
			$('#additionalLendingView').hide();	
			// OFFSET TOOLS
			$('#offsetToolsContainerFinder').hide();
		}
			
		// if pageViewHashValue = #search-results then display Product Search Results
		else if (pageViewHashValue == '#search-results') {
			// RESET ALL CHECKBOXES TO BE UNCHECKED
			$('#fullRangeView input:checkbox').removeAttr('checked');
			$('#typeRangeView input:checkbox').removeAttr('checked');
			// VIEW 1
			$('#resultsView').show();	
			// VIEW 2
			$('#fullRangeView').hide();
			// VIEW 3
			$('#typeRangeView').hide();
			// VIEW 4
			$('#compareView').hide();
			// INTRO COPY			
			$('#introCopyContainer').hide();
			// SEARCH FORM
			$('#formContainer').show();
			// PROMO
			$('#promoContainer').hide();
			// EXISTING BORROWER CHANGING DEAL
			$('#changingDealView').hide();
			// EXISTING BORROWER ADDITIONAL LENDING
			$('#additionalLendingView').hide();

			
			$('#resultsView').scrollTo();
			
			fullListViewed = 0;
			
		}
		
		else if (pageViewHashValue == '#offset-range' || pageViewHashValue == '#fixed-range' || pageViewHashValue == '#tracker-range' || pageViewHashValue == '#tracker-to-fixed-range') {
			// RESET ALL CHECKBOXES TO BE UNCHECKED
			$('#resultsView input:checkbox').removeAttr('checked');
			$('#fullRangeView input:checkbox').removeAttr('checked');
			// VIEW 1
			$('#resultsView').hide();
			// VIEW 2
			$('#fullRangeView').hide();
			// VIEW 3
			$('#typeRangeView').show();
			// VIEW 4
			$('#compareView').hide();
			// INTRO COPY			
			$('#introCopyContainer').hide();
			// SEARCH FORM
			$('#formContainer').show();
			// PROMO
			$('#promoContainer').hide();
			// EXISTING BORROWER CHANGING DEAL
			$('#changingDealView').hide();
			// EXISTING BORROWER ADDITIONAL LENDING
			$('#additionalLendingView').hide();
			// OFFSET TOOLS
			$('#offsetToolsContainerFinder').hide();
			// CHECK TO SEE IF THE USER HAS MOVED FROM THE FULL LIST TO THE COMPARISON AND BACK, TO AVOID CHECKBOX RESET			
			//alert("fullListViewed: " + fullListViewed);
			if (fullListViewed == 0) {
				//alert("Option 1");
				$('#typeRangeData').empty();
				setTimeout('$(\'.searchInProgressAnimationContainer\').show();',50);
				setTimeout('searchInProgressAnimation("#typeRangeData")',loadingAnimationTimeoutLength);
				setTimeout('showFullRange()',1500);
			}
			else {
				//alert("Option 2");
				fullListViewed = 0;
			}
			
			$('#formContainer').scrollTo();
		}
		
		else if (pageViewHashValue == '#full-product-range') {			
			// RESET ALL CHECKBOXES TO BE UNCHECKED
			$('#resultsView input:checkbox').removeAttr('checked');
			$('#typeRangeView input:checkbox').removeAttr('checked');
			// VIEW 1
			$('#resultsView').hide();
			// VIEW 2
			$('#fullRangeView').show();
			// VIEW 3
			$('#typeRangeView').hide();
			// VIEW 4
			$('#compareView').hide();
			// INTRO COPY			
			$('#introCopyContainer').hide();
			// SEARCH FORM
			$('#formContainer').show();
			// PROMO
			$('#promoContainer').hide();
			// EXISTING BORROWER CHANGING DEAL
			$('#changingDealView').hide();
			// EXISTING BORROWER ADDITIONAL LENDING
			$('#additionalLendingView').hide();
			// OFFSET TOOLS
			$('#offsetToolsContainerFinder').hide();
			// CHECK TO SEE IF THE USER HAS MOVED FROM THE FULL LIST TO THE COMPARISON AND BACK, TO AVOID CHECKBOX RESET			
			//alert("fullListViewed: " + fullListViewed);
			if (fullListViewed == 0) {
				//alert("Option 1");
				$('#fullRangeData').empty();
				setTimeout('$(\'.searchInProgressAnimationContainer\').show();',50);
				setTimeout('searchInProgressAnimation("#fullRangeData")',loadingAnimationTimeoutLength);
				setTimeout('showFullRange()',1500);				
			}
			else {
				//alert("Option 2");
				fullListViewed = 0;
			}
			
			$('#formContainer').scrollTo();
		}
		
		// if pageViewHashValue = #product-comparison then display Product Comparison selections
		else if (pageViewHashValue == '#product-comparison') {
			// VIEW 1
			$('#resultsView').hide();
			// VIEW 2
			$('#fullRangeView').hide();
			// VIEW 3
			$('#typeRangeView').hide();
			// VIEW 4
			$('#compareView').show();
			// INTRO COPY			
			$('#introCopyContainer').hide();
			// SEARCH FORM
			$('#formContainer').hide();			
			// PROMO
			$('#promoContainer').hide();
			// EXISTING BORROWER CHANGING DEAL
			$('#changingDealView').hide();
			// EXISTING BORROWER ADDITIONAL LENDING
			$('#additionalLendingView').hide();
			// OFFSET TOOLS
			$('#offsetToolsContainerFinder').hide();
			// THE USER HAS MOVED FROM THE FULL LIST TO THE COMPARISON, TO AVOID CHECKBOX RESET	FLAG THIS INCASE THEY MOVE BACK	
			//alert("fullListViewed: " + fullListViewed);
			if (fullListViewed == 0) {
				//alert("Option 3");
				fullListViewed = 1;
			}
			else {
				//alert("Option 4");
				//fullListViewed++;
			}
			
			$('#compareView').scrollTo();
		}
		
		// if pageViewHashValue = #changing-deal then display Changing deal information
		else if (pageViewHashValue == '#changing-deal') {					
			// VIEW 1
			$('#resultsView').hide();
			// VIEW 2
			$('#fullRangeView').hide();
			// VIEW 3
			$('#typeRangeView').hide();
			// VIEW 4
			$('#compareView').hide();
			// INTRO COPY			
			$('#introCopyContainer').hide();
			// SEARCH FORM
			$('#formContainer').hide();
			// PROMO
			$('#promoContainer').hide();
			// EXISTING BORROWER CHANGING DEAL
			$('#changingDealView').show();
			// EXISTING BORROWER ADDITIONAL LENDING
			$('#additionalLendingView').hide();
			// OFFSET TOOLS
			$('#offsetToolsContainerFinder').hide();
		}
		
		// if pageViewHashValue = ##additional-lending then display Additional Lending information
		else if (pageViewHashValue == '#additional-lending') {					
			// VIEW 1
			$('#resultsView').hide();
			// VIEW 2
			$('#fullRangeView').hide();
			// VIEW 3
			$('#typeRangeView').hide();
			// VIEW 4
			$('#compareView').hide();
			// INTRO COPY			
			$('#introCopyContainer').hide();
			// SEARCH FORM
			$('#formContainer').hide();
			// PROMO
			$('#promoContainer').hide();
			// EXISTING BORROWER CHANGING DEAL
			$('#changingDealView').hide();
			// EXISTING BORROWER ADDITIONAL LENDING
			$('#additionalLendingView').show();
			// OFFSET TOOLS
			$('#offsetToolsContainerFinder').hide();
		}
		
		if (pageViewHashValue == '#offset-range') {
			$('#offsetToolsContainerFinder').show();
		}
		
		// run tracking update to send hit to omniture
	    mortgageFinderStateTracker(pageViewHashValue);

	})
	
	// when the hash changes or the page is loaded, fire the update
	$(window).trigger( 'hashchange' );
	
});


// MOVE USER BACK TO TOP OF SCREEN
function resetView() {
	
	window.scrollTo(0,0);
		
}


// LOAD XML
var mortgageProducts;
function xmlLoader() {
	
	// Read the data	
	downloadUrl(xmlDataFile, function(doc) {
													   
		xmlDoc = xmlParse(doc);
				
		mortgageProducts = xmlDoc.documentElement.getElementsByTagName("product");
		
	});
	
};

// customerType dropdown list
var customerTypeDropdown = '<option value="newBorrower">New Borrower</option>' +
							'<option value="existingBorrower">Existing Borrower</option>';	
// buyerType dropdown list
var newCustomerBuyerType = '<option value="select">Please select</option>' +
							'<option value="remortgaging">Remortgaging</option>' +
							'<option value="movingHome">Moving Home</option>' +
							'<option value="firstTimeBuyer">First Time Buyer</option>';	
var existingCustomerBuyerType = '<option value="select">Please select</option>' +
							'<option value="changingDeal">Changing deal</option>' +
							'<option value="movingHome">Moving Home</option>' +
							'<option value="additionalLending">Additional Lending</option>';
var newMortgageType = 		'<option value="allMortgageTypes">All mortgage types</option>' +
							'<option value="offset">Offset</option>' +
							'<option value="fixed">Fixed Rate</option>' +
							'<option value="tracker">Tracker</option>' +
							'<option value="mixed">Tracker to Fixed</option>';	

function checkNewOrExisting() {
	
	customerType = $("#customerTypeSelector").val();
	
	$('.formColumnMiddle').show();
	$('#mortgageTypeContainer').show();
	
    switch (customerType) {
		case "newBorrower":
			$('#buyerTypeSelector').empty();
			$(newCustomerBuyerType).appendTo('#buyerTypeSelector');
			break;
		case "existingBorrower":
			$('#buyerTypeSelector').empty();			
			$(existingCustomerBuyerType).appendTo('#buyerTypeSelector');
			break;
	}
	
}

function checkBuyerType() {
	
	customerType = $("#customerTypeSelector").val();
	buyerType = $("#buyerTypeSelector").val();	
	
	if (customerType == "existingBorrower") {
		$('#depositLabelContainer').addClass('twoLineLabel');
		$('#depositLabel').text('Outstanding amount:');
		$('#depositValue').val('');
	}
	else if (customerType == "newBorrower" && buyerType == "remortgaging") {
		$('#depositLabelContainer').addClass('twoLineLabel');
		$('#depositLabel').text('Outstanding amount:');
		$('#depositValue').val('');
	}	
	else {
		if ($('#depositLabelContainer').hasClass('twoLineLabel')) {
			$('#depositLabelContainer').removeClass('twoLineLabel');
			$('#depositLabel').text('Deposit:');
			$('#depositValue').val('');
		}
	}
	
	if (buyerType == "changingDeal" || buyerType == "additionalLending") {
		$('.formColumnMiddle').hide();
		$('#mortgageTypeContainer').hide();
	}
	else {
		$('.formColumnMiddle').show();
		$('#mortgageTypeContainer').show();
	}
	
}




function validateNumber(currentFieldID) {	
	
	// get the id of the input being used	
	inputID = currentFieldID;
	
	enteredValue = $("#" + inputID +"").val();
	enteredValue = enteredValue.replace(/\,/g,'');
	enteredValueWithCommas = addCommas(enteredValue);
	$("#" + inputID +"").val(enteredValueWithCommas);
	
}

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		// $cmignore
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
		// $/cmignore
	}
	return x1 + x2;
}



function mortgageSearchFormValidation() {
	
	
	
	$('#errorMessageList').empty();
	
	///////////////////////////////////////////////////////////////////////////////////////////
	// ON FORM SUBMISSION, GET VALUES OF FORM ELEMENTS
	///////////////////////////////////////////////////////////////////////////////////////////
	customerType = $("#customerTypeSelector").val();	
	buyerType = $("#buyerTypeSelector").val();
	mortgageType = $("#mortgageTypeSelector").val();
	propertyValue = $("#propertyValue").val();
	// remove commas from value
	propertyValue = propertyValue.replace(/\,/g,'');
	depositValue = $("#depositValue").val();
	// remove commas from value
	depositValue = depositValue.replace(/\,/g,'');
	mortgageTerm = $("#mortgageTerm").val();
	// remove commas from value
	mortgageTerm = mortgageTerm.replace(/\,/g,'');	
	
	///////////////////////////////////////////////////////////////////////////////////////////
	// ERROR HANDLING. IF ANY OF THE FOLLOWING CHECKS FAIL, THE ERRORCOUNT WILL BE INCREMENTED
	///////////////////////////////////////////////////////////////////////////////////////////
	var errorList = '';
	var errorCount = 0;
	// CUSTOMER IS AN EXISTING BORROWER, HAS SELECTED MOVING DEAL OR ADDITIONAL LENDING
	var noSearchRequired = 0;
	
	
	// NO ERRORS FOUND
	// CUSTOMER HAS SELECTED EXISTING BORROWER - MOVING DEAL OR EXISTING BORROWER - ADDITIONAL LENDING 	
	if (buyerType == "changingDeal") {
		resetView();
		noSearchRequired++;
		$('#formValidationErrorContainer').hide();
		$('div').removeClass('formError');
		window.location.hash = "#changing-deal";
	}
	else if (buyerType == "additionalLending") {
		resetView();
		noSearchRequired++;
		$('#formValidationErrorContainer').hide();
		$('div').removeClass('formError');
		window.location.hash = "#additional-lending";
	}	
	else {
		
		///////////////////////////////////////////////////////////////////////////////////////////
		// BUYER TYPE
		///////////////////////////////////////////////////////////////////////////////////////////
		// CHECK IF SELECTION MADE
		if (buyerType == "select") {
			$('#buyerTypeValidate').addClass('formError');
			errorList = errorList + '<li>Select what type of buyer you are</li>';
			errorCount++;
		}
		// SELECTION MADE OK. REMOVE FIELD ERROR IF PRESENT
		else if (buyerType != "select" && $('#buyerTypeValidate').hasClass('formError')) {
			$('#buyerTypeValidate').removeClass('formError');	
		}
		
		///////////////////////////////////////////////////////////////////////////////////////////
		// PROPERTY VALUE
		///////////////////////////////////////////////////////////////////////////////////////////
		// CHECK IF A VALUE HAS BEEN ENTERED
		if (propertyValue == "") {
			$('#propertyValueValidate').addClass('formError');
			errorList = errorList + '<li>Enter a Property Value</li>';
			errorCount++;
		}
		// CHECK IF THE VALUE A VALID NUMBER (DOES NOT INCLUDE OTHER CHARACTERS)
		else if (isNaN(propertyValue)) {
			$('#propertyValueValidate').addClass('formError');
			errorList = errorList + '<li>The value of your property is not a valid number.</li>';
			errorCount++;		
		}
		// CHECK IF THE VALUE IS NOT NEGATIVE
		else if (propertyValue < 0) {
			$('#propertyValueValidate').addClass('formError');
			errorList = errorList + '<li>The value of your property can not be a negative.</li>';
			errorCount++;
		}
		// VALUE ENTERED OK, IS NOT A NEGATIVE, AND IS A WHOLE NUMBER. REMOVE FIELD ERROR IF PRESENT	
		else if (propertyValue != "" && $('#propertyValueValidate').hasClass('formError')) {
			$('#propertyValueValidate').removeClass('formError');	
		}
		
		///////////////////////////////////////////////////////////////////////////////////////////
		// DEPOSIT VALUE
		///////////////////////////////////////////////////////////////////////////////////////////
		// CHECK IF A VALUE HAS BEEN ENTERED, AND FIELD LABEL IS DEPOSIT
		if (depositValue == "" && ($('#depositLabel').text() == 'Deposit:')) {
			$('#depositValueValidate').addClass('formError');
			errorList = errorList + '<li>Enter a Deposit</li>';
			errorCount++;
		}
		// CHECK IF A VALUE HAS BEEN ENTERED, AND FIELD LABEL IS OUTSTANDING AMOUNT
		else if (depositValue == "" && ($('#depositLabel').text() != 'Deposit:')) {
			$('#depositValueValidate').addClass('formError');
			errorList = errorList + '<li>Enter the amount that is outstanding on your mortgage</li>';
			errorCount++;
		}
		// CHECK IF THE VALUE A VALID NUMBER, AND FIELD LABEL IS DEPOSIT
		else if (isNaN(depositValue) && ($('#depositLabel').text() == 'Deposit:')) {
			$('#depositValueValidate').addClass('formError');
			errorList = errorList + '<li>Your deposit is not a valid number.</li>';
			errorCount++;
		}	
		// CHECK IF THE VALUE A VALID NUMBER, AND FIELD LABEL IS OUTSTANDING AMOUNT
		else if (isNaN(depositValue) && ($('#depositLabel').text() != 'Deposit:')) {
			$('#depositValueValidate').addClass('formError');
			errorList = errorList + '<li>Your outstanding balance is not a valid number.</li>';
			errorCount++;
		}	
		// CHECK IF THE VALUE IS NOT NEGATIVE, AND FIELD LABEL IS DEPOSIT
		else if (depositValue < 0 && ($('#depositLabel').text() == 'Deposit:')) {
			$('#depositValueValidate').addClass('formError');
			errorList = errorList + '<li>Your deposit can not be a negative.</li>';
			errorCount++;
		}
		// CHECK IF THE VALUE IS NOT NEGATIVE, AND FIELD LABEL IS OUTSTANDING AMOUNT
		else if (depositValue < 0 && ($('#depositLabel').text() != 'Deposit:')) {
			$('#depositValueValidate').addClass('formError');
			errorList = errorList + '<li>Your outstanding balance can not be a negative.</li>';
			errorCount++;
		}	
		// VALUE ENTERED OK, IS NOT A NEGATIVE, AND IS A WHOLE NUMBER. REMOVE FIELD ERROR IF PRESENT	
		else if (depositValue != "" && $('#depositValueValidate').hasClass('formError')) {
			$('#depositValueValidate').removeClass('formError');	
		}
		
		///////////////////////////////////////////////////////////////////////////////////////////
		// REPAYMENT TERM
		///////////////////////////////////////////////////////////////////////////////////////////
		// CHECK IF A VALUE HAS BEEN ENTERED
		if (mortgageTerm == "") {
			$('#mortgageTermValidate').addClass('formError');
			errorList = errorList + '<li>Enter a Mortgage Term</li>';
			errorCount++;
		}
		// CHECK IF THE VALUE A VALID NUMBER
		else if (isNaN(mortgageTerm)) {
			$('#mortgageTermValidate').addClass('formError');
			errorList = errorList + '<li>Your selected Mortgage Term is not a valid number</li>';
			errorCount++;
		}
		// CHECK IF THE VALUE IS NOT NEGATIVE
		else if (mortgageTerm < 0) {
			$('#mortgageTermValidate').addClass('formError');
			errorList = errorList + '<li>Your selected Mortgage Term can not be negative</li>';
			errorCount++;
		}
		// CHECK IF THE VALUE IS LESS THAN 35 YEARS
		else if (mortgageTerm > chelseaMaxTerm) {
			$('#mortgageTermValidate').addClass('formError');
			errorList = errorList + '<li>Your selected Mortgage Term can not exceed ' + chelseaMaxTerm + ' years</li>';
			errorCount++;
		}
		// VALUE ENTERED OK, IS NOT A NEGATIVE, AND IS A WHOLE NUMBER. REMOVE FIELD ERROR IF PRESENT
		else if (mortgageTerm != "" && $('#mortgageTermValidate').hasClass('formError')) {
			$('#mortgageTermValidate').removeClass('formError');	
		}
		
		///////////////////////////////////////////////////////////////////////////////////////////
		// FINAL VALIDATION COLLECTION - ERRORCOUNT CHECK
		///////////////////////////////////////////////////////////////////////////////////////////	
		
		
		// CUSTOMER DID NOT SELECT EXISTING BORROWER - MOVING DEAL OR EXISTING BORROWER - ADDITIONAL LENDING 
		// NO ERRORS FOUND, ALL FIELDS WERE ENTERED CORRECTLY, AND FIELD LABEL IS DEPOSIT
		if (noSearchRequired == 0 && errorCount == 0 && $('#depositLabel').text() == 'Deposit:') {
			// DEPOSIT% = (DEPOSIT ÷ PROPERTY VALUE) x 100 = 
			// CUSTOMER LTV = 100 - DEPOSIT%
			customerDeposit = Math.round((depositValue/propertyValue) * 100);
			customerLTV = (100 - customerDeposit);
			
			// PROPERTY VALUE = CUSTOMER LOAN			
			customerLoan = (propertyValue - depositValue);
			
			$('#formValidationErrorContainer').hide();
			//resetView();
			mortgageSearch();
		}
		// CUSTOMER DID NOT SELECT EXISTING BORROWER - MOVING DEAL OR EXISTING BORROWER - ADDITIONAL LENDING 
		// NO ERRORS FOUND, ALL FIELDS WERE ENTERED CORRECTLY, AND FIELD LABEL IS OUTSTANDING AMOUNT
		else if (noSearchRequired == 0 && errorCount == 0 && $('#depositLabel').text() != 'Deposit:') {
			// CUSTOMER LTV = (DEPOSIT ÷ PROPERTY VALUE) x 100
			customerLTV = Math.round((depositValue/propertyValue) * 100);
			
			// CUSTOMER LOAN = PROPERTY VALUE - DEPOSIT
			customerLoan = depositValue;
			
			$('#formValidationErrorContainer').hide();
			//resetView();
			mortgageSearch();
		}	
		// CUSTOMER HAS SELECTED EXISTING BORROWER - MOVING DEAL OR EXISTING BORROWER - ADDITIONAL LENDING
		// NO ERRORS FOUND, ALL FIELDS WERE ENTERED CORRECTLY, AND FIELD LABEL IS OUTSTANDING AMOUNT
		else if (noSearchRequired != 0 && errorCount == 0) {
			$('#formValidationErrorContainer').hide();
		}
		
		// ERRORS WERE FOUND, DISPLAY LIST WITH RELEVANT ERROR MESSAGES
		else {
			$('#formValidationErrorContainer').show();
			$(errorList).appendTo('#errorMessageList');
		}
		
	}
	
}


/*function checkRange(customerLoan, customerLTV) {

	if (customerLoan < chelseaMinLoan) {
		// DON'T LOOP THE DATA, THE CUSTOMER IS REQUESTING LESS THAN THE MINIMUM LOAN AMOUNT
		// RANGE ERROR MESSAGE alert("REQUESTED LOAN IS BELOW THE MINIMUM");
		rangeError++;
	}	
	else if (customerLoan > chelseaMaxLoan) {
		// DON'T LOOP THE DATA, THE CUSTOMER IS REQUESTING MORE THAN THE MAXIMUM LOAN AMOUNT
		// RANGE ERROR MESSAGE alert("REQUESTED LOAN IS ABOVE THE MAXIMUM");
		rangeError++;
	}	
	else if (customerLTV > chelseaMaxLTV) {
		// DON'T LOOP THE DATA, THE CUSTOMER LTV IS TOO HIGH
		// RANGE ERROR MESSAGE alert("DATA CALCULATION SHOWS LTV IS " + customerLTV + "% - THIS IS ABOVE THE MAXIMUM");
		rangeError++;
	}

}*/




var productTableHeader = '<form id="searchResultsCompareForm" action="Javascript:compareProducts(\'searchRange\');" method="get" name="mortgageComparison">' + 
							'<table id="searchProductsTable" width="100%" cellspacing="0" cellpadding="0" border="0">' +
								'<thead>' +
									'<tr>' +
										'<th class="leftTableColumn" width="16%">Product</th>' +
										'<th width="9%" align="center">Interest rate</th>' +
										'<th width="8%" align="center"><a class="mortgagehelp untilEndDateTip" href="#" onclick="return false">Until end&nbsp;date<div class="mortgagehelpText"><span class="mortgagehelpImg">&nbsp;</span> <span class="mortgagehelpContent">Although the product may be referred to as a \'2 year fixed\' for example, the rate of interest may last slightly more or slightly less than 2 years - until the <strong>product end date</strong>.</span></div></a></th>' +
										'<th width="12%" align="center"><a class="mortgagehelp svrTip" href="#" onclick="return false">Followed by Chelsea\'s&nbsp;SVR, currently<div class="mortgagehelpText"><span class="mortgagehelpImg">&nbsp;</span> <span class="mortgagehelpContent"><strong>SVR</strong> (Standard Variable Rate) applies for the remaining term of the mortgage.</span></div></a></th>' +
										'<th width="13%" align="center"><a class="mortgagehelp costForComparisonTip" href="#" onclick="return false">The overall cost for comparison is<div class="mortgagehelpText"><span class="mortgagehelpImg">&nbsp;</span> <span class="mortgagehelpContent"><strong>APR</strong> is a figure which all lenders must quote when referring to mortgages. It is designed to show the total yearly cost of a mortgage stated as a percentage of the loan. It includes items such as the interest rate paid at the start of the mortgage, product fee, valuation fee and other charges commonly paid at the end of a mortgage. This figure is intended to help customers compare the overall cost of different loans.</span></div></a></th>' +
										'<th width="8%" align="center">Min. deposit</th>' +
										'<th width="8%" align="center">Product fee</th>' +
										'<th width="10%" align="center"><a class="mortgagehelp estimatedMonthlyRepaymentTip" href="#" onclick="return false">Estimated Monthly Repayment<div class="mortgagehelpText"><span class="mortgagehelpImg">&nbsp;</span> <span class="mortgagehelpContent">The <strong>Estimated Monthly Repayments</strong> provided are for illustration purposes only and assume that the initial interest rate will remain the same throughout the term of the mortgage, and mortgage type is repayment (rather than interest-only).</span></div></a></th>' +
										'<th class="noprint" width="4%" align="center"><a class="mortgagehelp moreInfoSearchTip" href="#" onclick="return false"><img alt="" src="/img/mortgages/icon-moreinfo.gif" /><div class="mortgagehelpText" ><span class="mortgagehelpImg">&nbsp;</span> <span class="mortgagehelpContent"><strong>More information</strong> click the "Details" links below to find out more about each product.</span></div></a></th>' +
										'<th class="rightTableColumnCTA noprint" width="11%" align="center"><input id="mortgageProductCompare" class="image" type="image" src="/img/buttons/button-mortgage-product-compare.gif" title="Compare mortgage products" value="mortgageProductCompare" name="mortgageProductCompare"></th>' +
									'</tr>' +
								'</thead>' +
								'<tbody>';

var productTableFooter = 			'<tr>' +
										'<td class="leftTableColumnCTA noprint" colspan="6" align="left" style="padding-left:4px;"><a href="#full-product-range" title="View full mortgage range"><img src="/img/buttons/button-mortgage-product-viewRange-large.gif" alt="View full mortgage range" /></a></td>' +
										'<td class="rightTableColumnCTA noprint" colspan="4" align="right"><input id="mortgageProductCompare" class="image" type="image" src="/img/buttons/button-mortgage-product-compare.gif" title="Compare mortgage products" value="mortgageProductCompare" name="mortgageProductCompare"></td>' +
									'</tr>' +
								'</tbody>' +
							'</table>' +
							'<div class="tableBottomClear"></div>' + 
						'</form>';
						

var productCheckSuccess;

function mortgageSearch(mortgageProductData) {
	
	setTimeout('$(\'#resultsView\').scrollTo();',200);
	
	$('#resultsData').empty();
		
	var searchResultsIntroText = '';
	var searchResultsProducts = '';	

	productCheckSuccess = 0;
	
	var offsetSearchTypes = "";
	
	if (mortgageType == "fixed") {						
		mortgageType = ["fixed","fixedoffset","mixed","mixedoffset"];
		$('#offsetToolsContainerFinder').hide();
	}
	else if (mortgageType == "tracker") {						
		mortgageType = ["tracker","trackeroffset","mixed","mixedoffset"];
		$('#offsetToolsContainerFinder').hide();
	}
	else if (mortgageType == "offset") {
		mortgageType = ["fixedoffset","trackeroffset","mixedoffset"];
		$('#offsetToolsContainerFinder').show();
	}
	else if (mortgageType == "mixed") {						
		mortgageType = ["mixed","mixedoffset"];
		$('#offsetToolsContainerFinder').hide();
	}
	else {
		// do nothing
	}

	$('#resultsData').hide();	
	
	setTimeout('$(\'.searchInProgressAnimationContainer\').show();',50);
	setTimeout('searchInProgressAnimation("#resultsData")',loadingAnimationTimeoutLength);			
	
	// SETUP TIERS FOR PRODUCT SEARCH		
	var setTier;
	
	if (customerLTV <= ltvTier1) {
		setTier = "TIER 1";		
	}
	else if (customerLTV > ltvTier1 && customerLTV <= ltvTier2) {
		setTier = "TIER 2";
	}
	else if (customerLTV > ltvTier2 && customerLTV <= ltvTier3) {
		setTier = "TIER 3";
	}
	else if (customerLTV > ltvTier3 && customerLTV <= ltvTier4) {
		setTier = "TIER 4";
	}
	else if (customerLTV > ltvTier4 && customerLTV <= ltvTier5) {
		setTier = "TIER 5";
	}
	else if (customerLTV > ltvTier5 && customerLTV <= ltvTier6) {
		setTier = "TIER 6";
	}
	else if (customerLTV > ltvTier6) {


		setTier = "TIER 7";
	}
	
	// FIRST RUN PRODUCT SEARCH - SET THE UPPER AND LOWER BOUNDARY FOR THE SEARCH AND PERFORM A SEARCH BASED ON THAT BOUNDARY
	tierSetter();
	productSearch();
	
	// IF A CUSTOMER LTV IS 60% THEN EVERY PRODUCT UNDER 85% WOULD BE RETURNED IN A SEARCH
	// TO MAKE IT MORE TAILORED TO THE CUSTOMER, WE SET TIERS SO THAT ONLY THE MOST RELEVANT PRODUCTS ARE RETURNED
	// THEREFORE ON CUSTOMER LTV OF 60%, TIER 1 WOULD FIRSTLY BE SET AS THE PRODUCT LIES BETWEEN 0-60
	// A CHECK WOULD THEN BE PERFORMED FOR PRODUCTS IN THIS TIER
	// IF NONE ARE RETURNED, THE BOUNDARIES WOULD THEN BE CHANGED TO SO A CHECK CAN BE PERFORMED ON THE NEXT TIER 61-70
	// AND SO ON UNTIL PRODUCTS ARE FOUND FOR THE NEAREST TIER TO THE CUSTOMER LTV.
	// THIS METHOD PREVENTS MASS RETURN OF RESULTS AND IS MORE TAILORED TO THE CUSTOMER REQUIREMENTS.
	while (productCheckSuccess < 2) {
		//alert(productCheckSuccess);
		if (setTier == "TIER 7") {
			//alert("TIER 5 CHECK COMPLETE - NO PRODUCTS FOUND");
			break;
		}
		else if (setTier == "TIER 6") {
			//alert("TIER 5 CHECK COMPLETE - NO PRODUCTS FOUND");
			setTier = "TIER 7";
			tierSetter();
			productSearch();
		}
		else if (setTier == "TIER 5") {
			//alert("TIER 5 CHECK COMPLETE - NO PRODUCTS FOUND");
			setTier = "TIER 6";
			tierSetter();
			productSearch();
		}
		else if (setTier == "TIER 4") {
			//alert("TIER 4 CHECK COMPLETE - NO PRODUCTS FOUND");
			setTier = "TIER 5";
			tierSetter();
			productSearch();
		}
		else if (setTier == "TIER 3") {
			//alert("TIER 3 CHECK COMPLETE - NO PRODUCTS FOUND");
			setTier = "TIER 4";
			tierSetter();
			productSearch();
		}
		else if (setTier == "TIER 2") {
			//alert("TIER 2 CHECK COMPLETE - NO PRODUCTS FOUND");
			setTier = "TIER 3";
			tierSetter();
			productSearch();
		}
		else if (setTier == "TIER 1") {
			//alert("TIER 1 CHECK COMPLETE - NO PRODUCTS FOUND");				
			setTier = "TIER 2";
			tierSetter();
			productSearch();
		}
		
	}
	
	// SET A TIER
	function tierSetter() {
	
		switch (setTier) {
			case "TIER 1":
				//alert("TIER 1");
				lowerBoundary = 0;
				upperBoundary = ltvTier1;
				break;
			case "TIER 2":
				//alert("TIER 2");
				lowerBoundary = ltvTier1;
				upperBoundary = ltvTier2;
				break;
			case "TIER 3":
				//alert("TIER 3");
				lowerBoundary = ltvTier2;
				upperBoundary = ltvTier3;
				break;
			case "TIER 4":
				//alert("TIER 4");
				lowerBoundary = ltvTier3;
				upperBoundary = ltvTier4;
				break;
			case "TIER 5":
				//alert("TIER 5");
				lowerBoundary = ltvTier4;
				upperBoundary = ltvTier5;
				break;
			case "TIER 6":
				//alert("TIER 5");
				lowerBoundary = ltvTier5;
				upperBoundary = ltvTier6;
				break;
			case "TIER 7":
				//alert("TIER 5");
				lowerBoundary = ltvTier6;
				upperBoundary = ltvTier7;
				break;
		}
	
	}
	
	// PERFORM A CHECK TO COLLECT THE PRODUCTS THAT MATCH THE SEARCH
	function productSearch() {
		
		//alert("customerLTV = " + customerLTV);
		
		for (var i = 0; i < mortgageProducts.length; i++) {	
		
			var allCheckSuccess = 0;
			//alert("PRODUCT " + i + " CHECK STARTS");
			
			var mortCode = mortgageProducts[i].getAttribute("code");
			
			var mortCustomerType = mortgageProducts[i].getAttribute(customerType);
			var mortBuyerType = mortgageProducts[i].getAttribute(buyerType);			
			
			var mortMortgageType = mortgageProducts[i].getAttribute("mortgageType");
			
			var mortMinLoan = mortgageProducts[i].getAttribute("minLoan");
			mortMinLoan = mortMinLoan.replace(/\,/g,'');
			mortMinLoan = Math.round(mortMinLoan)
			var mortMaxLoan = mortgageProducts[i].getAttribute("maxLoan");	
			mortMaxLoan = mortMaxLoan.replace(/\,/g,'');
			mortMaxLoan = Math.round(mortMaxLoan);
			
			var mortMaxLTV = mortgageProducts[i].getAttribute("maxLTV");
			mortMaxLTV = mortMaxLTV.substring(0, 2);
			// LIMIT INTEREST RATE TO RATE ONLY (FIRST 5 CHARACTERS) - ADDITIONAL DETAILS ARE FOR FULL DETAIL VIEW ONLY
			var mortInterestRate1 = mortgageProducts[i].getAttribute("interestRate");
			mortInterestRate1 = mortInterestRate1.substring(0, 4);
			var mortInterestRate2 = mortgageProducts[i].getAttribute("interestRate2");
			mortInterestRate2 = mortInterestRate2.substring(0, 4);
			var mortInterestRate = "";
			if (mortInterestRate2 != "") {
				mortInterestRate = mortInterestRate1 + "%<br />" + mortInterestRate2;
			}
			else {
				mortInterestRate = mortInterestRate1;
			}
			
								
			if (mortCustomerType == "Y") {
				
				//alert("CHECK 1 SUCCESS");
				
				if (mortBuyerType == "Y") {
					
					//alert("CHECK 2 SUCCESS");
					
					// CUSTOMER SELECTED FIXED/OFFSET/TRACKER FROM MORTGAGE TYPE DROPDOWN WHICH INCLUDES MORE THAN 1 VALUE
					if (mortgageType.length > 1) {
						
						for (var num = 0; num < mortgageType.length; num++) {
							
							if (mortMortgageType == mortgageType[num]) {
								
								//alert("CHECK 3 SUCCESS");
								allCheckSuccess++;	
								
							}
							
							else if (mortMortgageType == mortgageType || mortgageType == "allMortgageTypes") {
								//alert("CHECK 3 SUCCESS");
								allCheckSuccess++;
							}
							
							else {
								//alert("CHECK 5 FAILED - MOVE TO NEXT PRODUCT");
							}
							
						}					
						
					}
					
					if (allCheckSuccess != 0) {
						
						if (customerLoan < mortMinLoan) {
							
							//alert(mortCode + " - less than min loan");	
						
						}
						else if (customerLoan > mortMaxLoan) {
							
							//alert(mortCode + " - greater than max loan");
						
						}
						else if (mortMaxLTV > lowerBoundary && mortMaxLTV <= upperBoundary) {
							
							//alert(mortCode + " - PRODUCT INCLUDED");
															
							// CALCULATE ESTIMATED MONTHLY REPAYMENT
							estimatedMonthlyRepayment = (mortInterestRate1/100/12)/(1 - Math.pow((1 + mortInterestRate1/100/12),(-mortgageTerm*12)) )*customerLoan;
							estimatedMonthlyRepayment = '£' + Math.round(estimatedMonthlyRepayment);
							estimatedMonthlyRepayment = addCommas(estimatedMonthlyRepayment);
							//alert(estimatedMonthlyRepayment);
							
							// PRODUCT CHECK SUCCESSFUL
							productCheckSuccess++;
							
							var mortName = mortgageProducts[i].getAttribute("name");
							var mortPageURL = mortgageProducts[i].getAttribute("pageURL");	
								
							var mortPageFolder = "";
							switch (mortMortgageType) {
								case "fixed":
									mortPageFolder = "fixed";
									break;
								case "fixedoffset":
									mortPageFolder = "fixed-offset";
									break;
								case "tracker":
									mortPageFolder = "tracker";
									break;
								case "trackeroffset":
									mortPageFolder = "tracker-offset";
									break;
								case "mixed":
									mortPageFolder = "tracker-to-fixed";
									break;
								case "mixedoffset":
									mortPageFolder = "tracker-to-fixed-offset";
									break;			
							}
							
							
							var mortTerm = mortgageProducts[i].getAttribute("term");
							var mortTerm2 = mortgageProducts[i].getAttribute("term2");
							if (mortTerm2 != "") {
								mortTerm = mortTerm + "<br />" + mortTerm2;
							}
							
							var mortSVR = chelseaSVR;
							var mortCostForComparison = mortgageProducts[i].getAttribute("apr");
							var mortMinDeposit = (100 - mortMaxLTV);
							
							var mortBookingFee = mortgageProducts[i].getAttribute("bookingFee");		
							var mortCompletionFee = mortgageProducts[i].getAttribute("completionFee");
							mortProductFee = "";			
							if (mortBookingFee == "None" || mortBookingFee == "none") {
								mortProductFee = "None";
							}
							else {			
								var mortProductFee = (parseInt(mortBookingFee) + parseInt(mortCompletionFee));	
								mortProductFee = "£" + addCommas(mortProductFee);
							}
							
							searchResultsProducts = searchResultsProducts + '<tr>' +
								'<td class="leftTableColumn"><a href="products/' + mortPageFolder + '/' + mortPageURL + '" class="productSelectionLink" title="' + mortName + '"><strong>' + mortName + '</strong></a></td>' +
								'<td align="center">' + mortInterestRate + '%</td>' +
								'<td align="center">' + mortTerm + '</td>' +
								'<td align="center">' + mortSVR + '</td>' +
								'<td align="center">' + mortCostForComparison + ' APR</td>' +
								'<td align="center">' + mortMinDeposit + '%</td>' +
								'<td align="center">' + mortProductFee + '</td>' +
								'<td align="center" class="estimatedMonthlyRepaymentValue"><strong>' + estimatedMonthlyRepayment + '</strong></td>' +
								/*'<td class="noprint" align="center"><a href="products/' + mortPageURL + '" class="productSelectionLink" title="Find out more about this product"><img src="/img/bullet-small-darkred.gif" alt="Find out more about this product" /></a></td>' +*/
								'<td class="noprint" align="center"><a href="products/' + mortPageFolder + '/' + mortPageURL + '" class="productSelectionLink" title="Find out more details about this product"><strong>Details</strong></a></td>' +
								'<td class="rightTableColumnCTA noprint" align="center"><input class="accountCompareCheckbox" type="checkbox" name="account" value="' + i + '" /></td>' +
							'</tr>';
								
						}
						else {
							//alert(mortCode + " - CHECK 4 FAILED - OUTSIDE SELECTED TIER");	
						}
						
					}
					else {
						//alert(mortCode + " - CHECK 3 FAILED - SUCCESS FLAG NOT PRESENT");	
					}
					
				}			
				else {
					//alert(mortCode + " - CHECK 2 FAILED - BUYER TYPE");
				}
				
			}	
			
			else {
				//alert(mortCode + " - CHECK 1 FAILED - MORTGAGE TYPE");

			}
			
		}	
		
	}	
	
	if (productCheckSuccess == 0) {
		$('#resultsData').hide();	
		setTimeout('$(\'.searchInProgressAnimationContainer\').show();',50);
		setTimeout('searchInProgressAnimation("#resultsData")',loadingAnimationTimeoutLength);
		
		$('<p><strong>There are no products that match your requirements.</strong></p>' +
		  '<p>Please <a href="#" onclick="resetView(); return false;" title="modify your search">modify your search</a> and try again.</p>' +
		  '<p>Alternately, you can <a href="#full-product-range" title="View full mortgage range"><strong>view all our mortgage products</strong></a></p>' + 
		  '<p>&nbsp;</p>').appendTo('#resultsData');
	}
	else if (productCheckSuccess == 1) {
		searchResultsIntroText = '<div class="searchResultsIntroCopy">Based on your <strong>Loan to Value of ' + customerLTV + '%</strong> we have <strong>' + productCheckSuccess + ' product</strong> that best meets your mortgage requirements.<br />' +
		'If your loan requirements are flexible, you may want to change your loan amount to show different products.</div>' +
		'<div class="searchAgainContainer"><a class="modifyFormButton" href="#" title="Modify the search details you have entered"><img src="/img/buttons/button-mortgage-product-modifySearch.gif" alt="Modify search" /></a></div>' +
		'<div class="clear"></div>';
		$(searchResultsIntroText + productTableHeader + searchResultsProducts + productTableFooter).appendTo('#resultsData');
	}
	else {
		searchResultsIntroText = '<div class="searchResultsIntroCopy">Based on your <strong>Loan to Value of ' + customerLTV + '%</strong> we have <strong>' + productCheckSuccess + ' products</strong> that best meet your mortgage requirements.<br />' +
		'If your loan requirements are flexible, you may want to change your loan amount to show different products.</div>' +
		'<div class="searchAgainContainer"><a class="modifyFormButton" href="#" title="Modify the search details you have entered"><img src="/img/buttons/button-mortgage-product-modifySearch.gif" alt="Modify search" /></a></div>' +
		'<div class="clear"></div>';
		$(searchResultsIntroText + productTableHeader + searchResultsProducts + productTableFooter).appendTo('#resultsData');
	}
	
	window.location.hash = "#search-results";
	
}

// LOADING ANIMATION (FOR AESTHETICS ONLY)
function searchInProgressAnimation(searchMethod) {
	
	$('.searchInProgressAnimationContainer').hide();
	
	if (searchMethod == "#compareData") {
		$('#compareData').show();
		setHeights();
	}
	else {
		$(searchMethod).show();
	}
	
}






// FULL RANGE VIEW

						
function showFullRange() {
	
	var productTableID = "";
	var compareMethodTableType = "";	
	
	if (pageViewHashValue == "#offset-range") {
		mortgageType = ["fixedoffset","trackeroffset","mixedoffset"];
		productTableID = "offsetProductsTable";
		// DEFINE THE TABLE WITH WHICH TO PULL THE ESTIMATED MONTHLY REPAYMENT DATA FROM
		compareMethodTableType = "offsetRange";
	}
	else if (pageViewHashValue == "#fixed-range") {
		mortgageType = ["fixed","fixedoffset","mixed","mixedoffset"];
		productTableID = "fixedProductsTable";
		// DEFINE THE TABLE WITH WHICH TO PULL THE ESTIMATED MONTHLY REPAYMENT DATA FROM
		compareMethodTableType = "fixedRange";
	}
	else if (pageViewHashValue == "#tracker-range") {
		mortgageType = ["tracker","trackeroffset","mixed","mixedoffset"];
		productTableID = "trackerProductsTable";
		// DEFINE THE TABLE WITH WHICH TO PULL THE ESTIMATED MONTHLY REPAYMENT DATA FROM
		compareMethodTableType = "trackerRange";
	}
	else if (pageViewHashValue == "#tracker-to-fixed-range") {
		mortgageType = ["mixed","mixedoffset"];
		productTableID = "trackerToFixedProductsTable";
		// DEFINE THE TABLE WITH WHICH TO PULL THE ESTIMATED MONTHLY REPAYMENT DATA FROM
		compareMethodTableType = "trackerToFixedRange";
	}	
	else {
		mortgageType = ["fixedoffset","trackeroffset","fixed","tracker","mixed","mixedoffset"];
		productTableID = "allProductsTable";
		// DEFINE THE TABLE WITH WHICH TO PULL THE ESTIMATED MONTHLY REPAYMENT DATA FROM
		compareMethodTableType = "fullRange";
	}
	
	var rangeTableHeader = '<form id="fullRangeCompareForm" action="Javascript:compareProducts(\'' + compareMethodTableType + '\');" method="get" name="mortgageComparison">' + 
								'<table id="' + productTableID + '" width="100%" cellspacing="0" cellpadding="0" border="0">' +
									'<thead>' +
										'<tr>' +
											'<th class="leftTableColumn" width="16%">Product</th>' +
											'<th width="9%" align="center">Interest rate</th>' +
											'<th width="8%" align="center"><a class="mortgagehelp untilEndDateTip" href="#" onclick="return false">Until end&nbsp;date<div class="mortgagehelpText"><span class="mortgagehelpImg">&nbsp;</span> <span class="mortgagehelpContent">Although the product may be referred to as a \'2 year fixed\' for example, the rate of interest may last slightly more or slightly less than 2 years - until the <strong>product end date</strong>.</span></div></a></th>' +
											'<th width="12%" align="center"><a class="mortgagehelp svrTip" href="#" onclick="return false">Followed by Chelsea\'s&nbsp;SVR, currently<div class="mortgagehelpText"><span class="mortgagehelpImg">&nbsp;</span> <span class="mortgagehelpContent"><strong>SVR</strong> (Standard Variable Rate) applies for the remaining term of the mortgage.</span></div></a></th>' +
											'<th width="13%" align="center"><a class="mortgagehelp costForComparisonTip" href="#" onclick="return false">The overall cost for comparison is<div class="mortgagehelpText"><span class="mortgagehelpImg">&nbsp;</span> <span class="mortgagehelpContent"><strong>APR</strong> is a figure which all lenders must quote when referring to mortgages. It is designed to show the total yearly cost of a mortgage stated as a percentage of the loan. It includes items such as the interest rate paid at the start of the mortgage, product fee, valuation fee and other charges commonly paid at the end of a mortgage. This figure is intended to help customers compare the overall cost of different loans.</span></div></a></th>' +
											'<th width="8%" align="center">Min. deposit</th>' +
											'<th width="8%" align="center">Product fee</th>' +
											'<th width="10%" align="center"><a class="mortgagehelp estimatedMonthlyRepaymentTip" href="#" onclick="return false">Estimated Monthly Repayment<div class="mortgagehelpText"><span class="mortgagehelpImg">&nbsp;</span> <span class="mortgagehelpContent">The <strong>Estimated Monthly Repayments</strong> provided are for illustration purposes only and assume that the initial interest rate will remain the same throughout the term of the mortgage, and mortgage type is repayment (rather than interest-only).</span></div></a></th>' +
											'<th class="noprint" width="4%" align="center"><a class="mortgagehelp moreInfoSearchTip" href="#" onclick="return false"><img alt="" src="/img/mortgages/icon-moreinfo.gif" /><div class="mortgagehelpText" ><span class="mortgagehelpImg">&nbsp;</span> <span class="mortgagehelpContent"><strong>More information</strong> click the "Details" links below to find out more about each product.</span></div></a></th>' +
											'<th class="rightTableColumnCTA noprint" width="11%" align="right"><input id="mortgageProductCompare" class="image" type="image" src="/img/buttons/button-mortgage-product-compare.gif" title="Compare mortgage products" value="mortgageProductCompare" name="mortgageProductCompare"></th>' +
										'</tr>' +
									'</thead>' +
									'<tbody>';
	
	var rangeTableFooter = 			'<tr>' +
	
										'<td class="leftTableColumnCTA noprint" colspan="6" align="left" style="padding-left:4px;"><a href="#" onclick="resetView(); return false;" title="Use the find a mortgage form to narrow your search"><img src="/img/buttons/button-mortgage-product-narrow-search.gif" alt="Use the find a mortgage form to narrow your search" /></a></td>' +	
										'<td colspan="4" class="rightTableColumnCTA noprint" align="right"><input id="mortgageProductCompare" class="image" type="image" src="/img/buttons/button-mortgage-product-compare.gif" value="mortgageProductCompare" name="mortgageProductCompare"></td>' +
										'</tr>' +
									'</tbody>' +
								'</table>' +
								'<div class="tableBottomClear"></div>' + 
							'</form>';
	
	
	customerType = $("#customerTypeSelector").val();
	buyerType = $("#buyerTypeSelector").val();
	
	var fullRangeProduct = '';
	var fullRangeProductUnavailable = '';
	
	// FINDER FORM HAS NOT BEEN COMPLETED, THE CUSTOMERLTV THEREFORE CANNOT BE CALCULATED
	if ((isNaN(customerLTV))) {	
		fullRangeIntroCopy = '<p>This is our full range of mortgage products. To view the mortgage products that may be suitable for you and find out what your Estimated Monthly Repayment could be, please complete <a class="modifyFormButton" href="#" title="mortgage finder"><strong>mortgage finder</strong></a> above.</p>';	
	}
	// FINDER FORM COMPLETED, CUSTOMERLTV CALCULATED
	else {
		fullRangeIntroCopy = '<p>Based on the information you have provided, we have highlighted the products that could be available to you and supplied you with an Estimated Monthly Repayment to help you. To narrow your search to only the products that best suit your requirements, please complete <a class="modifyFormButton" href="#" title="mortgage finder"><strong>mortgage finder</strong></a> above.</p>';	
	}
	
	if (pageViewHashValue != "#full-product-range") {
		$('#typeRangeData').hide();
	}
	else {	
		$('#fullRangeData').hide();
	}
	
	var totalProducts = 0;
		
	for (var i = 0; i < mortgageProducts.length; i++) {
		
		var mortTypeSuccess = 0;
		
		//var mortCode = mortgageProducts[i].getAttribute("code");
		
		var mortCustomerType = mortgageProducts[i].getAttribute(customerType);
		var mortBuyerType = mortgageProducts[i].getAttribute(buyerType);
		var mortMortgageType = mortgageProducts[i].getAttribute("mortgageType");
		
		//alert("mortMortgageType = " + mortMortgageType + ", mortgageType[num] = " + mortgageType);
		
		// CUSTOMER SELECTED FIXED/OFFSET/TRACKER FROM MORTGAGE TYPE DROPDOWN WHICH INCLUDES MORE THAN 1 VALUE
		if (mortgageType.length > 1) {
			
			for (var num = 0; num < mortgageType.length; num++) {
				
				if (mortMortgageType == mortgageType[num]) {
					
					//alert("mortgageType: " + mortgageType + ", mortMortgageType: " + mortMortgageType);
					mortTypeSuccess++;
					//alert(mortCode + " - match found");
					
				}
				
				else if (mortMortgageType == mortgageType || mortgageType == "allMortgageTypes") {
					
					mortTypeSuccess++;
					//alert(mortCode + " - match found");
					
				}
				
				else {
					
					// do nothing
					//alert(mortCode + " - no match found");
					
				}
				
			}					
			
		}
				
		var mortMaxLTV = mortgageProducts[i].getAttribute("maxLTV");		
		mortMaxLTV = mortMaxLTV.substring(0, 2);
		
		var mortTerm = mortgageProducts[i].getAttribute("term");
		var mortTerm2 = mortgageProducts[i].getAttribute("term2");		
		if (mortTerm2 != "") {
			mortTerm = mortTerm + "<br />" + mortTerm2;
		}
		
		// LIMIT INTEREST RATE TO RATE ONLY (FIRST 5 CHARACTERS) - ADDITIONAL DETAILS ARE FOR FULL DETAIL VIEW ONLY
		var mortInterestRate1 = mortgageProducts[i].getAttribute("interestRate");
		mortInterestRate1 = mortInterestRate1.substring(0, 4);
		var mortInterestRate2 = mortgageProducts[i].getAttribute("interestRate2");
		mortInterestRate2 = mortInterestRate2.substring(0, 4);
		var mortInterestRate = "";
		if (mortInterestRate2 != "") {
			mortInterestRate = mortInterestRate1 + "%<br />" + mortInterestRate2;
		}
		else {
			mortInterestRate = mortInterestRate1;
		}
		
		var mortName = mortgageProducts[i].getAttribute("name");
		var mortPageURL = mortgageProducts[i].getAttribute("pageURL");
		
		var mortPageFolder = "";
		switch (mortMortgageType) {
			case "fixed":
				mortPageFolder = "fixed";
				break;
			case "fixedoffset":
				mortPageFolder = "fixed-offset";
				break;
			case "tracker":
				mortPageFolder = "tracker";
				break;
			case "trackeroffset":
				mortPageFolder = "tracker-offset";
				break;
			case "mixed":
				mortPageFolder = "tracker-to-fixed";
				break;
			case "mixedoffset":
				mortPageFolder = "tracker-to-fixed-offset";
				break;			
		}
		
		var mortSVR = chelseaSVR;
		var mortCostForComparison = mortgageProducts[i].getAttribute("apr");
		var mortMinDeposit = (100 - mortMaxLTV);
		
		var mortBookingFee = mortgageProducts[i].getAttribute("bookingFee");		
		var mortCompletionFee = mortgageProducts[i].getAttribute("completionFee");
		var mortProductFee = (parseInt(mortBookingFee) + parseInt(mortCompletionFee));	
		mortProductFee = "";			
		if (mortBookingFee == "None" || mortBookingFee == "none") {
			mortProductFee = "None";
		}
		else {			
			var mortProductFee = (parseInt(mortBookingFee) + parseInt(mortCompletionFee));	
			mortProductFee = "£" + addCommas(mortProductFee);
		}
		
		
		productUnavailable = '<tr style="background:#f0f0f0;">' +
				'<td class="leftTableColumn"><strong>' + mortName + '</strong></td>' +
				'<td align="center">' + mortInterestRate + '%</td>' +
				'<td align="center">' + mortTerm + '</td>' +
				'<td align="center">' + mortSVR + '</td>' +
				'<td align="center">' + mortCostForComparison + ' APR</td>' +
				'<td align="center">' + mortMinDeposit + '%</td>' +
				'<td align="center">' + mortProductFee + '</td>' +
				'<td align="center" class="estimatedMonthlyRepaymentValue"><strong>n/a</strong></td>' +
				'<td class="noprint" align="center"><strong>n/a</strong></td>' +
				'<td class="rightTableColumnCTA noprint" align="center"><input class="accountCompareCheckbox" type="checkbox" name="account" value="' + i + '" DISABLED /></td>' +
			'</tr>';
		
		productEstimatedMonthlyRepaymentUnavailable = '<tr>' +
				'<td class="leftTableColumn"><a href="products/' + mortPageFolder + '/' + mortPageURL + '" class="productSelectionLink" title="' + mortName + '"><strong>' + mortName + '</strong></a></td>' +
				'<td align="center">' + mortInterestRate + '%</td>' +
				'<td align="center">' + mortTerm + '</td>' +
				'<td align="center">' + mortSVR + '</td>' +
				'<td align="center">' + mortCostForComparison + ' APR</td>' +
				'<td align="center">' + mortMinDeposit + '%</td>' +
				'<td align="center">' + mortProductFee + '</td>' +
				'<td align="center" class="estimatedMonthlyRepaymentValue"><strong>n/a</strong></td>' +
				'<td class="noprint" align="center"><a href="products/' + mortPageFolder + '/' + mortPageURL + '" class="productSelectionLink" title="Find out more details about this product"><strong>Details</strong></a></td>' +				
				'<td class="rightTableColumnCTA noprint" align="center"><input class="accountCompareCheckbox" type="checkbox" name="account" value="' + i + '" /></td>' +
			'</tr>';
			
		var mortMinLoan = mortgageProducts[i].getAttribute("minLoan");
		mortMinLoan = mortMinLoan.replace(/\,/g,'');
		mortMinLoan = Math.round(mortMinLoan)
		var mortMaxLoan = mortgageProducts[i].getAttribute("maxLoan");	
		mortMaxLoan = mortMaxLoan.replace(/\,/g,'');
		mortMaxLoan = Math.round(mortMaxLoan);
			
		
			
		if (customerLoan != 0 && customerLoan < mortMinLoan && mortTypeSuccess != 0 && mortCustomerType == "Y" && mortBuyerType == "Y" && mortTypeSuccess != 0 && (customerLTV <= mortMaxLTV) && !(isNaN(customerLTV)) && (productCheckSuccess != 0)) {
							
			//alert(mortCode + " - less than min loan");	
			fullRangeProductUnavailable = fullRangeProductUnavailable + productUnavailable;
						
		}
		else if (customerLoan != 0 && customerLoan > mortMaxLoan && mortTypeSuccess != 0 && mortCustomerType == "Y" && mortBuyerType == "Y" && mortTypeSuccess != 0 && (customerLTV <= mortMaxLTV) && !(isNaN(customerLTV)) && (productCheckSuccess != 0)) {
			
			//alert(mortCode + " - greater than max loan");
			fullRangeProductUnavailable = fullRangeProductUnavailable + productUnavailable;
		
		}
		
		// NEWBORROWER/EXISTING BORROWER IS DEFINED, CUSTOMERLTV IS LESS THAN MORTGAGE MAXLTV AND CUSTOMERLTV IS A VALID NUMBER
		else if (mortCustomerType == "Y" && mortBuyerType == "Y" && mortTypeSuccess != 0 && (customerLTV <= mortMaxLTV) && !(isNaN(customerLTV)) && (productCheckSuccess != 0)) {
			
			//alert("1 - " + mortCode);			
			// CALCULATE ESTIMATED MONTHLY REPAYMENT
			estimatedMonthlyRepayment = (mortInterestRate1/100/12)/(1 - Math.pow((1 + mortInterestRate1/100/12),(-mortgageTerm*12)) )*customerLoan;	
			estimatedMonthlyRepayment = '£' + Math.round(estimatedMonthlyRepayment);
			estimatedMonthlyRepayment = addCommas(estimatedMonthlyRepayment);
			
			fullRangeProduct = fullRangeProduct + '<tr>' +
				'<td class="leftTableColumn"><a href="products/' + mortPageFolder + '/' + mortPageURL + '" onclick="return false" class="productSelectionLink" title="' + mortName + '"><strong>' + mortName + '</strong></a></td>' +
				'<td align="center">' + mortInterestRate + '%</td>' +
				'<td align="center">' + mortTerm + '</td>' +
				'<td align="center">' + mortSVR + '</td>' +
				'<td align="center">' + mortCostForComparison + ' APR</td>' +
				'<td align="center">' + mortMinDeposit + '%</td>' +
				'<td align="center">' + mortProductFee + '</td>' +
				'<td align="center" class="estimatedMonthlyRepaymentValue"><strong>' + estimatedMonthlyRepayment + '</strong></td>' +
				'<td class="noprint" align="center"><a href="products/' + mortPageFolder + '/' + mortPageURL + '" class="productSelectionLink" title="Find out more details about this product"><strong>Details</strong></a></td>' +				
				'<td class="rightTableColumnCTA noprint" align="center"><input class="accountCompareCheckbox" type="checkbox" name="account" value="' + i + '" /></td>' +
			'</tr>';
			
		}
		// NEWBORROWER/EXISTING BORROWER IS DEFINED, CUSTOMERLTV IS GREATER THAN MORTGAGE MAXLTV AND CUSTOMERLTV IS A VALID NUMBER
		else if (mortCustomerType == "Y" && mortBuyerType == "Y" && mortTypeSuccess != 0 && (customerLTV > mortMaxLTV) && !(isNaN(customerLTV)) && (productCheckSuccess != 0)) {			
			//alert("2 - " + mortCode);		
			fullRangeProductUnavailable = fullRangeProductUnavailable + productUnavailable;
			
		}
		// NEWBORROWER/EXISTING BORROWER IS DEFINED, USER HAS MOVED STRAIGHT TO VIEWING ALL PRODUCTS WITHOUT COMPLETING FINDER FORM, BUT 		CUSTOMERLTV IS NOT A VALID NUMBER
		else if (mortCustomerType == "Y" && mortBuyerType != "Y" && mortTypeSuccess != 0 && displayAllOnLoad != true && (isNaN(customerLTV))) {			
			
			//alert("3 - " + mortCode);
			fullRangeProductUnavailable = fullRangeProductUnavailable + productEstimatedMonthlyRepaymentUnavailable;
			
		}
		// USER HAS MOVED STRAIGHT TO VIEWING ALL PRODUCTS VIA DIRECT #full-product-range URL
		else if (mortTypeSuccess != 0 && mortCustomerType == "Y" && mortBuyerType != "Y" && displayAllOnLoad == true && (isNaN(customerLTV)) && (productCheckSuccess != 0)) {					
			
			//alert("4 - " + mortCode + " DIRECT URL");			
			fullRangeProductUnavailable = fullRangeProductUnavailable + productEstimatedMonthlyRepaymentUnavailable;
			
		}
		
		// USER HAS VIEWED FULL RANGE, IS AN EXISTING CUSTOMER, HAS VIEWED CHANGE DEAL OR ADDITIONAL LENDING STATES AND HAS MOVED BACK TO FULL RANGE
		else if (mortCustomerType == "Y" && buyerType == "changingDeal" || mortCustomerType == "Y" && buyerType == "additionalLending") {
			
			//alert("5 - " + mortCode);			
			fullRangeProductUnavailable = fullRangeProductUnavailable + productUnavailable;
		
		}
		
		// USER HAS RETURNED A SEARCH WITH NO RESULTS AND HAS MOVED TO VIEW ALL PRODUCTS - ALL PRODUCTS ARE UNAVAILABLE		
		else if (productCheckSuccess == 0 && mortTypeSuccess != 0) {
			
			//alert("6 - " + mortCode);			
			fullRangeProductUnavailable = fullRangeProductUnavailable + productUnavailable;
		
		}
		
		// USER HAS VIEWED FULL RANGE MOVED TO ANOTHER PAGE AND CLICKED BACK TO MORTGAGE FINDER - IF YOU REMOVE THIS THE QUERYSTRING WORKS
		else if (isNaN(productCheckSuccess) && pageViewHashValue == "#full-product-range") {

			resetForm();			
			fullRangeProductUnavailable = fullRangeProductUnavailable + productEstimatedMonthlyRepaymentUnavailable;
		
		}		
		
		// ANY OTHER POSSIBILITY
		else {
			//alert(productCheckSuccess);
			// DO NOT DISPLAY PRODUCT		
			//alert("7 - " + mortCode);
		}
		
	}
	
	if (pageViewHashValue == "#full-product-range") {
		$('.fullRangeTitle').text('Our full range of mortgage products');
		$(fullRangeIntroCopy + rangeTableHeader + fullRangeProduct + fullRangeProductUnavailable + rangeTableFooter).appendTo('#fullRangeData');	
	}
	else if (pageViewHashValue == "#offset-range") {
		$('.fullRangeTitle').text('Our full range of Offset Accounts');
		fullRangeIntroCopy = '<p>This is our full range of Offset mortgage products. To view the mortgage products that may be suitable for you and find out what your Estimated Monthly Repayment could be, please complete <a class="modifyFormButton" href="#" title="mortgage finder"><strong>mortgage finder</strong></a> above.</p>';
		$(fullRangeIntroCopy + rangeTableHeader + fullRangeProduct + fullRangeProductUnavailable + rangeTableFooter).appendTo('#typeRangeData');
	}
	else if (pageViewHashValue == "#fixed-range") {
		$('.fullRangeTitle').text('Our full range of Fixed rate mortgage products');		
		fullRangeIntroCopy = '<p>This is our full range of Fixed rate mortgage products. To view the mortgage products that may be suitable for you and find out what your Estimated Monthly Repayment could be, please complete <a class="modifyFormButton" href="#" title="mortgage finder"><strong>mortgage finder</strong></a> above.</p>';
		$(fullRangeIntroCopy + rangeTableHeader + fullRangeProduct + fullRangeProductUnavailable + rangeTableFooter).appendTo('#typeRangeData');
	}
	else if (pageViewHashValue == "#tracker-range") {
		$('.fullRangeTitle').text('Our full range of Bank of England Tracker mortgage products');
		fullRangeIntroCopy = '<p>This is our full range of Bank of England Tracker mortgage products. To view the mortgage products that may be suitable for you and find out what your Estimated Monthly Repayment could be, please complete <a class="modifyFormButton" href="#" title="mortgage finder"><strong>mortgage finder</strong></a> above.</p>';
		$(fullRangeIntroCopy + rangeTableHeader + fullRangeProduct + fullRangeProductUnavailable + rangeTableFooter).appendTo('#typeRangeData');
	}
	else if (pageViewHashValue == "#tracker-to-fixed-range") {
		$('.fullRangeTitle').text('Our full range of Tracker to Fixed rate mortgage products');
		fullRangeIntroCopy = '<p>This is our full range of Tracker to Fixed rate mortgage products. To view the mortgage products that may be suitable for you and find out what your Estimated Monthly Repayment could be, please complete <a class="modifyFormButton" href="#" title="mortgage finder"><strong>mortgage finder</strong></a> above.</p>';
		$(fullRangeIntroCopy + rangeTableHeader + fullRangeProduct + fullRangeProductUnavailable + rangeTableFooter).appendTo('#typeRangeData');
	}
	
	Cufon.replace('#centerColumn h2');
	
}
















// LIMIT COMPARISON PRODUCTS TO 3 CHECKBOX SELECTIONS
$(function(){
		   
	$(".accountCompareCheckbox").live("click",function() {		
													   
		checkedProduct = $("input[name='account']:checked");
		
		//alert(checkedProduct.getCheckboxVal());
													   
		checkedProductCount = checkedProduct.length;
		
		if (checkedProductCount > 3) {
			
			alert("Sorry, but you can only compare 3 products at a time");
			
			$(this).attr('checked', false);
			
		}
		
	});

});

jQuery.fn.getCheckboxVal = function(){ 
    var vals = []; 
	var checkVal = 0;
    this.each(function(){ 
        vals[checkVal++] = jQuery(this).val(); 
    }); 
    return vals;
}


function compareProducts(compareMethod) {
	
	// CARRY THE ESTIMATED MONTHLY REPAYMENT VALUE FROM THE PRODUCT VIEW TO THE COMPARE VIEW
	// set the ID for each product table so there isn't duplication of the same id across multiple tables
	var compareTableSelector = '';	
	if (compareMethod == "searchRange") {
		compareTableSelector = "#searchProductsTable ";
	}	
	else if (compareMethod == "offsetRange") {
		compareTableSelector = "#offsetProductsTable ";
	}
	else if (compareMethod == "fixedRange") {
		compareTableSelector = "#fixedProductsTable ";
	}
	else if (compareMethod == "trackerRange") {
		compareTableSelector = "#trackerProductsTable ";
	}
	else if (compareMethod == "trackerToFixedRange") {
		compareTableSelector = "#trackerToFixedProductsTable ";
	}	
	else {
		compareTableSelector = "#allProductsTable ";
	}
	
	// empty any previous comparison
	$('#compareData').empty();
	
	// CHECK TO SEE WHICH PRODUCTS HAVE BEEN CHECKED FOR COMPARISON
	var selectedProduct = $("input[name='account']:checked").getCheckboxVal();
	//alert(selectedProduct);
	
	// FAIL - NO PRODUCTS HAVE BEEN SELECTED or ONLY ONE PRODUCT HAS BEEN SELECTED
	if (selectedProduct.length <= 1) {
	
		alert("Please select at least two products to compare");
		
	}
	
	// SUCCESS - PRESENT SELECTED PRODUCTS
	else {
		
		var productCompareHeader = '<div class="compareIntroCopy">You have selected to compare <strong>' + selectedProduct.length + ' products</strong> from the Chelsea mortgage range.</div>' +
			'<div class="returntoResultsContainer">' +
				'<a href="javascript:history.go(-1)" title="Change the products you\'re currently comparing"><img alt="Change the products you\'re currently comparing" src="/img/buttons/button-mortgage-product-change-comparison.gif"></a>' +
			'</div>' +
			'<div class="clear"></div>' +
			'<p class="printonly">This is the Chelsea Building Society Mortgage Finder.</p>' +
            '<h2 class="printonly">These are the products that you have chosen to compare:</h2>' +
			'<div class="compareContainer productCompareHeaders">' +
			'<table class="tableborderzero" width="100%" cellpadding="0" cellspacing="0" border="0">' +
				'<tbody>' +
					'<tr>' +
						'<td><div class="prodNameRow"><p>Product Name:</p></div></td>' +
					'</tr>' +
					'<tr>' +
						'<td><div class="estimatedMonthlyRepaymentRow"><p>Estimated Monthly Repayment:</p></div></td>' +
					'</tr>' +
					'<tr>' +
						'<td><div class="availableForRow"><p>Available For:</p></div></td>' +
					'</tr>' +
					'<tr>' +
						'<td><div class="interestRateRow"><p>Interest Rate:</p></div></td>' +
					'</tr>' +
					'<tr>' +
						'<td><div class="costForComparisonRow"><p>The overall cost for comparison is:</p></div></td>' +
					'</tr>' +						
					'<tr>' +
						'<td><div class="equivSavingsRateRow"><p>Equivalent savings&nbsp;rate:</p></div></td>' +
					'</tr>' +
					'<tr>' +
						'<td><div class="minLoanRow"><p>Min. loan amount:</p></div></td>' +
					'</tr>' +
					'<tr>' +
						'<td><div class="maxLTVRow"><p>Max. Loan to Value:</p></div></td>' +
					'</tr>' +
					'<tr>' +
						'<td><div class="feeAssistanceRow"><p>Fee assistance:</p></div></td>' +
					'</tr>' +					
					'<tr>' +
						'<td><div class="additionalFeaturesRow"><p>Additional Features:</p></div></td>' +
					'</tr>' +
					'<tr>' +
						'<td><div class="productFeeRow"><p>Product fee:</p></div></td>' +
					'</tr>' +		
					'<tr>' +
						'<td><div class="higherLendingChargeRow"><p>Higher lending charge:</p></div></td>' +
					'</tr>' +
					'<tr>' +
						'<td><div class="earlyRepaymentChargeRow"><p>Early Repayment Charges:</p></div></td>' +
					'</tr>' +
					'<tr>' +
						'<td><div class="overpaymentAllowanceRow"><p>Overpayment allowance:</p></div></td>' +
					'</tr>' +
					'<tr>' +
						'<td><div class="mortgageFeeRow"><p>Mortgage Fee:</p></div></td>' +
					'</tr>' +
					'<tr>' +
						'<td><div class="howToApplyRow"><p>How to apply:</p></div></td>' +
					'</tr>' +
					'<tr>' +
						'<td class="productApply"><div class="productApplyRow"><p>&nbsp;</p></div></td>' +
					'</tr>' +
				'</tbody>' +
			'</table>' +
			'<div class="tableBottomClear"></div>' +			
		'</div>';
		
		var productCompareFooter = 	'<div class="clear"></div>' +
			'<H2 title="Important information">Important information</H2>' +
			/*'<ul>' +
				'<li>The product details for this mortgage should be read in conjunction with Chelsea Building Society\'s <a class="pdfLink" title="Fix your mortgage with us" href="/documents/mortgages/fix_your_mortgage_with_us.pdf" target="_blank">Fix your mortgage with us</a> leaflet.</li>' +
				'<li>We reserve the right to charge you interest at Chelsea Building Society\'s Standard Variable Rate if your mortgage falls two or more months into arrears.</li>' +
				'<li>If we agree to you letting the property, we will increase the interest rate we charge on your mortgage account by 1% throughout the letting period.</li>' +
				'<li>For existing Chelsea Building Society borrowers these products are only available when they are moving home.</li>' +
				'<li>The maximum loan may be restricted by product specifications or lending policy.</li>' +
				'<li>Applicants must be aged 18 years or over.</li>' +
			'</ul>' +*/
			'<a id="scrolled" name="legal"></a>' +
			'<h3 title="Legal fees">Legal fees</h3>' +
			'<p>Some of our mortgage products offer no legal fees for standard remortgage work. This means you pay <strong>no legal fees for standard legal work</strong>, provided:</p>' +
			'<ul>' +
				'<li>You are moving your mortgage but NOT your home, and</li>' +
				'<li>Your home is in England, Scotland or Wales, and</li>' +
				'<li>Chelsea Building Society solicitors are used to carry out only the standard work required to transfer your mortgage.</li>' +
			'</ul>' +
			'<p>However, some administration fees may be your responsibility.</p>' +
			'<p>In all other cases, for example if you are moving home, you don\'t currently have a mortgage on your home, your property is located in Northern Ireland or your legal requirements exceed the standard work of just moving your mortgage, you will have to pay your own legal costs.</p>' +			
			'<p>If the transfer of your mortgage does not proceed, you will be liable for any costs&nbsp;incurred.</p>';	
		
		var productCompareDetail = '';
		var compareEstimatedMonthlyRepayment = '';
		
		for (var i = 0; i<selectedProduct.length; i++) {
			
			var compareName = mortgageProducts[selectedProduct[i]].getAttribute("name");
			// FIND THE CORRESPONDING ESTIMATED MONTHLY REPAYMENT FOR EACH OF THE SELECTED COMPARISON VIEW PRODUCTS
			var compareEstimatedMonthlyRepayment = $(compareTableSelector + 'input[value="' + selectedProduct[i] + '"]').closest('tr').find("td.estimatedMonthlyRepaymentValue").text();	
			//console.log(compareEstimatedMonthlyRepayment);			
			
			var compareAvailableFor = mortgageProducts[selectedProduct[i]].getAttribute("availableFor");
				
			var compareCustomerMovingHome = mortgageProducts[selectedProduct[i]].getAttribute("movingHome");
			var compareCustomerRemortgaging = mortgageProducts[selectedProduct[i]].getAttribute("remortgaging");				
			var compareCustomerFirstTimeBuyer = mortgageProducts[selectedProduct[i]].getAttribute("firstTimeBuyer");		
			var compareAvailableFor = "";
			
			if (compareCustomerMovingHome == "Y") {
				compareAvailableFor = "Moving Home";
			}
			if (compareCustomerRemortgaging == "Y") {
				if (compareAvailableFor == "") {
					compareAvailableFor = compareAvailableFor + "Remortgaging from other lender";
				}
				else {
					compareAvailableFor = compareAvailableFor + "<br />Remortgaging from other lender";
				}				
			}
			if (compareCustomerFirstTimeBuyer == "Y") {
				if (compareAvailableFor == "") {
					compareAvailableFor = compareAvailableFor + "First Time Buyers";
				}
				else {
					compareAvailableFor = compareAvailableFor + "<br /> First Time Buyers";
				}	
			}
			
			var compareMortgageType = mortgageProducts[selectedProduct[i]].getAttribute("mortgageType");
			
			var comparePageURL = mortgageProducts[selectedProduct[i]].getAttribute("pageURL");
			
			var comparePageFolder = "";
			switch (compareMortgageType) {
				case "fixed":
					comparePageFolder = "fixed";
					break;
				case "fixedoffset":
					comparePageFolder = "fixed-offset";
					break;
				case "tracker":
					comparePageFolder = "tracker";
					break;
				case "trackeroffset":
					comparePageFolder = "tracker-offset";
					break;
				case "mixed":
					comparePageFolder = "tracker-to-fixed";
					break;
				case "mixedoffset":
					comparePageFolder = "tracker-to-fixed-offset";
					break;			
			}
			
			var compareInterestRate = mortgageProducts[selectedProduct[i]].getAttribute("interestRate");
			var compareInterestRate2 = mortgageProducts[selectedProduct[i]].getAttribute("interestRate2");
			var compareCollar = mortgageProducts[selectedProduct[i]].getAttribute("collar");
			var compareTerm = mortgageProducts[selectedProduct[i]].getAttribute("term");
			var compareTerm2 = mortgageProducts[selectedProduct[i]].getAttribute("term2");
			var compareInterestRateDetail = "";
			
			if (compareMortgageType == "fixed" || compareMortgageType == "fixedoffset") {	
				compareInterestRateDetail = compareInterestRate +" fixed until " + compareTerm + " then Chelsea Building Society's Standard Variable Rate, currently " + chelseaSVR + " variable, for the remaining term of your mortgage";
			}
			else if (compareMortgageType == "tracker" || compareMortgageType == "trackeroffset") {				
				compareInterestRateDetail = compareInterestRate + " variable (BoE Base Rate + " + compareCollar + "), collared at " + compareInterestRate + " until " + compareTerm + " then Chelsea Building Society's Standard Variable Rate, currently " + chelseaSVR + " variable, for the remaining term of your mortgage";
			}
			else if (compareMortgageType == "mixed" || compareMortgageType == "mixedoffset") {				
				compareInterestRateDetail = compareInterestRate + " variable (BoE Base Rate + " + compareCollar + "), collared at " + compareInterestRate + " until " + compareTerm + ", then " + compareInterestRate2 + " fixed until " + compareTerm2 + ", then Chelsea Building Society's Standard Variable Rate, currently " + chelseaSVR + " variable, for the remaining term of your mortgage";
			}
			
			var compareTaxBasicRate = mortgageProducts[selectedProduct[i]].getAttribute("taxBasicRate");
			var compareTaxHigherRate = mortgageProducts[selectedProduct[i]].getAttribute("taxHigherRate");				
			var compareTaxAdditionalRate = mortgageProducts[selectedProduct[i]].getAttribute("taxAdditionalRate");	
			var compareTaxBasicRate2 = mortgageProducts[selectedProduct[i]].getAttribute("taxBasicRate2");
			var compareTaxHigherRate2 = mortgageProducts[selectedProduct[i]].getAttribute("taxHigherRate2");				
			var compareTaxAdditionalRate2 = mortgageProducts[selectedProduct[i]].getAttribute("taxAdditionalRate2");	
			var compareEquivSavingsRate = "";
			
			if (compareMortgageType == "fixedoffset" || compareMortgageType == "trackeroffset") {
				compareEquivSavingsRate = compareTaxBasicRate + " basic rate taxpayer<br />" +
										  compareTaxHigherRate + " higher rate taxpayer<br />" +
										  compareTaxAdditionalRate + " additional rate taxpayer";
			}
			else if (compareMortgageType == "mixedoffset") {
				compareEquivSavingsRate = "<u>Tracker rate period:</u><br />" +
										  compareTaxBasicRate + " basic rate taxpayer<br />" +
										  compareTaxHigherRate + " higher rate taxpayer<br />" +
										  compareTaxAdditionalRate + " additional rate taxpayer<br /><br />" +
										  "<u>Fixed rate period:</u><br />" +
										  compareTaxBasicRate2 + " basic rate taxpayer<br />" +
										  compareTaxHigherRate2 + " higher rate taxpayer<br />" +
										  compareTaxAdditionalRate2 + " additional rate taxpayer";
			}
			else {
				compareEquivSavingsRate = "n/a";
			}	
						
			var compareCostForComparison = mortgageProducts[selectedProduct[i]].getAttribute("apr");
			
			//var compareLegalFees = mortgageProducts[selectedProduct[i]].getAttribute("legalFees");
			var compareMinLoan = mortgageProducts[selectedProduct[i]].getAttribute("minLoan");
			var compareMaxLTV = mortgageProducts[selectedProduct[i]].getAttribute("maxLTV");
			
			
			
			var compareFreeValuation = mortgageProducts[selectedProduct[i]].getAttribute("freeValuation");
			var compareFreeLegals = mortgageProducts[selectedProduct[i]].getAttribute("freeLegals");			
			var compareFeeAssistance = "";
			if (compareFreeValuation  == "Y") {
				compareFeeAssistance = "Free standard valuation";
			}
			if (compareFreeLegals  == "Y") {
				if (compareFeeAssistance == "") {
					compareFeeAssistance = "<a id='inPageScroll' title='No legal fees for standard remortgage work' onclick='return false;' href='#legal'>No legal fees for standard remortgage work</a>, payable by customer for house purchase.";
				}
				else {
					compareFeeAssistance = compareFeeAssistance + "<br /><a id='inPageScroll' title='No legal fees for standard remortgage work' onclick='return false;' href='#legal'>No legal fees for standard remortgage work</a>, payable by customer for house purchase.";
				}
				
			}
			if (compareFreeValuation  != "Y" && compareFreeLegals  != "Y") {
				compareFeeAssistance = "None";
			}
			
			var compareAdditionalFeatures = mortgageProducts[selectedProduct[i]].getAttribute("additionalFeatures");
			if (compareAdditionalFeatures == "") {
				compareAdditionalFeatures = "n/a";	
			}
			
			var compareBookingFee = mortgageProducts[selectedProduct[i]].getAttribute("bookingFee");		
			var compareCompletionFee = mortgageProducts[selectedProduct[i]].getAttribute("completionFee");
			compareProductFeeDetail = "";			
			if (compareBookingFee == "None" || compareBookingFee == "none") {
				compareProductFeeDetail = "There are no product fees for this product.";
			}
			else {					
				var compareProductFee = (parseInt(compareBookingFee) + parseInt(compareCompletionFee));
			
				var productFeeBreakdown = "";			
				if (compareBookingFee == "0" || compareBookingFee == "" || compareBookingFee == "none") {
					productFeeBreakdown = "(£" + addCommas(compareCompletionFee) + " is added to your mortgage on completion).";				
				}
				else if (compareCompletionFee == "0" || compareCompletionFee == "" || compareCompletionFee == "none") {				
					productFeeBreakdown = "(payable on application and is non refundable).";		
				}	
				else {
					productFeeBreakdown = "(£" + addCommas(compareBookingFee) + " of this fee is payable on application and is non refundable, £" + addCommas(compareCompletionFee) + " is added to your mortgage on completion).";
				}
				compareProductFeeDetail = "£" + addCommas(compareProductFee) + " <br />" + productFeeBreakdown;				
			}
			
			var compareHigherLendingCharge = mortgageProducts[selectedProduct[i]].getAttribute("higherLendingCharge");
			//var compareValuationFee = mortgageProducts[selectedProduct[i]].getAttribute("valuationFee");
			var compareEarlyRepaymentCharge = mortgageProducts[selectedProduct[i]].getAttribute("erc");
			var compareOverpaymentAllowance = "";
			if (compareMortgageType == "fixedoffset" || compareMortgageType == "trackeroffset" || compareMortgageType == "mixedoffset") {
				compareOverpaymentAllowance = "Unlimited overpayments (monthly or lump sum) are allowed. However, if the product is repaid in full or, transferred in full or part, an Early Repayment Charge will be payable as described above.";
			}
			else {
				compareOverpaymentAllowance = "Overpayments (monthly or lump sum) up to a total of 10% of the outstanding loan per year are allowed without charge. Any amount repaid over the 10% limit will incur an Early Repayment Charge, of the percentage specified above, on the excess amount.";
			}
			
			var compareMortgageFee = "£90 (payable on redemption of your mortgage)";
			var compareApplyOnline = mortgageProducts[selectedProduct[i]].getAttribute("applyOnline");
			var compareBranchOnline = mortgageProducts[selectedProduct[i]].getAttribute("applyBranch");
			var comparePhoneOnline = mortgageProducts[selectedProduct[i]].getAttribute("applyPhone");
			
			howToApplyCopy = "";
			availableApplyMethods = "";
			if(compareApplyOnline == "Y") {
				howToApplyCopy = howToApplyCopy + '- Online <br />';				
				availableApplyMethods = availableApplyMethods + "online";				
			}
			if(compareBranchOnline == "Y") {
				howToApplyCopy = howToApplyCopy + '- in branch <br />';
				availableApplyMethods = availableApplyMethods + "branch";
			}
			if(comparePhoneOnline == "Y") {
				howToApplyCopy = howToApplyCopy + '- by Telephone';
				availableApplyMethods = availableApplyMethods + "telephone";
			}
			
			productCompareDetail = productCompareDetail + '<div class="compareContainer productCompareContainer">' +
				'<table class="tableborderzero" width="100%" cellpadding="0" cellspacing="0" border="0">' +
					'<tbody>' +
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="prodNameRow"><p>Product Name:</p></div></td>' +
							'<th><a title="Find out more about this ' + compareName + ' mortgage" href="products/' + comparePageFolder + '/' + comparePageURL + '" class="productSelectionLink"><div class="prodNameRow"><p><strong>' + compareName + '</p></strong></div></a></th>' +
						'</tr>' +
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="availableForRow"><p>Estimated Monthly Repayment:</p></div></td>' +
							'<td><div class="estimatedMonthlyRepaymentRow"><p><strong>' + compareEstimatedMonthlyRepayment + '</strong></p></div></td>' +
						'</tr>' +
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="availableForRow"><p>Available For:</p></div></td>' +
							'<td><div class="availableForRow"><p>' + compareAvailableFor + '</p></div></td>' +
						'</tr>' +	
						'<tr>' +			
							'<td class="print_compareTableHeader"><div class="interestRateRow"><p>Interest Rate:</p></div></td>' +
							'<td><div class="interestRateRow"><p>' + compareInterestRateDetail + '</p></div></td>' +
						'</tr>' +
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="costForComparisonRow"><p>The overall cost for comparison is:</p></div></td>' +
							'<td><div class="costForComparisonRow"><p>' + compareCostForComparison + ' APR</p></div></td>' +
						'</tr>' +	
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="equivSavingsRateRow"><p>Equivalent savings&nbsp;rate:</p></div></td>' +
							'<td><div class="equivSavingsRateRow"><p>' + compareEquivSavingsRate + '</p></div></td>' +
						'</tr>' +
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="minLoanRow"><p>Min. loan amount:</p></div></td>' +
							'<td><div class="minLoanRow"><p>£' + compareMinLoan + '</p></div></td>' +
						'</tr>' +
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="maxLTVRow"><p>Max. Loan to Value:</p></div></td>' +
							'<td><div class="maxLTVRow"><p>' + compareMaxLTV + '</p></div></td>' +
						'</tr>' +
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="feeAssistanceRow"><p>Fee assistance:</p></div></td>' +
							'<td><div class="feeAssistanceRow"><p>' + compareFeeAssistance + '</p></div></td>' +
						'</tr>' +						
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="additionalFeaturesRow"><p>Additional Features:</p></div></td>' +
							'<td><div class="additionalFeaturesRow"><p>' + compareAdditionalFeatures + '</p></div></td>' +
						'</tr>' +
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="productFeeRow"><p>Product fee:</p></div></td>' +
							'<td><div class="productFeeRow"><p>' + compareProductFeeDetail + '</p></div></td>' +
						'</tr>' +
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="higherLendingChargeRow"><p>Higher lending charge:</p></div></td>' +
							'<td><div class="higherLendingChargeRow"><p>' + compareHigherLendingCharge + '</p></div></td>' +
						'</tr>' +
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="earlyRepaymentChargeRow"><p>Early Repayment Charges:</p></div></td>' +
							'<td><div class="earlyRepaymentChargeRow"><p>' + compareEarlyRepaymentCharge + '</p></div></td>' +
						'</tr>' +
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="overpaymentAllowanceRow"><p>Overpayment allowance:</p></div></td>' +
							'<td><div class="overpaymentAllowanceRow"><p>' + compareOverpaymentAllowance + '</p></div></td>' +
						'</tr>' +						
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="mortgageFeeRow"><p>Mortgage Fee:</p></div></td>' +
							'<td><div class="mortgageFeeRow"><p>' + compareMortgageFee + '</p></div></td>' +
						'</tr>' +
						'<tr>' +
							'<td class="print_compareTableHeader"><div class="howToApplyRow"><p>How to apply:</p></div></td>' +
							'<td><div class="howToApplyRow"><p>' + howToApplyCopy + '</p></div></td>' +
						'</tr>' +
						'<tr class="productApplyRowContainer">' +
							'<td class="print_compareTableHeader"><div class="productApplyRow"><p>&nbsp;</p></div></td>' +
							'<td class="productApply"><div class="productApplyRow"><p><a onclick="productApplyClick(\'' + comparePageURL + '\',\'' + availableApplyMethods + '\'); return false;" href="#" title="Apply NOW for this product"><img src="/img/buttons/button-mortgage-product-compare-applynow.gif" style="display:block !important" alt="Apply NOW for this product" /></a></p></div></td>' +
						'</tr>' +
					'</tbody>' +
				'</table>' +
				'<div class="tableBottomClear"></div>' + 
			'</div>';
				
		}
		
		// LESS THAN 3 PRODUCTS HAVE BEEN SELECTED FOR COMPARISON, SHOW BLANK HOLDING CONTAINER IN THIRD PRODUCT POSITION TO FILL WHITE SPACE
		if (selectedProduct.length < 3) {
			
			productCompareDetail = productCompareDetail + '<div class="compareContainer productCompareContainer">&nbsp;</div>';
			
		}
		
		$('#compareData').hide();	
		setTimeout('$(\'.searchInProgressAnimationContainer\').show();',50);
		setTimeout('searchInProgressAnimation("#compareData")',loadingAnimationTimeoutLength);
		
		window.location.hash = "#product-comparison";
		
		$(productCompareHeader + productCompareDetail + productCompareFooter).appendTo('#compareData');
		
		Cufon.replace('#centerColumn h2, #centerColumn h3');
		
	}
	
}


function setHeights() {
	
	$(".prodNameRow").equalHeights();
	$(".estimatedMonthlyRepaymentRow").equalHeights();	
	$(".availableForRow").equalHeights();
	$(".interestRateRow").equalHeights();
	$(".costForComparisonRow").equalHeights();	
	$(".equivSavingsRateRow").equalHeights();	
	//$(".legalFeesRow").equalHeights();
	$(".minLoanRow").equalHeights();
	$(".maxLTVRow").equalHeights();
	$(".feeAssistanceRow").equalHeights();	
	$(".additionalFeaturesRow").equalHeights();
	$(".productFeeRow").equalHeights();
	$(".higherLendingChargeRow").equalHeights();
	//$(".valuationFeeRow").equalHeights();
	$(".earlyRepaymentChargeRow").equalHeights();
	$(".overpaymentAllowanceRow").equalHeights();	
	$(".mortgageFeeRow").equalHeights();	
	$(".howToApplyRow").equalHeights();
	$(".productApplyRow").equalHeights();
	$(".compareContainer").equalHeights();
	
}

// WHEN A USER CLICKS TO APPLY ONLINE, THE MORTGAGE APPLICATION FORM WILL OPEN IN NEW WINDOW. PARENT WINDOW WILL REDIRECT TO SELECTED PRODUCT PAGE
function productApplyClick(comparePageURL, availableApplyMethods) {
	
	mortgageFinderApplyLinkTracker(comparePageURL, availableApplyMethods);
	
}








function resetForm() {

	//$('#mortgageSearchForm')[0].reset();
	
	$('.formColumnMiddle').show();
	$('#mortgageTypeContainer').show();
	
	// reset customerType dropdown list to default state
	$('#customerTypeSelector').empty();
	$(customerTypeDropdown).appendTo('#customerTypeSelector');	
	
	// reset buyerType dropdown list to default state
	$('#buyerTypeSelector').empty();
	$(newCustomerBuyerType).appendTo('#buyerTypeSelector');
	
	// reset buyerType dropdown list to default state
	$('#mortgageTypeSelector').empty();
	$(newMortgageType).appendTo('#mortgageTypeSelector');
	
	$('#propertyValue').val('');
	$('#depositValue').val('');
	$('#mortgageTerm').val('');
	
	$('#depositLabel').text('Deposit:');
	
	if ($('#depositLabelContainer').hasClass('twoLineLabel')) {
		$('#depositLabelContainer').removeClass('twoLineLabel');
	}
		
}






// TRACKING
function mortgageFinderStateTracker(pageViewHashValue) {
  // BEFORE SENDING THE HASH VALUE TO OMNITURE, RUN CHECK TO SEE WHAT THE HASH VALUE IS
  // THIS IS A CLEANUP TO ENSURE THAT IF URL HAS THE SOLE VALUE OF "#" THEN CHANGE THE VALUE SENT TO OMNITURE TO BLANK SO AS NOT TO CREATE A NEW ENTRY FOR "#"
  if (pageViewHashValue == "#" || pageViewHashValue == "") {
	  pageViewHashValue = "";
	  var s=s_gi('ybschelsea');
	  s.linkTrackVars='prop3';
	  s.linkTrackEvents='event1';
	  s.prop3 = s.pageName + pageViewHashValue;
	  //console.log(s.prop3);	
	  //alert(s.prop3);
	  s.tl(this,'o','Hashed Link');	
  }
  else {
	  var s=s_gi('ybschelsea');
	  s.linkTrackVars='prop3';
	  s.linkTrackEvents='event1';
	  s.prop3 = s.pageName + pageViewHashValue;
	  //console.log(s.prop3);	
	  //alert(s.prop3);
	  s.tl(this,'o','Hashed Link');	  
  }
};

// USER HAS CLICKED APPLY NOW LINK - HIT RECORDED
function mortgageFinderApplyLinkTracker(productApplyClicked, availableApplyMethods) {
	
	productApplyClicked = productApplyClicked + "_apply_finder";
	
	var s=s_gi('ybschelsea');
	s.linkTrackVars='prop10';
	s.linkTrackEvents='event1';
	s.prop10 = productApplyClicked;
	//console.log(s.prop10);	
	//alert(s.prop10);
	s.tl(this,'o','Hashed Link');
	
	//window.location = "how-to-apply.html?apply=" + availableApplyMethods;
	
	applyRedirectDelay = 'window.location = "how-to-apply.html?apply=' + availableApplyMethods + '"';
	setTimeout(applyRedirectDelay, 500);
	
};
// USER HAS CLICKED DETAILS OR PRODUCT NAME LINK FOR MORE INFORMATION - HIT RECORDED
function mortgageFinderDetailsLinkTracker(productPageURL, productTrack) {
	
	productDetailsClicked = productTrack + "_details_finder";
	
	var s=s_gi('ybschelsea');
	s.linkTrackVars='prop10';
	s.linkTrackEvents='event1';
	s.prop10 = productDetailsClicked;
	//console.log(s.prop10);	
	//alert(s.prop10);
	s.tl(this,'o','Hashed Link');
	
	//window.location = "products/" + productDetailsClicked;
	
	detailsRedirectDelay = 'window.location = "' + productPageURL + '"';
	setTimeout(detailsRedirectDelay, 500);
	
};



