var warningDisplayed = false;
var validationFocusInfo = { lastScrolled: null, ignoreScrollWithin: 5000 };	// ignoreScrollWithin: milliseconds value.

  /*** GLOBAL VARIABLES ****/
    var loanstocompareTimeOutMonitor = 0;
    var loanstocompareTimeOutInterval = 40000;
    var showLoantoCompare = true;   
    var pageID = 0;
    
	/*** HTML CONTROLS ***/   
    var nonhomeownerPanel = $$(".msfg-nonhomeownerpanel")[0];
    var loanstocompare = $$(".msfg-loanstocompare-span")[0];
    var totalloansavailable = $$(".msfg-totalloansavailable")[0];	 
    var loanstocomparePanel = $$(".msfg-loanstocomparepanel")[0];	
    var totalloansavailable = $$(".msfg-totalloansavailable")[0];
    var oSpanMessage = $$(".msfg-spanMessage")[0];
    var ddlLoanPeriod = $$(".msfg-ddlLoanPeriod")[0];
    var ddlResidentialStatus = $$(".msfg-ddlResidentialStatus")[0];
    var hidProductType = $$(".msfg-hidPageId")[0];
    var txtLoanAmount = $$(".msfg-loanamount")[0];

/* Validation highlighting. */

function MsfgProductsLoans$ScrollToShow(element, browserVisibleRect, padding, focusFirstChild) {
	// If necessary, scrolls the user's browser to show the specified element (inclusive of the provided padding).
	var elementRect = MsfgProductsLoans$GetElementRect(element);
	if (elementRect.bottom() > browserVisibleRect.bottom()) {
		// Field, or part thereof, is below the current view-port.
		window.scrollBy(0, (elementRect.bottom() - browserVisibleRect.bottom()) + padding);
	} else if (elementRect.top < browserVisibleRect.top) {
		// Field is above the current view-port.
		window.scrollBy(0, (browserVisibleRect.top - elementRect.top) + padding);
	}
	
	if (focusFirstChild) {
		MsfgProductsLoans$FocusOnFirstAvailableChild(element);
	}
}

function MsfgProductsLoans$FocusOnFirstAvailableChild(container) {
	// Places cursor focus on the first (nested) child of the container that can accept focus.
	// Requires prototype v1.5 at a minimum.
	//TODO: Add exception management.
	var descendants = container.descendants();
	var focused = false;
	var focusableTags = ["input", "select", "textarea"];
	
	for (var i = 0, max = descendants.length; i < max && !focused; i++) {
		var node = descendants[i];
		if (node.type != "hidden" && !node.disabled && focusableTags.include(node.tagName.toLowerCase())) {
			try {
				node.focus();
				break;
			} catch (ex) {}
		}
	}
}

function MsfgProductsLoans$ValidationHighlightActual() {
	// Used to scroll the user to a failed validation field, when highlighted with a validation highlighter,
	// should they have a low monitor resolution.
	// This method should be called from a custom validator [unattached to a field] that is placed at the end of the form
	// being validated. This custom validator, if used only to focus on failed validation fields, method should not fail the
	// page validation [i.e. args.isvalid should be set to true].
	// This method will attempt to check bubble ("bubbleright" validation highlighter option) validation before falling back 
	// on highlighted fields [options provided by the WF].
	
	// This method is should be removed once support for "jump to validation" is added into the WF.
	
	// Note: the viewport/scrolling checks are dependent on prototype.
	
	// Skip the scroll if within n seconds from the last scroll.
	if (validationFocusInfo.lastScrolled
		&& (new Date().getTime() - validationFocusInfo.lastScrolled.getTime()) 
			< validationFocusInfo.ignoreScrollWithin) {
		return;
	}
	
	try {
		var scrollMargin = 15;
		var bubbleDiv = $get("floatvalidationtest");
		var browserViewPortRect = MsfgProductsLoans$GetBrowserVisibleRect();
		
		var highlightDiv = bubbleDiv;
		var getFirstAncestor = function(childElement) {
			return $(childElement).ancestors()[0];
		}
		
		if (bubbleDiv != null) {
			// Bubble based validation - only one bubble will be displayed at a time.
			highlightDiv = getFirstAncestor(bubbleDiv);
		} else {
			// Either the page is valid, or we're using validation highlighting. All highlighter div containers
			// will have an id suffix of "_ErrorMessageContainer".
			var willHighlight = false;
			var pageDivs = document.getElementsByTagName("div");
			if (pageDivs && pageDivs.length > 0) {
				for (var i = 0, max = pageDivs.length; i < max && !willHighlight; i++) {
					var pageDiv = pageDivs[i];
					if (pageDiv.id && pageDiv.id.toLowerCase().indexOf("_errormessagecontainer") > 0) {
						// We need to ensure the parent container [data entry container] is visible. If any sub-control
						// can receive focus, we'll set it. Supported focusable controls: input[type="text"], select.
						highlightDiv = getFirstAncestor(pageDiv);
						willHighlight = true;
					}
				}
			}
		}
		
		if (highlightDiv != null) {
			MsfgProductsLoans$ScrollToShow(highlightDiv, browserViewPortRect, scrollMargin, true);
			validationFocusInfo.lastScrolled = new Date();
		}
	} catch (ex) {} // Ignore exceptions: this is a non-critical function.
}

function MsfgProductsLoans$ValidationHighlight(sender, args) {
	// Placeholder method: this will be called by the validation routines. Execution will be delayed
	// to allow the validator highlighter to complete its element creation job so we can correctly position elements.
	window.setTimeout("MsfgProductsLoans$ValidationHighlightActual()", 600);
	args.isvalid = true;
}

function MsfgProductsLoans$GetElementRect(element) {
	// Creates an object containing the rectangle coordinates for the specified element.
	// Dependent on the prototype and MSFG common.js libraries.
	// Members on return: left, top, width, height, right(), bottom(). All values integers.
	var elementPosition = truePosition(element);
	var elementDimensions = $(element).getDimensions();
	
	var rect =
		{
			left: elementPosition[0],
			top: elementPosition[1],
			width: elementDimensions.width,
			height: elementDimensions.height,
			right: function() {
				return this.left + this.width;
			},
			bottom: function() {
				return this.top + this.height;
			}
		};
	return rect;
}

function MsfgProductsLoans$GetBrowserVisibleRect() {
	// Calculates the visible viewport rectangular coordinates.
	// Members on return: left, top, width, height, right(), bottom(). All values integers.
	var browserViewport = MsfgProductsLoans$GetBrowserViewport();
	var bodyScroll = MsfgProductsLoans$GetScrollOffset();
	
	var rect =
		{
			left: bodyScroll.left, 
			top: bodyScroll.top,
			width: browserViewport.width, 
			height: browserViewport.height,
			bottom: function() {
				return this.top + this.height;
			},
			right: function() {
				return this.left + this.width;
			}
		};
	return rect;
}

