var msfgDebtSolutions$MailCheck = new RegExp("[A-Za-z0-9_\\-\\.]+@(([A-Za-z\\-0-9])+\\.)+([A-Za-z\\-]){2,3}\\.?([A-Za-z\\-])?");

function MsfgDebtSolution$checkDebtSolution(sender, args) {
	var chkListControl = $(sender.debtSolution);
	var hidDebtConsolidationPath = document.getElementById('ucHomePageContent_hidDebtConsolidationPath');
	var chlDebtConsolidationView = document.getElementById(hidDebtConsolidationPath.value + '_0')
	
	args.IsValid = !(!chkListControl.childNodes[0].checked && !chlDebtConsolidationView.checked);
}

function MsfgDebtSolutions$AddReviewInit(emailFieldId) {
	var emailField = $get(emailFieldId);
	var rateAlertField = $get((emailField.rateAlertFieldId || ""));
	if (emailField && rateAlertField) 
	{
		rateAlertField.disabled = true;
		$addHandler(emailField, "keyup", MsfgDebtSolution$AddReviewSyncEmailRegisterRateAlert);
		$addHandler(emailField, "blur", MsfgDebtSolution$AddReviewSyncEmailRegisterRateAlert);
	}
}

function MsfgDebtSolution$AddReviewSyncEmailRegisterRateAlert(eventDetail) {
	var emailField = eventDetail.rawEvent.srcElement ? eventDetail.rawEvent.srcElement : eventDetail.rawEvent.target;
	if (emailField && emailField.rateAlertFieldId) 
	{
		var rateAlertField = $get(emailField.rateAlertFieldId);
		if (rateAlertField) 
		{
			rateAlertField.disabled = !(emailField.value.match(msfgDebtSolutions$MailCheck));
			if (rateAlertField.disabled)
				rateAlertField.checked = false;
		}
	}
}


var msfgProducts$PostCodeRegex = new RegExp("^((([A-PR-UWYZa-pr-uwyz])([0-9][0-9A-HJKS-UWa-hjks-uw]?)\\s{0,1}(([0-9])([ABD-HJLNP-UW-Zabd-hjlnp-uw-z])([ABD-HJLNP-UW-Zabd-hjlnp-uw-z])))|(([A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y])([0-9][0-9ABEHMNPRV-Yabehmnprv-y]?))\\s{0,1}(([0-9])([ABD-HJLNP-UW-Zabd-hjlnp-uw-z])([ABD-HJLNP-UW-Zabd-hjlnp-uw-z])))|(((GIgi)(Rr))\\s{0,1}((0)(Aa)(Aa)))$");

function MsfgProductsDebt$StripUnsafeCharsAll(sender, args) {
	if (sender && typeof sender.fieldsAffected != "undefined") {
		var fields = eval(sender.fieldsAffected);
		for (var i = 0, max = fields.length - 1; i < max; i++) {
			MsfgProductsDebt$StripUnsafeChars(fields[i]);
		}
	}
}

function MsfgProductsDebt$StripUnsafeChars(fieldId) {
	var field = $(fieldId);
	if (field && field.value && field.value.length > 0) {
		var replaceRgx = new RegExp("[\\/<>]", "g");
		field.value = field.value.replace(replaceRgx, "");
	}
}

function FindFirstChildOfType(parent, type, confirmDelegate) {
	var nodes = parent.childNodes;
	var result = null;
	
	if (nodes && nodes.length > 0) {
		for (var i = 0; i < nodes.length && result == null; i++) {
			var node = nodes[i];
			if (node.tagName == type) {
				if (confirmDelegate == null || (typeof confirmDelegate == "function" && confirmDelegate(node))) {
					result = node;
				}
			}
		}
	}
	
	return result;
}

function MsfgProductsDebt$HideAllToolTips(sender, args) {
	var images = document.getElementsByTagName('img');
	
	for (var i = 0, max = images.length; i < max; i++) {
		var image = images[i];
		if (image.className == "msfg-helpimg") {
			var helpIcon = image.id;
			var helpLayer = $get(helpIcon.replace(/HelpIcon/, 'HelpLayer'));
			
			Msfg$closeHelp(helpLayer, image);					
		}
	}
}

