<!--
if (globalSystemDate==undefined) {
	var globalSystemDate = new Date(); //Use client date
}


function ValidateForm() {
	if (ValidateDropDown()) {
		if (ValidateTextBoxes()) { 
			if (ValidateDates()) {
				if (ValidateRadioButtons()) {
					if (ValidateCheckboxes()) {
						if (ValidateInvalidLoan()) {
							return true;
						}
					}
				}
			}
		}
	}
	return false;
}

function AddressLessThanThreeYears() {
	if (LoanTypeIsTenant()) {
		monObj = document.loanapp.AddressMonth;
		yearObj = document.loanapp.AddressYear;
		//dtObj = document.loanapp.C1Address_Start_Date;
		if (monObj) {
			dtStr = "01/" + monObj.value + "/" + yearObj.value;
			error = IsDate(dtStr, "Address start date");
			if (!error) { //Valid date is entered
				var pos1=dtStr.indexOf(dtCh);
				var pos2=dtStr.indexOf(dtCh,pos1+1);
				var strDay=dtStr.substring(0,pos1);
				var strMonth=dtStr.substring(pos1+1,pos2);
				var strYear=dtStr.substring(pos2+1);
				
				year = parseInt(strYear, 10);
				month = parseInt(strMonth, 10);
				day = parseInt(strDay, 10);
				
				month--;//have to subtract 1 month as it is 0 based
				var threeYearDate = new Date(globalSystemDate.getFullYear()-3, globalSystemDate.getMonth(), globalSystemDate.getDate());
				var testDate = new Date(year,month,day);
				if (testDate > threeYearDate) {
					return true;
				}
			}
		}
	}
	return false;//by default return false, address date might not be visible
}

function ValidateInvalidLoan() {
	PropertyValue = parseInt(document.loanapp.PropertyValue.value, 0);
	MortgageBalance = parseInt(document.loanapp.MortgageBalance.value, 0);
	LoanAmount = parseInt(document.loanapp.LoanAmount.value, 0);
	
	if ((!LoanTypeIsTenant()) && PropertyValue == 0 && MortgageBalance == 0) {
		alert('A property value of \'0\' and a Mortgage balance of \'0\' suggest that you are not looking for a secured loan but an unsecured loan please select Tenant / Unsecured loan at the top of the form.');
		return false;
	}
	
	//70% check for secure loans now set to 80% below
	if (!LoanTypeIsTenant()) {
		SeventyPercent = Math.ceil(PropertyValue * .80);
		TotalLoan = Math.ceil(LoanAmount + MortgageBalance);
		if (TotalLoan > SeventyPercent) {
			alert("Your loan plus your mortgage balance equals (" + TotalLoan + ") which is greater than 80% (" + SeventyPercent + ") of your propery value. In the current climate 80% of your property value is the maximum loan amount to value you can acheive. Please edit your loan amount to reflect a 80% LTV(Loan To Value) by reducing the loan amount or keep your current loan amount and select Unsecured Loan from the drop down menu at the top of the form to apply for an Unsecured Loan instead.");
			return false;
		}
	}
	
	
	if (LoanTypeIsTenant() && PropertyValue > 0 && MortgageBalance > 0) {
		//Silently change loan type to secure...
		ResidentialStatusBox = MM_findObj('ResidentialStatus');
		ResidentialStatusBox.selectedIndex = 0;
	}
	
	Forename = document.loanapp.Forename.value;
	C2Forename = document.loanapp.C2Forename.value;
	Surname = document.loanapp.Surname.value;
	C2Surname = document.loanapp.C2Surname.value;
	if (Forename == C2Forename && Surname == C2Surname) {
		document.loanapp.C1Status.selectedIndex = 2;
	}
	
	
	return true;
}

function ValidateCheckboxes() {
	if (document.loanapp.term.checked == false ){
		alert('Please agree to our terms by checking the box.');
		return false;
	} else {
		return true;
	}
}
function showHide(id, selectedIndex)
{
	var block = document.getElementById(id);
	block.style.visibility = selectedIndex == 0 ? 'hidden' : 'visible';
	block.style.display = selectedIndex == 0 ? 'none' : 'block';
} 
function ShowHideArea(id, show) {
	var block = document.getElementById(id);
	block.style.visibility = show ? 'visible' : 'hidden';
	block.style.display = show ? 'block' : 'none';
}

function ShowHidePrevAddress() {
	var obj = document.loanapp.ResidentialStatus;
	if (obj.selectedIndex == 1 && AddressLessThanThreeYears()) {
		ShowHideArea('Unsecured3', true);
	} else {
		ShowHideArea('Unsecured3', false);
	}
	
}