function MsfgProductsLoans$GetScrollOffset() {
	// Calculates the scroll offset for the browser.
	// Members on return: left: int, top: int, isEmpty: bool.
	// isEmpty will be set to true if the browser is unsupported.
	var left = 0, top = 0;
	var empty = false;
	
	if (self.pageYOffset) {
		// All except IE.
		left = self.pageXOffset;
		top = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {
		// IE 6 strict.
		left = document.documentElement.scrollLeft;
		top = document.documentElement.scrollTop;
	} else if (document.body) {
		left = document.body.scrollLeft;
		top = document.body.scrollTop;
	} else {
		empty = true;
	}
	
	return { left: left, top: top, isEmpty: empty };
}

function MsfgProductsLoans$GetBrowserViewport() {
	// Gets the available browser screen real estate.
	// Members on return: width: int, height: int, isEmpty: bool.
	// isEmpty will be set to true if the browser is unsupported.
	var width = 0, height = 0;
	var empty = false;
	
	if (typeof window.innerWidth != "undefined") {
		// Compliant browsers [NS/Mozilla/Opera/IE7]
		width = window.innerWidth;
		height = window.innerHeight;
	} else if (typeof document.documentElement != "undefined"
		&& typeof document.documentElement.clientWidth != "undefined"
		&& typeof document.documentElement.clientWidth != 0) {
		// IE6: standards compliant mode.
		width = document.documentElement.clientWidth;
		height = document.documentElement.clientHeight;
	} else {
		// Older IE.
		var bodyElement = document.getElementsByTagName("body");
		if (bodyElement && bodyElement.length > 0) {
			bodyElement = bodyElement[0];
			width = bodyElement.clientWidth;
			height = bodyElement.clientHeight;
		} else {
			empty = true;
		}
	}
	
	return {width: width, height: height, isEmpty: empty };
}

/* End: validation highlighting. */

function MsfgProductsLoans$suggestPeriodIncrease(sender, args) 
{
	// Need to warn the user that if they select a loan amount of greater than £25,000, a loan duration
	// of greater than 5 years will increase their chances of finding a hit.
	// To do this, we need the client-side field identifiers for the amount text field, and the period dropdown list.
	args.IsValid = true;
	if (typeof sender.loanAmountFieldId == "undefined" || typeof sender.periodFieldId == "undefined" || typeof sender.residentialStatusFieldId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure - delegate validation or warning to the server.
		return;
	}
	var periodField = $(sender.periodFieldId);
	var loanAmountField = $(sender.loanAmountFieldId);
	var residentialStatusField = $(sender.residentialStatusFieldId);
	if (periodField == null || loanAmountField == null || residentialStatusField == null) 
	{
		// The field couldn't be found
		return;
	}
	
	// We won't check for numerical validity on the fields as there should be a validator checking this already.
	var amountEntered = (!isNaN(parseFloat(loanAmountField.value)) ? parseFloat(loanAmountField.value) : 0);
	var selectedDurationMonths = parseInt(periodField.options[periodField.selectedIndex].value);
	var residentialStatus = parseInt(residentialStatusField.options[residentialStatusField.selectedIndex].value);

	if(selectedDurationMonths == 1)
	selectedDurationMonths = 6;
	else
	selectedDurationMonths = (selectedDurationMonths - 1) * 12;
	
	if ((residentialStatus != '2' && residentialStatus != '1') && amountEntered > 25000) 
	{
		// Home ownership must be validated before displaying the message
		return;
	}
	
		if (amountEntered < 50 || amountEntered > 250000) 
	{
		// Suppress the warning - Loan amount is invalid.
		return;
	}
	if (warningDisplayed) 
	{
		// We've already displayed the warning - no need to continue with this check.
		return;
	}
	if (!warningDisplayed && (amountEntered > 25000 && selectedDurationMonths < 60)) 
	{
		warningDisplayed = true;
		args.IsValid = false;
		MsfgProductsLoans$setFocus(sender.controltovalidate);
	}
}

function MsfgProductsLoans$suggestSearchResult(sender, args) 
{
	if (warningDisplayed) 
	{
		// We've already displayed the warning - no need to continue with this check.
		return;
	}

	// Need to warn the user that if they select a loan amount of greater than £25,000, a loan duration
	// of greater than 5 years will increase their chances of finding a hit.
	// To do this, we need the client-side field identifiers for the amount text field, and the period dropdown list.
	if (typeof sender.loanAmountFieldId == "undefined" || typeof sender.periodFieldId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure - delegate validation or warning to the server.
		return;
	}
	
	var periodField = $(sender.periodFieldId);
	var loanAmountField = $(sender.loanAmountFieldId);
	
	if (periodField == null || loanAmountField == null) 
	{
		// The field couldn't be found
		return;
	}
	
	// We won't check for numerical validity on the fields as there should be a validator checking this already.
	var amountEntered = (!isNaN(parseFloat(loanAmountField.value)) ? parseFloat(loanAmountField.value) : 0);
	var selectedDurationMonths = parseInt(periodField.options[periodField.selectedIndex].value);
	
	if(selectedDurationMonths == 1)
		selectedDurationMonths = 6;
	else
		selectedDurationMonths = (selectedDurationMonths - 1) * 12;
	
	if (amountEntered < 50 || amountEntered > 250000) 
	{
		// Suppress the warning - Loan amount is invalid.
		return;
	}
	
	if (!warningDisplayed && (amountEntered > 25000 && selectedDurationMonths < 60)) 
	{
		warningDisplayed = true;
		args.IsValid = false;
		MsfgProductsLoans$setFocus(sender.controltovalidate);
	}
}

function MsfgProductsLoans$checkTelephone(sender, args) 
{
    if (typeof sender.telephoneFieldId == "undefined") 
	{
		return;
	}
	var telephoneField = $(sender.telephoneFieldId);
	if(telephoneField == null)
	{
	    return;
	}
	// Convert into a string and check that we were provided with something
    var telnum = telephoneField.value + " ";
     if (telnum.length == 1)  {
        args.IsValid = false;
        MsfgProductsLoans$setFocus(sender.controltovalidate);
    }
    telnum.length = telnum.length - 1;
  
    // Don't allow country codes to be included (assumes a leading "+")
    var exp = /^(\+)[\s]*(.*)$/;
    if (exp.test(telnum) == true) {
        args.IsValid = false;
        MsfgProductsLoans$setFocus(sender.controltovalidate); 
    }
  
    // Remove spaces from the telephone number to help validation
    while (telnum.indexOf(" ")!= -1)  {
        telnum = telnum.slice (0,telnum.indexOf(" ")) + telnum.slice (telnum.indexOf(" ")+1)
    }
  
    // Remove hyphens from the telephone number to help validation
     while (telnum.indexOf("-")!= -1)  {
        telnum = telnum.slice (0,telnum.indexOf("-")) + telnum.slice (telnum.indexOf("-")+1)
    }  
  
     // Now check that all the characters are digits
    exp = /^[0-9]{10,11}$/;
    if (exp.test(telnum) != true) {
        args.IsValid = false;
        MsfgProductsLoans$setFocus(sender.controltovalidate);
     }
    
     // Now check that the first digit is 0
    exp = /^0[0-9]{9,10}$/;
    if (exp.test(telnum) != true) {
      args.IsValid = false;
      MsfgProductsLoans$setFocus(sender.controltovalidate);
   }
     // Finally check that the telephone number is appropriate.
     exp = (/^(01|02|03|05|070|071|072|073|074|075|07624|077|078|079)[0-9]+$/);
	if (exp.test(telnum) != true) {
        args.IsValid = false;
        MsfgProductsLoans$setFocus(sender.controltovalidate); 
  }
}

//Checks for numeric field
function MsfgProductsLoans$numericValidate(sender, args)  { 
 if (typeof sender.loanAmountFieldId == "undefined") 
	{
		return;
	}
	var loanAmountFieldId = $(sender.loanAmountFieldId);
	if(loanAmountFieldId == null)
	{
	    return;
	}
	// Convert into a string and check that we were provided with something
    var loanAmount = loanAmountFieldId.value
    
    var intCharCode; 
    for (var i = 0; i < loanAmount.length; i++) 
    { 
      intCharCode = loanAmount.charCodeAt(i);         
        if (!((intCharCode >= 48 && intCharCode <= 57)))  
      {
        args.IsValid = false;
    } 
        
       MsfgProductsLoans$setFocus(sender.controltovalidate); 
    } 

} 

var MsfgProductsLoans$STR_PAD_LEFT = 1;
var MsfgProductsLoans$STR_PAD_RIGHT = 2;
var MsfgProductsLoans$STR_PAD_BOTH = 3;

function pad(str, len, pad, dir) {

    if (typeof(len) == "undefined") { var len = 0; }
    if (typeof(pad) == "undefined") { var pad = ' '; }
    if (typeof(dir) == "undefined") { var dir = MsfgProductsLoans$STR_PAD_RIGHT; }

    if (len + 1 >= str.length) {

        switch (dir){

            case MsfgProductsLoans$STR_PAD_LEFT:
                str = Array(len + 1 - str.length).join(pad) + str;
            break;

            case MsfgProductsLoans$STR_PAD_BOTH:
                var right = Math.ceil((padlen = len - str.length) / 2);
                var left = padlen - right;
                str = Array(left+1).join(pad) + str + Array(right+1).join(pad);
            break;

            default:
                str = str + Array(len + 1 - str.length).join(pad);
            break;

        } // switch

    }

    return str;

}

function MsfgProductsLoans$suggestSBSCompare(sender, args) {
var dataBoundControlName = 'ucSearchResults_orResults'; 
var checkBoxNameInDataBoundControl = 'chkCompare';
var checkedCount = 0;
var i = 2;
var ctlId = "_ctl";
var derivedName = dataBoundControlName + '_ctl0' + i + '_'+ checkBoxNameInDataBoundControl;
var currentListItem = document.getElementById(derivedName);
while (currentListItem != null){
    if (currentListItem.checked == true) {
    checkedCount += 1;
   }
    //increment i AND get the next control
    i += 1 ;
    if(i < 10)
    derivedName = dataBoundControlName + '_ctl0' + i + '_'+ checkBoxNameInDataBoundControl;
   else
    derivedName = dataBoundControlName + '_ctl' + i + '_'+ checkBoxNameInDataBoundControl;
    currentListItem = document.getElementById(derivedName);
}

if (checkedCount <2 || checkedCount > 4) {
   alert('You can compare upto 4 quotes side by side, minimum is 2') ;
}
}

function MsfgProductsLoans$changeButtonImage(searchType) 
{
	// Method to change the button's image.
	var parentElementField = searchType.parentNode;
	if (typeof parentElementField.compareButtonFieldId == "undefined" || typeof parentElementField.compareNowButtonFieldId == "undefined" || typeof parentElementField.continueButtonFieldId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure
		return;
	}
	// Get reference to the ProceedButton button controls
	var compareButton = $(parentElementField.compareButtonFieldId);
	var compareNowButton = $(parentElementField.compareNowButtonFieldId);
	var continueButton = $(parentElementField.continueButtonFieldId);
	if (compareButton == null || compareNowButton == null || continueButton == null) 
	{
		return;
	}
	var compareButtonStyle = 'none';
	var compareNowButtonStyle = 'none';
	var continueButtonStyle = 'none';
	if (searchType.value == "Quick Search")
	{
		compareNowButtonStyle = '';
	}
	else if (searchType.value == "Smart Search")
	{
		continueButtonStyle = '';
	}
	compareButton.style.display = compareButtonStyle;
	compareNowButton.style.display = compareNowButtonStyle;
	continueButton.style.display = continueButtonStyle;
}

// Resets the warning displayed indicator to allow re-evaluation of the loan term warning
function MsfgProductsLoans$periodChanged()
{
	warningDisplayed = false;
}
function MsfgProductsLoans$setFocus(validatedControlID)
{
	if (typeof validatedControlID == "undefined") 
	{
		// The control ID was not provided
		return;
	}
	// Gets a reference to the control being validated
	var validatedControl = $(validatedControlID);
	if (validatedControl == null) 
	{
		// The fields couldn't be found - once again, delegate to the server.
		return;
	}
	validatedControl.focus();
}
function MsfgProductsLoans$disableProviderList(sender)
{
	if (typeof sender.mainAccountProviderFieldId == "undefined") 
	{
		// The control ID was not provided
		return;
	}
	// Get reference to the control being validated
	var mainAccountProviderField = $(sender.mainAccountProviderFieldId);
	if (mainAccountProviderField == null) 
	{
		// The fields couldn't be found - once again, delegate to the server.
		return;
	}
	if (sender.value == '1')
	{
		mainAccountProviderField.value = 0;
		mainAccountProviderField.disabled = true;	
	}
	else
	{
		mainAccountProviderField.disabled = false;
	}
}








function MsfgProductsLoans$DCStoreCards(sender, args)
{

	args.IsValid = true;
	if (typeof sender.OweStoreCardsId == "undefined" || typeof sender.PayBackStoreCardsId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure - delegate validation or warning to the server.
		return;
	}
		var oweStoreCards = $(sender.OweStoreCardsId);
		var payBackStoreCards = $( sender.PayBackStoreCardsId);
		var oweStoreCardsAmount = (!isNaN(parseFloat(oweStoreCards.value)) ? parseFloat(oweStoreCards.value) : 0);
		var payBackStoreCardsAmount = (!isNaN(parseFloat(payBackStoreCards.value)) ? parseFloat(payBackStoreCards.value) : 0);

		if((oweStoreCardsAmount ==0)&&(payBackStoreCardsAmount>0))
		{
			/*alert('Existing loans repayment should not have a value, as the outstanding amount is zero');
			oweExistingLoans.focus();*/
			args.IsValid = false;
			return;
		}
} 


function MsfgProductsLoans$DCPayBackStoreCards(sender, args)
{

	args.IsValid = true;
	if (typeof sender.OweStoreCardsId == "undefined" || typeof sender.PayBackStoreCardsId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure - delegate validation or warning to the server.
		return;
	}
		var oweStoreCards = $(sender.OweStoreCardsId);
		var payBackStoreCards = $( sender.PayBackStoreCardsId);
		var oweStoreCardsAmount = (!isNaN(parseFloat(oweStoreCards.value)) ? parseFloat(oweStoreCards.value) : 0);
		var payBackStoreCardsAmount = (!isNaN(parseFloat(payBackStoreCards.value)) ? parseFloat(payBackStoreCards.value) : 0);

		if((oweStoreCardsAmount >0)&&(payBackStoreCardsAmount==0))
		{
			/*alert('Existing loans repayment cannot be zero');
			payBackExistingLoansAmount.focus();*/
			args.IsValid = false;
			return;
		}
} 


function MsfgProductsLoans$DCExistingLoans(sender, args)
{

	args.IsValid = true;
	if (typeof sender.OweExistingLoansId == "undefined" || typeof sender.PayBackExistingLoansId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure - delegate validation or warning to the server.
		return;
	}
		var oweExistingLoans = $(sender.OweExistingLoansId);
		var payBackExistingLoans = $( sender.PayBackExistingLoansId);
		var oweExistingLoansAmount = (!isNaN(parseFloat(oweExistingLoans.value)) ? parseFloat(oweExistingLoans.value) : 0);
		var payBackExistingLoansAmount = (!isNaN(parseFloat(payBackExistingLoans.value)) ? parseFloat(payBackExistingLoans.value) : 0)

		if((oweExistingLoansAmount ==0)&&(payBackExistingLoansAmount>0))
		{
			/*alert('Existing loans repayment should not have a value, as the outstanding amount is zero');
			oweExistingLoans.focus();*/
			args.IsValid = false;
			return;
		}
} 


function MsfgProductsLoans$DCPayBackExistingLoans(sender, args)
{

	args.IsValid = true;
	if (typeof sender.OweExistingLoansId == "undefined" || typeof sender.PayBackExistingLoansId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure - delegate validation or warning to the server.
		return;
	}
		var oweExistingLoans = $(sender.OweExistingLoansId);
		var payBackExistingLoans = $( sender.PayBackExistingLoansId);
		var oweExistingLoansAmount = (!isNaN(parseFloat(oweExistingLoans.value)) ? parseFloat(oweExistingLoans.value) : 0);
		var payBackExistingLoansAmount = (!isNaN(parseFloat(payBackExistingLoans.value)) ? parseFloat(payBackExistingLoans.value) : 0)

		if((oweExistingLoansAmount >0)&&(payBackExistingLoansAmount==0))
		{
			/*alert('Existing loans repayment cannot be zero');
			payBackExistingLoansAmount.focus();*/
			args.IsValid = false;
			return;
		}
} 



function MsfgProductsLoans$DCCarLoan(sender, args)
{

	args.IsValid = true;
	if (typeof sender.OweCarLoansHireId == "undefined" || typeof sender.PayBackCarLoansHireId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure - delegate validation or warning to the server.
		return;
	}
		var oweCarLoansHire = $(sender.OweCarLoansHireId);
		var payBackCarLoansHire = $( sender.PayBackCarLoansHireId);
		var oweCarLoansHireAmount = (!isNaN(parseFloat(oweCarLoansHire.value)) ? parseFloat(oweCarLoansHire.value) : 0);
		var payBackCarLoansHireAmount = (!isNaN(parseFloat(payBackCarLoansHire.value)) ? parseFloat(payBackCarLoansHire.value) : 0);

		if((oweCarLoansHireAmount ==0)&&(payBackCarLoansHireAmount>0))
		{
			/*alert('Existing loans repayment should not have a value, as the outstanding amount is zero');
			oweExistingLoans.focus();*/
			args.IsValid = false;
			return;
		}
} 


function MsfgProductsLoans$DCPayBackCarLoan(sender, args)
{

	args.IsValid = true;
	if (typeof sender.OweCarLoansHireId == "undefined" || typeof sender.PayBackCarLoansHireId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure - delegate validation or warning to the server.
		return;
	}
		var oweCarLoansHire = $(sender.OweCarLoansHireId);
		var payBackCarLoansHire = $( sender.PayBackCarLoansHireId);
		var oweCarLoansHireAmount = (!isNaN(parseFloat(oweCarLoansHire.value)) ? parseFloat(oweCarLoansHire.value) : 0);
		var payBackCarLoansHireAmount = (!isNaN(parseFloat(payBackCarLoansHire.value)) ? parseFloat(payBackCarLoansHire.value) : 0);

		if((oweCarLoansHireAmount >0)&&(payBackCarLoansHireAmount==0))
		{
			/*alert('Existing loans repayment cannot be zero');
			payBackExistingLoansAmount.focus();*/
			args.IsValid = false;
			return;
		}
} 


function MsfgProductsLoans$DCOtherDebt(sender, args)
{
	args.IsValid = true;
	if (typeof sender.OweOtherDebtsId == "undefined" || typeof sender.PayBackOtherDebtsId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure - delegate validation or warning to the server.
		return;
	}
	var oweOtherDebts = $(sender.OweOtherDebtsId);
	var payBackOtherDebts = $( sender.PayBackOtherDebtsId);
	var oweOtherDebtsAmount = (!isNaN(parseFloat(oweOtherDebts.value)) ? parseFloat(oweOtherDebts.value) : 0);
	var payBackOtherDebtsAmount = (!isNaN(parseFloat(payBackOtherDebts.value)) ? parseFloat(payBackOtherDebts.value) : 0);


		if((oweOtherDebtsAmount ==0)&&(payBackOtherDebtsAmount>0))
		{
			/*alert('Existing loans repayment should not have a value, as the outstanding amount is zero');
			oweExistingLoans.focus();*/
			args.IsValid = false;
			return;
		}
} 


function MsfgProductsLoans$DCPayBackOtherDebt(sender, args)
{

	args.IsValid = true;
	if (typeof sender.OweOtherDebtsId == "undefined" || typeof sender.PayBackOtherDebtsId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure - delegate validation or warning to the server.
		return;
	}
	var oweOtherDebts = $(sender.OweOtherDebtsId);
	var payBackOtherDebts = $( sender.PayBackOtherDebtsId);
	var oweOtherDebtsAmount = (!isNaN(parseFloat(oweOtherDebts.value)) ? parseFloat(oweOtherDebts.value) : 0);
	var payBackOtherDebtsAmount = (!isNaN(parseFloat(payBackOtherDebts.value)) ? parseFloat(payBackOtherDebts.value) : 0);

		if((oweOtherDebtsAmount >0)&&(payBackOtherDebtsAmount==0))
		{
			//alert('Credit Card repayment cannot be zero');
			/*payBackCreditCards.focus();
			sender.innerText = 'errorMessage';
			sender.ErrorMessage = 'cc';*/
			args.IsValid = false;
			return;
		}
} 


function MsfgProductsLoans$DebtConsolidation1(sender, args) 
{
	args.IsValid = true;
	if (typeof sender.OweCreditCardsId == "undefined" || typeof sender.PayBackCreditCardsId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure - delegate validation or warning to the server.
		return;
	}
	var oweCreditCards = $(sender.OweCreditCardsId);
	var payBackCreditCards = $( sender.PayBackCreditCardsId);
	var oweCreditCardsAmount = (!isNaN(parseFloat(oweCreditCards.value)) ? parseFloat(oweCreditCards.value) : 0);
	var payBackCreditCardsAmount = (!isNaN(parseFloat(payBackCreditCards.value)) ? parseFloat(payBackCreditCards.value) : 0);

		if((oweCreditCardsAmount >0)&&(payBackCreditCardsAmount==0))
		{
			//alert('Credit Card repayment cannot be zero');
			/*payBackCreditCards.focus();
			sender.innerText = 'errorMessage';
			sender.ErrorMessage = 'cc';*/
			args.IsValid = false;
			return;
		}
	}





function MsfgProductsLoans$DebtConsolidation(sender, args) 
{
	args.IsValid = true;
	if (typeof sender.OweCreditCardsId == "undefined" || typeof sender.PayBackCreditCardsId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure - delegate validation or warning to the server.
		return;
	}
	var oweCreditCards = $(sender.OweCreditCardsId);
	var payBackCreditCards = $( sender.PayBackCreditCardsId);
	var oweCreditCardsAmount = (!isNaN(parseFloat(oweCreditCards.value)) ? parseFloat(oweCreditCards.value) : 0);
	var payBackCreditCardsAmount = (!isNaN(parseFloat(payBackCreditCards.value)) ? parseFloat(payBackCreditCards.value) : 0);
	
	
	/*var oweExistingLoans = $(sender.OweExistingLoansId);
	var payBackExistingLoans = $( sender.PayBackExistingLoansId);
	var oweExistingLoansAmount = (!isNaN(parseFloat(oweExistingLoans.value)) ? parseFloat(oweExistingLoans.value) : 0);
	var payBackExistingLoansAmount = (!isNaN(parseFloat(payBackExistingLoans.value)) ? parseFloat(payBackExistingLoans.value) : 0);
	
	var oweStoreCards = $(sender.OweStoreCardsId);
	var payBackStoreCards = $( sender.PayBackStoreCardsId);
	var oweStoreCardsAmount = (!isNaN(parseFloat(oweStoreCards.value)) ? parseFloat(oweStoreCards.value) : 0);
	var payBackStoreCardsAmount = (!isNaN(parseFloat(payBackStoreCards.value)) ? parseFloat(payBackStoreCards.value) : 0);
	
	var oweCarLoansHire = $(sender.OweCarLoansHireId);
	var payBackCarLoansHire = $( sender.PayBackCarLoansHireId);
	var oweCarLoansHireAmount = (!isNaN(parseFloat(oweCarLoansHire.value)) ? parseFloat(oweCarLoansHire.value) : 0);
	var payBackCarLoansHireAmount = (!isNaN(parseFloat(payBackCarLoansHire.value)) ? parseFloat(payBackCarLoansHire.value) : 0);
	
	var oweCarLoansHire = $(sender.OweCarLoansHireId);
	var payBackCarLoansHire = $( sender.PayBackCarLoansHireId);
	var oweCarLoansHireAmount = (!isNaN(parseFloat(oweCarLoansHire.value)) ? parseFloat(oweCarLoansHire.value) : 0);
	var payBackCarLoansHireAmount = (!isNaN(parseFloat(payBackCarLoansHire.value)) ? parseFloat(payBackCarLoansHire.value) : 0);*/
	
	
	if((oweCreditCardsAmount ==0)&&(payBackCreditCardsAmount>0))
	{
	//alert('Credit Card repayment should not have a value, as the outstanding amount is zero');
	oweCreditCards.value ='0';
	oweCreditCards.focus();
	//sender.innerText = 'errorMessage';
	//sender.ErrorMessage = 'cc';
	args.IsValid = false;
	return; 
	}
	
/*	if((oweCreditCardsAmount >0)&&(payBackCreditCardsAmount==0))
	{
	alert('Credit Card repayment cannot be zero');
	payBackCreditCards.focus();
	sender.innerText = 'errorMessage';
	sender.ErrorMessage = 'cc';
	args.IsValid = false;
	return;
	}
	
	
	
	if((oweExistingLoansAmount ==0)&&(payBackExistingLoansAmount>0))
	{
	alert('Existing loans repayment should not have a value, as the outstanding amount is zero');
	oweExistingLoans.focus();
	args.IsValid = false;
	return;
	}
	
	if((oweExistingLoansAmount >0)&&(payBackExistingLoansAmount==0))
	{
	alert('Existing loans repayment cannot be zero');
	payBackExistingLoansAmount.focus();
	args.IsValid = false;
	return;
	}
	
	
	if((oweStoreCardsAmount ==0)&&(payBackStoreCardsAmount>0))
	{
	alert('Store cards repayment should not have a value, as the outstanding amount is zero');
	oweStoreCards.focus();
	args.IsValid = false;
	return;
	}
	
	if((oweStoreCardsAmount >0)&&(payBackStoreCardsAmount==0))
	{
	alert('Store cards repayment cannot be zero');
	payBackStoreCards.focus();
	args.IsValid = false;
	return;
	}
	
	
	
	
	
	if((oweCarLoansHireAmount ==0)&&(payBackCarLoansHireAmount>0))
	{
	alert('Car loans / Hire purchase amount repayment should not have a value, as the outstanding amount is zero');
	oweCarLoansHire.focus();
	args.IsValid = false;
	return;
	}
	
	if((oweCarLoansHireAmount >0)&&(payBackCarLoansHireAmount==0))
	{
	alert('Car loans / Hire purchase repayment cannot be zero');
	CarLoansHire.focus();
	args.IsValid = false;
	return;
	}*/
	
	
	/*if (periodField == null || loanAmountField == null || residentialStatusField == null) 
	{
		// The field couldn't be found
		return;
	}
	
	
	// We won't check for numerical validity on the fields as there should be a validator checking this already.
	var amountEntered = (!isNaN(parseFloat(loanAmountField.value)) ? parseFloat(loanAmountField.value) : 0);
	var selectedDurationMonths = parseInt(periodField.options[periodField.selectedIndex].value);
	var residentialStatus = parseInt(residentialStatusField.options[residentialStatusField.selectedIndex].value);

	if ((residentialStatus != '2' && residentialStatus != '1') && amountEntered > 25000) 
	{
		// Home ownership must be validated before displaying the message
		return;
	}
	
		if (amountEntered < 50 || amountEntered > 250000) 
	{
		// Suppress the warning - Loan amount is invalid.
		return;
	}
	if (warningDisplayed) 
	{
		// We've already displayed the warning - no need to continue with this check.
		return;
	}
	if (!warningDisplayed && (amountEntered > 25000 && selectedDurationMonths < 60)) 
	{
		warningDisplayed = true;
		args.IsValid = false;
		MsfgProductsLoans$setFocus(sender.controltovalidate);
	}*/
	
	//args.IsValid = false;
}



function MsfgProductsLoans$ExistingLoans(sender, args) 
{
	args.IsValid = true;
	if (typeof sender.OweExistingLoansId == "undefined" || typeof sender.PayBackExistingLoansId == "undefined") 
	{
		// We don't have the parameters we need, or they aren't in the expected structure - delegate validation or warning to the server.
		return;
	}
	var oweExistingLoans = $(sender.OweExistingLoansId);
	var payBackExistingLoans = $( sender.PayBackExistingLoansId);
	var oweExistingLoansAmount = (!isNaN(parseFloat(oweExistingLoans.value)) ? parseFloat(oweExistingLoans.value) : 0);
	var payBackExistingLoansAmount = (!isNaN(parseFloat(payBackExistingLoans.value)) ? parseFloat(payBackExistingLoans.value) : 0);
	if((oweExistingLoansAmount ==0)&&(payBackExistingLoansAmount>0))
	{
	alert('Existing loans repayment should not have a value, as the outstanding amount is zero');
	oweCreditCards.focus();
	args.IsValid = false;
	}
	
	if((oweExistingLoansAmount >0)&&(payBackExistingLoansAmount==0))
	{
	alert('Existing loans repayment cannot be zero');
	payBackCreditCards.focus();
	args.IsValid = false;
	}
}

/* Pre-Apply page: expand / collapse the more button */
function ChangeExpandingText(hypMoreId)
{
    if (document.getElementById('divMore'))
    {
        if (document.getElementById(hypMoreId).innerHTML=="More")
        {
            document.getElementById(hypMoreId).innerHTML="Less";
            document.getElementById(hypMoreId).setAttribute('title','Less');
            document.getElementById('divMore').style.display="block";
        }
        else
        {
            document.getElementById(hypMoreId).innerHTML="More";
            document.getElementById(hypMoreId).setAttribute('title','More');
            document.getElementById('divMore').style.display="none";
        }
    }   
}
/* End Pre-Apply page: expand / collapse the more button */

function Msfg$Money$Loans$BestSellersTablesHelpText_OnExpandComplete(animationControl) 
{
	if (animationControl) 
	{
	    var animLink = $get(animationControl.get_ControlIdToToggleBlind());
	    
	    if (animLink) 
	    {
		    animLink.innerHTML = "Hide Help Text";
		    animLink.title = "Click here to hide the help text";
	    }
	}
}

function Msfg$Money$Loans$BestSellersTablesHelpText_OnCollapseComplete(animationControl) 
{
	if (animationControl) 
	{
	    var animLink = $get(animationControl.get_ControlIdToToggleBlind());
	    
	    if (animLink) 
	    {
		    animLink.innerHTML = "Tell me how to work out my credit profile";
		    animLink.title = "Click here to show the help text";
	    }
	}
}

/// <summary>
/// Adds prompt text to an input field.
/// </summary>
/// <param name="event">The event to handle.  </param>
function Msfg$Money$Loans$onBlurAddTemporaryInputText(event) {

    var element = Event.element(event);
    Msfg$Money$Loans$addTemporaryInputText(element);

}

/// <summary>
/// Adds prompt text to an input field.
/// </summary>
/// <param name="element">The element.  </param>
function Msfg$Money$Loans$addTemporaryInputText(element) {
   
    var element = $(element);
	var value = $F(element);
    var text = element.readAttribute("promptText");
    var maxLength = element.readAttribute("maxlength");    
    
    if (value == 'NaN')
    {
        value = '0';
        element.value = value;
    }
    
	var leftTrimmedValue = value.replace(/^\s+/,""); 	

	if (text.length > maxLength)
		text = text.substring(0, maxLength);
	
	if (leftTrimmedValue == "" || leftTrimmedValue == text) {
		// Losing focus and the field is empty or the user has typed in the prompt text (?!).
		element.addClassName("msfg-placeholder");
		element.value = text;
	} else {
		if (leftTrimmedValue != text) {
			element.removeClassName("msfg-placeholder");
		}
	}
}

/// <summary>
/// Removes prompt text from an input field.
/// </summary>
/// <param name="event">The event to handle.  </param>
function Msfg$Money$Loans$onFocusRemoveTemporaryInputText(event) {
    
    var element = Event.element(event);
    Msfg$Money$Loans$removeTemporaryInputText(element);
}

/// <summary>
/// Removes prompt text from an input field.
/// </summary>
/// <param name="element">The element.  </param>
function Msfg$Money$Loans$removeTemporaryInputText(element) {
    
    element = $(element);
	var value = $F(element);
    var text = element.readAttribute("promptText");
    var maxLength = element.readAttribute("maxlength");    
    
	var leftTrimmedValue = value.replace(/^\s+/,""); 

	if (text.length > maxLength)
		text = text.substring(0, maxLength);
	
	if (leftTrimmedValue == text) {
		// Gaining focus and the field has the the prompt text.
		element.removeClassName("msfg-placeholder");
		element.value = "";
	} else {
		element.removeClassName("msfg-placeholder");
	}
}

function Msfg$Money$Loans$observeOnClickForOpenRadWindow(element, radWindowManager)
{
    element = $(element);
    radWindowManager = $(radWindowManager);

    element.writeAttribute('radWindowManager', radWindowManager.identify());
    element.observe('click', Msfg$Money$Loans$onClickOpenRadWindow.bindAsEventListener(element));
}

function Msfg$Money$Loans$observeOnClickForOpenRadWindow(element, radWindowManager,offSetElementId)
{
    element = $(element);
    radWindowManager = $(radWindowManager);

    element.writeAttribute('radWindowManager', radWindowManager.identify());
    element.writeAttribute('offsetElementId', offSetElementId);
    element.observe('click', Msfg$Money$Loans$onClickOpenRadWindow.bindAsEventListener(element));
}

function Msfg$Money$Loans$onClickOpenRadWindow(event)
{
    var element = this;
    
    Msfg$Money$Loans$openRadWindow(element.readAttribute('radWindowManager'), element.readAttribute('href'),element.readAttribute('offsetElementId'));
    
    event.stop();
}

function Msfg$Money$Loans$openRadWindow(radWindowManager, url)
{
    var radWindowManager = $find($(radWindowManager).identify());

    if (!radWindowManager)
    {
        return;
    }    
    
    var radWindow = radWindowManager.open(url, 'Default');
    radWindow.center();
    radWindow.show();
}

function Msfg$Money$Loans$openRadWindow(radWindowManager, url, offsetElementId)
{
    var radWindowManager = $find($(radWindowManager).identify());

    if (!radWindowManager)
    {
        return;
    }    
    
    var radWindow = radWindowManager.open(url, 'Default');
    radWindow.OffsetElementId = offsetElementId;
    radWindow.show();
}

function Msfg$Money$Loans$onImgErrorLogo(image,alternativeImage)
{
       alert(image.tagName);
       image.src= alternativeImage;
       image.onerror = "";
       return true;
}

function Msfg$Money$Loans$onBlurRemoveAngleBrackets(event)
{
	var inputField = this;
	inputField.value = inputField.value.replace(/</g,"");
	inputField.value = inputField.value.replace(/>/g,"");
}
function Msfg$Money$Loans$EnableOrDisableValidators(element, enabled)
{
    // Accept element as an id or an actual DOM element object. 
    element = $(element);

    for (var i = 0; i < Page_Validators.length; i++)
    {
        var validator = Page_Validators[i];
        // Extend validator element with Prototype framework.  
        validator = $(validator);
        
        if (validator.descendantOf(element))
        {
            ValidatorEnable(validator, !!enabled);
        }
    }
}

function Msfg$Money$Loans$PreApply$onChangeToMarketingOption(event)
{
    var marketingOptionCheckBox = $$('.msfg-money-loans-preapply-marketingoption input')[0];
    
    var marketingOptionAnswer = marketingOptionCheckBox.checked;
    var questionsVisible = marketingOptionAnswer;
    
    var questionsDataEntryContainer = $$('.msfg-money-loans-preapply-questions')[0];    

    Msfg$Money$Loans$EnableOrDisableValidators(questionsDataEntryContainer, questionsVisible);
    
    if (questionsVisible)
    {
        questionsDataEntryContainer.setStyle({
            display: 'block'
        });
    }
    else
    {
        questionsDataEntryContainer.setStyle({
            display: 'none'
        });
    }
}


function Msfg$Money$Loans$PreApply$init()
{
    var marketingOptionCheckBox = $$('.msfg-money-loans-preapply-marketingoption')[0];
    if(marketingOptionCheckBox){
    marketingOptionCheckBox.observe(
        'click', 
        Msfg$Money$Loans$PreApply$onChangeToMarketingOption);
}
}

	Msfg$Money$Loans$PreApply$init();


// Channel Feedback
  
function OpenWindow(name, url)
{
    var oWnd = $find( name );
    oWnd.SetSize(510,310);
    oWnd.show();
}

// Compare Loans

 	// PM PUT HERE

    function Msfg$OnResidentialStatusChanged()
    {
		var nonhomeownerPanel = $$(".msfg-nonhomeownerpanel")[0];
		var loanstocompare = $$(".msfg-loanstocompare-span")[0];
    		var totalloansavailable = $$(".msfg-totalloansavailable")[0];	 
    		var loanstocomparePanel = $$(".msfg-loanstocomparepanel")[0];	
    		var totalloansavailable = $$(".msfg-totalloansavailable")[0];
    		var oSpanMessage = $$(".msfg-spanMessage")[0];
    		var ddlLoanPeriod = $$(".msfg-ddlLoanPeriod")[0];
    		var ddlResidentialStatus = $$(".msfg-ddlResidentialStatus")[0];
    		var hidProductType = $$(".msfg-hidPageId")[0];
    		var txtLoanAmount = $$(".msfg-loanamount")[0];


        if(pageID == 101)
        {
            var selectedValue = ddlResidentialStatus.options[ddlResidentialStatus.selectedIndex].value;
            if(selectedValue > 2)
            {
                showLoantoCompare = false;
                nonhomeownerPanel.style.visibility = 'visible';
                loanstocompare.style.visibility = 'hidden';
                totalloansavailable.style.visibility = 'hidden';        
                loanstocomparePanel.style.visibility = 'hidden';
                loanstocompare.style.display = 'none';
                totalloansavailable.style.display = 'none'; 
                loanstocomparePanel.style.display = 'none';

                if(oSpanMessage!=null)
                {
                    oSpanMessage.style.visibility = 'hidden';            
                }            
            }
            else
            {
                showLoantoCompare = true;
                
                nonhomeownerPanel.style.visibility = 'hidden';
                totalloansavailable.style.visibility = 'visible';
                totalloansavailable.style.visibility = 'visible';        
                loanstocomparePanel.style.visibility = 'visible';
                loanstocompare.style.display = 'block';
                totalloansavailable.style.display = 'block'; 
                loanstocomparePanel.style.display = 'block';

                if(oSpanMessage!=null)
                {
                    oSpanMessage.style.visibility = 'visible';            
                }
                Msfg$UpdateLoanCount();
            }
        }
        else
        {
            showLoantoCompare = true;
            nonhomeownerPanel.style.visibility = 'hidden';
            Msfg$UpdateLoanCount();
        }
    }
   
    function Msfg$UpdateLoanCount()
    {        
	  var nonhomeownerPanel = $$(".msfg-nonhomeownerpanel")[0];
    var loanstocompare = $$(".msfg-loanstocompare-span")[0];
    var totalloansavailable = $$(".msfg-totalloansavailable")[0];	 
    var loanstocomparePanel = $$(".msfg-loanstocomparepanel")[0];	
    var totalloansavailable = $$(".msfg-totalloansavailable")[0];
    var oSpanMessage = $$(".msfg-spanMessage")[0];
    var ddlLoanPeriod = $$(".msfg-ddlLoanPeriod")[0];
    var ddlResidentialStatus = $$(".msfg-ddlResidentialStatus")[0];
    var hidProductType = $$(".msfg-hidPageId")[0];
    var txtLoanAmount = $$(".msfg-loanamount")[0];


        self.clearInterval(loanstocompareTimeOutMonitor);
        if(showLoantoCompare)
        {           
            if(Msfg$InitializeCompareText())
            {
                loanstocompareTimeOutMonitor = self.setInterval("Msfg$LoansToCompareTimeOutHandler();",loanstocompareTimeOutInterval);
                try
                {
                    Msfg.Money.Loans.Presentation.Web.UI.availableloans.GetLoanCount(hidProductType.value, txtLoanAmount.value, 
                    ddlLoanPeriod.options[ddlLoanPeriod.selectedIndex].value, 
                    ddlResidentialStatus.options[ddlResidentialStatus.selectedIndex].value, 
                    Msfg$OnWSRequestComplete, 
                    Msfg$OnWSRequestFailed);
                }    
                catch(err)
                {
                }
            }
                              
            
        }
    }
    
    function Msfg$LoansToCompareTimeOutHandler()
    {
        var totalloansavailable = $$(".msfg-totalloansavailable")[0];	 
        totalloansavailable.innerHTML = "";
        totalloansavailable.style.visibility = "visible";
        oSpanMessage.innerHTML = '';
    }
    
    function Msfg$InitializeCompareText()
    {
 var nonhomeownerPanel = $$(".msfg-nonhomeownerpanel")[0];
    var loanstocompare = $$(".msfg-loanstocompare-span")[0];
    var totalloansavailable = $$(".msfg-totalloansavailable")[0];	 
    var loanstocomparePanel = $$(".msfg-loanstocomparepanel")[0];	
    var totalloansavailable = $$(".msfg-totalloansavailable")[0];
    var oSpanMessage = $$(".msfg-spanMessage")[0];
    var ddlLoanPeriod = $$(".msfg-ddlLoanPeriod")[0];
    var ddlResidentialStatus = $$(".msfg-ddlResidentialStatus")[0];
    var hidProductType = $$(".msfg-hidPageId")[0];
    var txtLoanAmount = $$(".msfg-loanamount")[0];


            var option1 = 0;
            var option2 = 0;
            var option3 = 0;
            
            if(ddlLoanPeriod.options[ddlLoanPeriod.selectedIndex].value != '')
            {
                option1 = 1;
            }
            
            if(ddlResidentialStatus.options[ddlResidentialStatus.selectedIndex].value != '')
            {
                option2 = 1;
            }
            
            if(txtLoanAmount.value != '')
            {
                option3 = 1;
            }

            if((option1 & option2 & option3) == 1)
            {
                totalloansavailable.innerHTML = "calculating";
                totalloansavailable.style.visibility = "visible";
                loanstocompare.style.visibility = "visible";  
                oSpanMessage.innerHTML = '...';
                return true;
            }
            else
            {
                totalloansavailable.innerHTML = "";
                oSpanMessage.innerHTML = "";        
                return false;
            }
    }
    
    function Msfg$OnWSRequestComplete(results)
    {
	    var totalloansavailable = $$(".msfg-totalloansavailable")[0];
        var loanstocompare = $$(".msfg-loanstocompare-span")[0];
	    var oSpanMessage = $$(".msfg-spanMessage")[0];

        if(showLoantoCompare)
        {
            self.clearInterval(loanstocompareTimeOutMonitor);
            if (results != null)
            { 
                totalloansavailable.innerHTML = results.toString();
                totalloansavailable.style.visibility = "visible";
                loanstocompare.style.visibility = "visible";
                
                if(oSpanMessage != null)
                {
                    if(results == 1)
                    {
                        oSpanMessage.innerHTML = 'loan to compare';
                    }
                    else
                    {
                        oSpanMessage.innerHTML = 'loans to compare';
                    }
                }
            }
            else
            {
                totalloansavailable.innerHTML = "";
            }
        }
    }
    
    function Msfg$OnWSRequestFailed(error) 
    { 
        var totalloansavailable = $$(".msfg-totalloansavailable")[0];	 
    	var loanstocompare = $$(".msfg-loanstocompare-span")[0];
        self.clearInterval(loanstocompareTimeOutMonitor);
        totalloansavailable.style.visibility = "hidden";
        loanstocompare.style.visibility = "hidden";
    }
    
    //Initialize the compare container
    function Msfg$InitialiseControlValues(pageId)
    {
		pageID = pageId;
		
         	var nonhomeownerPanel = $$(".msfg-nonhomeownerpanel")[0];
		    var loanstocompare = $$(".msfg-loanstocompare-span")[0];
    		var totalloansavailable = $$(".msfg-totalloansavailable")[0];	 
    		var loanstocomparePanel = $$(".msfg-loanstocomparepanel")[0];	
    		var totalloansavailable = $$(".msfg-totalloansavailable")[0];
    		var oSpanMessage = $$(".msfg-spanMessage")[0];
    		var ddlLoanPeriod = $$(".msfg-ddlLoanPeriod")[0];
    		var ddlResidentialStatus = $$(".msfg-ddlResidentialStatus")[0];
    		var hidProductType = $$(".msfg-hidPageId")[0];
    		var txtLoanAmount = $$(".msfg-loanamount")[0];

		txtLoanAmount.observe('blur', Msfg$UpdateLoanCount);
		ddlLoanPeriod.observe('blur', Msfg$UpdateLoanCount);
		ddlResidentialStatus.observe('blur', Msfg$UpdateLoanCount);
		ddlResidentialStatus.observe('blur', Msfg$OnResidentialStatusChanged);

		Msfg$OnResidentialStatusChanged();		
    }
    
    if (typeof(Controls) != "undefined" && typeof(Controls.BaseTooltipPanelBehaviour) != "undefined") {
        Controls.BaseTooltipPanelBehaviour.prototype._createIEFrame = function() {
            this._ieframe = document.createElement('iframe');
		    var frameStyle = this._ieframe.style;
		    this._ieframe.setAttribute("scrolling", "no");
		    this._ieframe.setAttribute("frameborder", "0");
		    this._ieframe.setAttribute("src", "about:blank");   // its only ever in IE
		    frameStyle.position = "absolute";
		    frameStyle.border = "none";
		    frameStyle.display = "none";
		    frameStyle.zIndex = 998;
		    this._tooltip.parentNode.appendChild(this._ieframe);		
        }
    }
    
// Email Results

var openEmailResults = null;

function initialiseEmailResultsPopup()
{
	var customerFeedbackLinks = $$(".msfg-hypemailresults");
	
	// Cannot find control so don't attempt to observe it.
	if (customerFeedbackLinks == "undefined" || customerFeedbackLinks == null)
	{
		return
	}
	
	if (customerFeedbackLinks.length == 1)
		openEmailResults = customerFeedbackLinks[0];
	else {
		for (var i = 0; i < customerFeedbackLinks.length && openEmailResults == null; i++) {
			if (customerFeedbackLinks[i].tagName.toUpperCase() == "A")
				openEmailResults = customerFeedbackLinks[i];
		}
	}
	
	if (openEmailResults != null)
	{
		openEmailResults.observe('click', Msfg$OpenEmailResultsOverlay);
	}	
}



function Msfg$OpenEmailResultsOverlay(evt)
{
	if (openEmailResults) {
		var targetWindow = $find(openEmailResults.TargetWindowId);
		if (targetWindow) {
			targetWindow.SetUrl(openEmailResults.readAttribute('href'));
			targetWindow.Show();
		}
	}
	evt.stop();
}


// Help and support
var li = $$(".msfg-tell-us-what-you-think")[0];

function Msfg$TellusWhatYouThinkOverlay()
{
	var windowManager = GetRadWindowManager();

	if (windowManager) 
	{
		var radWindow = windowManager.getWindowByName("rwHSTellusWhatYouThinkBanner");
		if (radWindow) 
		{
			radWindow.setUrl(li.readAttribute('href'));
			radWindow.show();
		}
	}

	return false;
}
	
if 	(li != null)
{
    li.observe('click',Msfg$TellusWhatYouThinkOverlay);
}

// Promorotator

var Index=1;
var maxIndex;
var lock = false;
var rightframe;
var leftframe;
var curframe;
var _templateWidth = 215;
var _autoDirection = 'right';
var elementPromorotator;
var _promoRotatorLock;
var frames;
var framesCollection;
function MSFG$MONEY$LOANS$PROMOROTATOR$MessageOut(message)
{
    var _message = document.getElementById('Message');
    _message.innerHTML = _message.innerHTML + ' ' + message;
}
      
function MSFG$MONEY$LOANS$PROMOROTATOR$Increment(index)
{
    index = index + 1;
    return MSFG$MONEY$LOANS$PROMOROTATOR$CapIndex(index);
}  

function MSFG$MONEY$LOANS$PROMOROTATOR$Decrement(index)
{
    index = index - 1;
    return MSFG$MONEY$LOANS$PROMOROTATOR$CapIndex(index);
}    

function MSFG$MONEY$LOANS$PROMOROTATOR$CapIndex(index)
{
    var _tmp = index;
    var _assigned = false;            
    if(index > maxIndex)
    {
        _tmp = 1;
        _assigned = true;
    }            
    if(index <= 0)           
    {
        _tmp = maxIndex;
        _assigned = true;
    }
    return _tmp;
}      

function MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(index)
{
	var x = $$("div.frameitem");
	
	for (i=0;i<x.length;i++)
		{
			if(x[i].id.endsWith(index.toString()))
			{
				return x[i];
			}
		}
}
       
function MSFG$MONEY$LOANS$PROMOROTATOR$GoLeft()
{   
    //Inverted the direction   
    _autoDirection = 'left';
            
    if(!lock)
    {   
        framesCollection = $$('div.frames'); 
		frames = framesCollection[0];  
        lock=true;                
        var moveEffect = new Effect.Move(frames, { x: _templateWidth , y: 0 });
        moveEffect.afterFinish = new MSFG$MONEY$LOANS$PROMOROTATOR$GoRightEffectFinished; 
    }   
    
    return false;         
}

function MSFG$MONEY$LOANS$PROMOROTATOR$GoRight()
{   
    //Inverted the direction          
    _autoDirection = 'right';
    if(!lock)
    {
        framesCollection = $$('div.frames'); 
		frames = framesCollection[0];  
        lock=true;
        var moveEffect = new Effect.Move(frames, { x: -1 * _templateWidth, y: 0 });      
        moveEffect.afterFinish = new MSFG$MONEY$LOANS$PROMOROTATOR$GoLeftEffectFinished; 
    }    
    
    return false;
}

function MSFG$MONEY$LOANS$PROMOROTATOR$GoLeftEffectFinished()
{
    var filmstrip = document.getElementById('filmstrip');
    framesCollection = $$('div.frames'); 
    frames = framesCollection[0];  
             
    curframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(Index);
    leftframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(MSFG$MONEY$LOANS$PROMOROTATOR$Decrement(Index));
    rightframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(MSFG$MONEY$LOANS$PROMOROTATOR$Increment(Index));                 
    filmstrip.appendChild(leftframe);
    filmstrip.appendChild(curframe);
    filmstrip.appendChild(rightframe);            
    Index = MSFG$MONEY$LOANS$PROMOROTATOR$Decrement(Index);
    curframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(Index);
    leftframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(MSFG$MONEY$LOANS$PROMOROTATOR$Decrement(Index));
    rightframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(MSFG$MONEY$LOANS$PROMOROTATOR$Increment(Index));
    frames.appendChild(rightframe);
    frames.appendChild(curframe);           
    frames.appendChild(leftframe);                       
    frames.style.left = "0px";                       
    setTimeout(MSFG$MONEY$LOANS$PROMOROTATOR$ReleaseLock,1000);
}

function MSFG$MONEY$LOANS$PROMOROTATOR$GoRightEffectFinished()
{
    var filmstrip = document.getElementById('filmstrip');
    framesCollection = $$('div.frames'); 
    frames = framesCollection[0];  
    curframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(Index);
    leftframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(MSFG$MONEY$LOANS$PROMOROTATOR$Decrement(Index));
    rightframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(MSFG$MONEY$LOANS$PROMOROTATOR$Increment(Index));
    filmstrip.appendChild(leftframe);
    filmstrip.appendChild(curframe);
    filmstrip.appendChild(rightframe);            
    Index = MSFG$MONEY$LOANS$PROMOROTATOR$Increment(Index);
    curframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(Index);
    leftframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(MSFG$MONEY$LOANS$PROMOROTATOR$Decrement(Index));
    rightframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(MSFG$MONEY$LOANS$PROMOROTATOR$Increment(Index));            
    frames.appendChild(rightframe);           
    frames.appendChild(curframe);
    frames.appendChild(leftframe);            
    frames.style.left = ( _templateWidth * 2 * -1 ) + "px";
    setTimeout(MSFG$MONEY$LOANS$PROMOROTATOR$ReleaseLock,1000);
}

function MSFG$MONEY$LOANS$PROMOROTATOR$Load()
{
    try
    {
        framesCollection = $$('div.frames'); 
		frames = framesCollection[0];  
        if(frames!=null)
        {
            curframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(Index);             
            leftframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(MSFG$MONEY$LOANS$PROMOROTATOR$Decrement(Index));            
            rightframe = MSFG$MONEY$LOANS$PROMOROTATOR$GetFrame(MSFG$MONEY$LOANS$PROMOROTATOR$Increment(Index));            
            frames.appendChild(leftframe);
            frames.appendChild(curframe);
            frames.appendChild(rightframe);
        }
    }
    catch(e)
    {
        document.write(e.message);
    }
}

function MSFG$MONEY$LOANS$PROMOROTATOR$ReleaseLock()
{
    lock = false;
}

function MSFG$MONEY$LOANS$PROMOROTATOR$HoldAnimation()
{
   _promoRotatorLock = true;
}

function MSFG$MONEY$LOANS$PROMOROTATOR$StartAnimation()
{
  _promoRotatorLock = false;
}   

function MSFG$MONEY$LOANS$PROMOROTATOR$Timer()
{
    if(!_promoRotatorLock)
    {
        if(_autoDirection=='left')
        {
            MSFG$MONEY$LOANS$PROMOROTATOR$GoLeft();           
        }
        if(_autoDirection=='right')
        {
           MSFG$MONEY$LOANS$PROMOROTATOR$GoRight();
        }
    }
    setTimeout(MSFG$MONEY$LOANS$PROMOROTATOR$Timer,5000);
}

function Msfg$PromotionalRotator$Initialise()
{
	//Set the timer
	setTimeout(MSFG$MONEY$LOANS$PROMOROTATOR$Timer,20000);

	// Map events to methods
	var viewport = $$('div.viewport')
	viewport[0].observe('mouseover',MSFG$MONEY$LOANS$PROMOROTATOR$HoldAnimation);
	viewport[0].observe('mouseout',MSFG$MONEY$LOANS$PROMOROTATOR$StartAnimation);
	
	var left = $$('div.msfg-promotionalrotator div.left');
	left[0].observe('click',MSFG$MONEY$LOANS$PROMOROTATOR$GoLeft);
	
	var right = $$('div.msfg-promotionalrotator div.right');
	right[0].observe('click',MSFG$MONEY$LOANS$PROMOROTATOR$GoRight);
	
	elementPromorotator = document.getElementById('promotionalrotator')
	_promoRotatorLock = false;

	// Set count of frames
	maxIndex = $$('div.frameitem').length;
	
    MSFG$MONEY$LOANS$PROMOROTATOR$Load();
}

// Search Filter
if (typeof(Controls) != "undefined" && typeof(Controls.BlindExtenderControlBehaviour) != "undefined") {
    Controls.BlindExtenderControlBehaviour.prototype._toggleBlind=function() 
    {
	    var controlExpanded = this.get_ClientState().ControlExpanded;
	    var effectCancelled = false;

        if (controlExpanded) {
		    effectCancelled = this._raiseOnClientCollapse();
		    if (!effectCancelled) {
			    Effect.BlindUp(this._controlIdToAnimate, { duration: 0.5, afterFinish: BlindAnimation_AfterCollapse, __client: this });
			    // Only if we're dealing with an image...
			    if (this._controlToToggleBlind && this._controlToToggleBlind.src)
				    this._controlToToggleBlind.src = this._toggleContractedImagePath;
		    }
        }
        else {
		    effectCancelled = this._raiseOnClientExpand();
		    if (!effectCancelled) {
			    Effect.BlindDown(this._controlIdToAnimate, { duration: 0.5, afterFinish: BlindAnimation_AfterExpand, __client: this });
			    // Only if we're dealing with an image...
			    if (this._controlToToggleBlind && this._controlToToggleBlind.src)
				    this._controlToToggleBlind.src = this._toggleExpandedImagePath;
		    }
        }
        
        if (!effectCancelled)
		    this._setToggleState(!controlExpanded);
    }
}

// Search Results

if (typeof Msfg == 'undefined')
    Msfg = Class.create();

if (typeof Msfg.Money == 'undefined')
    Msfg.Money = Class.create();
    
if (typeof Msfg.Money.Loans == 'undefined')
    Msfg.Money.Loans = Class.create();

Msfg.Money.Loans.UpdateProgress = Class.create({
    initialize: function(element) {
        if (!!element)
        {
            this._element = $(element);
        }
        
        var options = Object.extend({
            }, 
            arguments[1] || { });
                
        this._startDelay = options.startDelay || 0;
        this._endDelay = options.endDelay || 0;
    
    	if (Sys.WebForms && Sys.WebForms.PageRequestManager) {
           this._pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();
    	}
    	if (this._pageRequestManager !== null ) {
    	    this._beginRequestHandlerDelegate = Function.createDelegate(this, this._handleBeginRequest);
    	    this._endRequestHandlerDelegate = Function.createDelegate(this, this._handleEndRequest);

            this._pageRequestManager.add_beginRequest(this._beginRequestHandlerDelegate);
    	    this._pageRequestManager.add_endRequest(this._endRequestHandlerDelegate);
    	}
    },   
    _handleBeginRequest: function(sender, arg) {
        var curElem = arg.get_postBackElement();
        var showProgress = !this._element;
        var updatePanelId = this._element.identify();
        while (!showProgress && curElem) {
            if (curElem.id && updatePanelId === curElem.id) {
                showProgress = true; 
            }
            curElem = curElem.parentNode; 
        } 
        if (showProgress) {
            this._timerId = this._element.fire.bind(this._element).delay(this._startDelay, "Msfg.Money.Loans.UpdateProgress:show");
        }
    }, 
    _handleEndRequest: function(sender, arg) {   
        if (this._timerId) {
            this._element.fire("Msfg.Money.Loans.UpdateProgress:hide");
        
            window.clearTimeout(this._timerId);
            this._timerId = null;
        }
    }
});


var resultsTablesUpdateProgress;

function pageInitialise(resultsTablesUpdatePanel) 
{
    resultsTablesUpdatePanel = $(resultsTablesUpdatePanel);
    resultsTablesUpdateProgress = new Msfg.Money.Loans.UpdateProgress(resultsTablesUpdatePanel, {delay: 0.5 });

    resultsTablesUpdatePanel.observe("Msfg.Money.Loans.UpdateProgress:show", 
        function(event)
        {
            var progressElement = $("msfg-money-loans-searchresults-changingresultsindicator0");
            progressElement.setStyle({
                display: 'block'
            });
        });

    resultsTablesUpdatePanel.observe("Msfg.Money.Loans.UpdateProgress:hide", 
        function(event)
        {
            var progressElement = $("msfg-money-loans-searchresults-changingresultsindicator0");
            progressElement.setStyle({
                display: 'none'
            });
        });
}

// Video Feature
 function Msfg$VideoFeature$videowindow_close(sender, eventArgs)
 {
    sender.setUrl("about:blank");
    sender.get_navigateUrl();    
    sender.reload();    
 }
 
 //Add Customer Reviews
 
function Msfg$Money$Loans$AddCustomerReviews$Initialize(idFirstName,
            idHomeTown,
            idGiveReviewTitle,
            idReviewBodyText)
{
            var txtFirstName = $(idFirstName);
		    if(txtFirstName != null)
		    {
				txtFirstName.observe('blur', Msfg$Money$Loans$onBlurRemoveAngleBrackets.bindAsEventListener(txtFirstName));
			}
			
			var txtHomeTown = $(idHomeTown);			
			if(txtHomeTown != null)
			{
				txtHomeTown.observe('blur', Msfg$Money$Loans$onBlurRemoveAngleBrackets.bindAsEventListener(txtHomeTown));
			}
			
			var txtGiveReviewTitle = $(idGiveReviewTitle);
			if(txtGiveReviewTitle != null)
			{
				txtGiveReviewTitle.observe('blur', Msfg$Money$Loans$onBlurRemoveAngleBrackets.bindAsEventListener(txtGiveReviewTitle));
			}	
			
			var txtReviewBodyText = $(idReviewBodyText);
			if(txtReviewBodyText != null)
			{
				txtReviewBodyText.observe('blur', Msfg$Money$Loans$onBlurRemoveAngleBrackets.bindAsEventListener(txtReviewBodyText));
    }
}