function MsfgProductsDebt$AgeValidator(sender, args) {
	// Function to validate the age of the applicant against the option selected on
	var container = $get(sender.container);

	for (var i = 0, max = container.childNodes.length; i < max; i++) {
		if (container.childNodes[i].tagName == "SELECT" || container.childNodes[i].tagName == "INPUT") {
			var embeddedControl = container.childNodes[i].name;
			
			if (embeddedControl.match('Day')) {
				var dayOfBirth = container.childNodes[i].value;
			} else if (embeddedControl.match('Month')) {
				var monthOfBirth = container.childNodes[i].value;
			} else if (embeddedControl.match('Year')) {
				var yearOfBirth = container.childNodes[i].value;
			}
		}
	}	
			
	if (args.Value == 7 && dayOfBirth.selectedIndex != 0) {
		var dateOfBirth = dayOfBirth + '/' + monthOfBirth + '/' + yearOfBirth;
		var now = new Date();
		var age;
		
		dateOfBirth = dateOfBirth.split('/');
		dateOfBirth = new Date(dateOfBirth[2], dateOfBirth[1] * 1 - 1, dateOfBirth[0]);
		
		age = Math.floor((now.getTime() -  dateOfBirth.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
		
		if (age >= 55) {
			return;			
		} else {
			args.IsValid = false;
		}
	}
}

function SetManualAddressVisibility(control, visible) {
	control = $(control);
	if (control) {
		control.style.display = visible ? "block" : "none";
	}
}

function MsfgProductsDebt$AddressSearchValidate(sender, args) {
	/* Requires the following properties on the sender (validator):
		- type: auto|manual - if the user is manually entering address details, or if the standard search is being used.
		- postCodeFieldId: the client id of the textbox used to accept post code fields. Not used in manual mode.
		- hiddenFieldId: used to validate when the user selects an address. Not be used in manual mode.
		- postcodeMandatory: message to display when the user hasn't entered a postcode. Default error message.
		- addressNotSelected: message to display when the user has provided a valid postcode (with matches), but has not 
			selected an address.
		- invalidPostcode: message to display when the user has provided a badly formatted postcode.
	*/
	args.IsValid = true;
	
	if (MsfgProductsDebt$AddressSearchValidate_CheckArgs(sender)) {
		sender.errormessage = sender.postcodeMandatory;
		if (sender.type == "auto") {
			var postCode = $(sender.postCodeFieldId).value.trim();
			var isValidPostCode = postCode.match(msfgProducts$PostCodeRegex);
			var hasProvidedPostcode = postCode.length > 0;
			
			var innerValidator = { container: "ucDebtLeadContent_adPostcode_adPostcode_ctl02" };		// Server-side validator "container".
			Msfg$validationHighlighterRemoveErrorMessage(innerValidator);
			
			if (hasProvidedPostcode && !isValidPostCode) {
				sender.errormessage = sender.invalidPostcode;
				args.IsValid = false;
			} else {
				var hasSelectedAddress = eval($(sender.hiddenFieldId).value);
				
				if (hasProvidedPostcode & !hasSelectedAddress) {
					sender.errormessage = sender.addressNotSelected;
				}
				
				args.IsValid = hasProvidedPostcode && hasSelectedAddress;
			}
		}
	}
}

function MsfgProductsDebt$AddressSearchValidate_CheckArgs(sender) {
	return (sender && typeof sender.type == "string"
		&& typeof sender.postCodeFieldId == "string"
		&& typeof sender.hiddenFieldId == "string"
		&& typeof sender.postcodeMandatory == "string"
		&& typeof sender.addressNotSelected == "string"
		&& typeof sender.invalidPostcode == "string");
}

function MsfgProductsDebt$IsValidationTargetVisible(validator) {
	// Recurses up the element hierarchy checking for field visibility.
	var result = true;
	var field = $(validator.controltovalidate);
	if (field && field.parentNode) {
		var stack = new Array();
		stack.push(field);
		
		while (stack.length > 0 && result) {
			var item = stack.pop();
			
			if (item.style && item.style.display == "none") {
				result = false;
			} else if (item.parentNode != null) {
				stack.push(item.parentNode);
			}
		}
	}
	return result;
}

function MsfgProductsDebtLead$RequiredFieldValidate(sender, args) {
	args.IsValid = true;		// Default validation to the server.
	if (MsfgProductsDebt$IsValidationTargetVisible(sender)) {
		args.IsValid = (ValidatorTrim(args.Value || "") != "");
	}
}

function MsfgProductsDebtLead$PostcodeValidate(sender, args) {
	MsfgProductsDebtLead$RequiredFieldValidate(sender, args);
	
	if (args.IsValid && (args.Value || "").length > 0) {
		var validationRegex = new RegExp("^((([A-PR-UWYZa-pr-uwyz])([0-9][0-9A-HJKS-UWa-hjks-uw]?)\\s{0,1}(([0-9])([ABD-HJLNP-UW-Zabd-hjlnp-uw-z])([ABD-HJLNP-UW-Zabd-hjlnp-uw-z])))|(([A-PR-UWYZa-pr-uwyz][A-HK-Ya-hk-y])([0-9][0-9ABEHMNPRV-Yabehmnprv-y]?))\\s{0,1}(([0-9])([ABD-HJLNP-UW-Zabd-hjlnp-uw-z])([ABD-HJLNP-UW-Zabd-hjlnp-uw-z])))|(((GIgi)(Rr))\\s{0,1}((0)(Aa)(Aa)))$");
		args.IsValid = ValidatorTrim(args.Value || "").match(validationRegex);
		sender.errormessage = sender.InvalidPostCodeMessage;
	} else {
		sender.errormessage = sender.RequiredPostCodeMessage;
	}
}

var forceHiddenFieldUpdateCounter = 0; // This variable is used in the following method to avoid getting stuck in a recursive loop.

function MsfgProductsDebtLead$ForceHiddenFieldUpdate(){
    // This method calls the helper methods to hide/display the adverse credit and current lender fields. This is 
    // required by the Safari browser when it autofills the form with cached field values. The browser populates the 
    // values without the custom validators being called, therefore always leaving the hidden fields hidden.
    // This method is called by a startup script in the lead form after a small time delay.
    
    var amountDebtControl = $get('ucDebtLeadContent_decitmAmtDebt');
	var aboutYouControl = $get('ucDebtLeadContent_pnlAboutYou');
	
	if (amountDebtControl == null || aboutYouControl == null) {
        // We don't have the parameters we need, or they aren't in the expected structure
       
        // Wait for the controls to be created. Wait for a fraction of a second and call this method again.
        if(forceHiddenFieldUpdateCounter < 50)
        {
            forceHiddenFieldUpdateCounter++; 
            setTimeout('MsfgProductsDebtLead$ForceHiddenFieldUpdate()' , 100);
        }
        // Give up if the controls still aren't available after a number of attempts.
        return; 
    }  
}