function ShowHideSecure(obj) {
	showHide('Unsecured', obj.selectedIndex); 
	showHide('Unsecured2', obj.selectedIndex);
	showHide('Unsecured4', obj.selectedIndex); 
	ShowHidePrevAddress();
	
	//block.style.visibility = obj.selectedIndex == 0 ? 'hidden' : 'visible'; 
	//block.style.display = obj.selectedIndex == 0 ? 'none' : 'block';
	parentObj = parent.document.getElementById('appf');
	if (parentObj) {
		parentObj.getElementById('appf').style.height='1536';
	}
}
function ShowHideJointBox() {
	flag = (!IsJoint());

	block = document.getElementById('Joint'); 
	block.style.visibility = flag ? 'hidden' : 'visible'; 
	block.style.display = flag ? 'none' : 'block';
	
	parentObj = parent.document.getElementById('appf');
	if (parentObj) {
		parentObj.style.height='1690';
	}
}

function ValidateDates(){
	var dt=document.loanapp.C1DOB;
	if (ValidateDate(dt.value, "date of birth")==false){
		dt.focus();
		return false
	}
	if (IsJoint()) {
		dt=document.loanapp.C2DOB;
		if (ValidateDate(dt.value, "date of birth")==false){
			dt.focus();
			return false;
		}
	}
	//Also check for tenancy date fields
	if (LoanTypeIsTenant()) {
		dt=document.loanapp.C1Employer_Start_Date;
		if (ValidateDate(dt.value, "employed since date")==false){
			dt.focus();
			return false;
		}
		/*dt=document.loanapp.C1Address_Start_Date;
		if (ValidateDate(dt.value, "start date")==false){
			dt.focus();
			return false;
		}
		*/
		if (document.loanapp.AddressMonth.value == "" || document.loanapp.AddressYear.value == "")
		{
			alert("Please select valid date for the address.");
			document.loanapp.AddressMonth.focus();
			return false;
		}
		
// Commented out as temp fix for previous address date being required
		//if (AddressLessThanThreeYears()) {
			//if (document.loanapp.PrevAddressMonth.value == "" || document.loanapp.PrevAddressYear.value == "")
			//{
			//	alert("Please select valid date for previous address.");
			//	document.loanapp.PrevAddressMonth.focus();
			//	return false;
			//}
		//}
	}
	//C1Employer_Start_Date
	//C1Address_Start_Date
    return true;
 }

function ValidateTextBoxes() {
	var error;
	var fields;
	fields = "LoanAmount,,RinRange500:250000,Forename,,R,Surname,,R,C1DOB,,R,Email,,RisEmail,ContactTel,,RisNum,ContactTel2,,RisNum,C1AnnualIncome,,RinRange8000:100000,C1HouseNumber,,R,C1Street,,R,C1Town,,R,C1County,,R,C1Postcode,,R,PropertyValue,,RisNum,MortgageBalance,,RisNum";
	if (IsJoint()) {
		fields += ",C2Forename,,R,C2Surname,,R,C2DOB,,R,C2ContactTel,,RisNum,C2AnnualIncome,,RinRange6000:100000";
	}
	if (LoanTypeIsTenant()) {
		fields += ",EmployerName,,R";
		
// Commented out below as temporary fix for required 2nd address when not required
		
		//if (AddressLessThanThreeYears()) {
		//	fields += ",C1HouseNumber2,,R,C1Street2,,R,C1Town2,,R,C1County2,,R,C1County2,,R";
		//}
	}
	errors = ValidateTextFields(fields);
	if (errors) 
	{
	  	alert('The following error(s) occurred:\n'+errors);
		return false;
	} else {
		return true;
  	}
}



function ValidateTextFields(fields) { //Borrowed from existing application and changed
	var args = fields.split(',');
  var i,p,q,nm,test,num,min,max,errors='';
  for (i=0; i<(args.length-2); i+=3) { 
  	test=args[i+2]; 
	val=MM_findObj(args[i]);
	if (val) { 
		nm=val.name; 
		if ((val=val.value)!="") {
			if (test.indexOf('isEmail')!=-1) { 
				p=val.indexOf('@');
		        if (p<1 || p==(val.length-1)) 
					errors+='- '+nm+' must contain an e-mail address.\n';
	      } else if (test!='R') { 
		  	num = parseFloat(val);
        	if (isNaN(val)) 
				errors+='- '+nm+' must contain a number.\n';
        	if (test.indexOf('inRange') != -1) { 
				p=test.indexOf(':');
          		min=test.substring(8,p); 
				max=test.substring(p+1);
          		if (num<min || max<num) 
					errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    		} 
		} 
	} else if (test.charAt(0) == 'R') 
		errors += '- '+nm+' is required.\n'; }
  }
  return errors;
}

function ValidateDropDown() {
	var failed = false;
	if (IsJoint()) {
		if((document.loanapp.PurposeofLoan.selectedIndex == 0)
			|| (document.loanapp.C1Title.selectedIndex == 0)
			|| (document.loanapp.C1Status.selectedIndex == 0)
			|| (document.loanapp.C1EmploymentStatus.selectedIndex == 0)
			|| (document.loanapp.C2Title.selectedIndex == 0)
			|| (document.loanapp.C2Status.selectedIndex == 0)
			|| (document.loanapp.C2EmploymentStatus.selectedIndex == 0))		{
			failed = true;
		}
	} else {
		if((document.loanapp.PurposeofLoan.selectedIndex == 0)
			|| (document.loanapp.C1Title.selectedIndex == 0)
			|| (document.loanapp.C1Status.selectedIndex == 0)
			|| (document.loanapp.C1EmploymentStatus.selectedIndex == 0))		{
			failed = true;
		}
	}
	//Also check for tenant, if other fields are validated
	if (!failed) {
		if (LoanTypeIsTenant()) {
			if ( (document.loanapp.C1Occupation.selectedIndex == 0)
				|| (document.loanapp.x_PaymentType.selectedIndex == 0) 
				|| (document.loanapp.x_NumDebts.selectedIndex == 0)
				|| (document.loanapp.x_RepaymentPeriod.selectedIndex == 0)
				) {
				failed = true;
			}
		}
	}
	
	if(failed) {
		alert('You must make a selection from each drop down list.');
		return false;
	} else {
		return true;
	}
}

function ValidateRadio(obj) {
	for (counter = 0; counter < obj.length; counter++) {
		if (obj[counter].checked)
			return true; 
	}
	return false;
}

function ValidateRadioButtons() {
	if (!ValidateRadio(document.loanapp.ccj)) {
		alert("Please select Yes Or No For CCJ's.");
		return (false);
	}
	if (!ValidateRadio(document.loanapp.missed)) {
		alert("Please select Yes Or No For Missed Payments.");
		return (false);
	}
	if (!ValidateRadio(document.loanapp.bankc)) {
		alert("Please select Yes Or No For Bankruptcy Or IVA's.");
		return (false);
	}
	if (LoanTypeIsTenant()) {
		if (!ValidateRadio(document.loanapp.x_C1BACs)) {
			alert("Please select Yes Or No For bank wages paid directly into your bank account.");
			return (false);
		}
		if (!ValidateRadio(document.loanapp.x_C1DM)) {
			alert("Please select Yes Or No For debt management programme.");
			return (false);
		}
	}
	
	return (true);
}


function IsJoint() {
	NoOfClientsBox = MM_findObj('NoOfClients');
	C1StatusBox = MM_findObj('C1Status');
	if ( (NoOfClientsBox.selectedIndex != 0) || (C1StatusBox.value=='Married') || (C1StatusBox.value=='Co-habiting') ) {
		return true;
	} else {
		return false;
	}
}

function LoanTypeIsTenant() {
	ResidentialStatusBox = MM_findObj('ResidentialStatus');

	if (ResidentialStatusBox.selectedIndex != 0) {
		return true;
	} else {
		return false;
	}
}



function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

// date functions copied from existing application
function IsDate(dtStr, fieldname) {
	var msg;
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strDay=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var idob = 1; idob <= 3; idob++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		msg = "The date format for " + fieldname + " should be : dd/mm/yyyy";
	}
	if (strMonth.length<1 || month<1 || month>12){
		msg = "Please enter a valid month for " + fieldname;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		msg = "Please enter a valid day for " + fieldname;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		msg = "Please enter a valid 4 digit year between "+minYear+" and "+maxYear + " for " + fieldname;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		msg = "Please enter a valid date for " + fieldname;
	}
	return msg;
}

function ValidateDate(dtStr, fieldname){
	var error = IsDate(dtStr, fieldname);
	if (error) {
		alert(error);
		return false;
	} else {
		return true;
	}
}





// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(sdob){
	var idob;
    for (idob = 0; idob < sdob.length; idob++){   
        // Check that current character is number.
        var cdob = sdob.charAt(idob);
        if (((cdob < "0") || (cdob > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(sdob, bag){
	var idob;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (idob = 0; idob < sdob.length; idob++){   
        var cdob = sdob.charAt(idob);
        if (bag.indexOf(cdob) == -1) returnString += cdob;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(ndob) {
	for (var idob = 1; idob <= ndob; idob++) {
		this[idob] = 31
		if (idob==4 || idob==6 || idob==9 || idob==11) {this[idob] = 30}
		if (idob==2) {this[idob] = 29}
   } 
   return this
}


function removeSpaces(string) {
	var tstring = "";
	string = '' + string;
	splitstring = string.split(" ");
	for(rs = 0; rs < splitstring.length; rs++)
	tstring += splitstring[rs];
	return tstring;
}
//-->
