// JavaScript Document

//####################################################################################
function compare_to_applyInternal(){
	//$("div_compareunsecured").resize({delay:0,to:{width:0,height:391}},function(){
	//$("div_yourdetails").resize({delay:0,to:{width:453,height:391}});
	//});
	document.getElementById("div_compareunsecured").style.display='none';
	document.getElementById("div_comparesecured").style.display='none';
	document.getElementById("div_yourdetails").style.display='block';
	
	document.getElementById("sel_app1_title").focus();
	window.scroll(0,0);
}

//####################################################################################
function compare_to_applyExternal(){
	//$("div_compareunsecured").resize({delay:0,to:{width:0,height:391}},function(){
	//$("div_yourdetails").resize({delay:0,to:{width:453,height:391}});
	//});
	document.getElementById("div_compareunsecured").style.display='none';
	document.getElementById("div_comparesecured").style.display='none';
	document.getElementById("div_yourdetails").style.display='block';

	document.getElementById("div_whathappensnext_external").style.display='block';
	document.getElementById("div_links").style.display='none';

	document.getElementById("sel_app1_title").focus();
	window.scroll(0,0);

	//document.getElementById("div_yourdetails").style.width='360px';
	//document.getElementById("div_whathappensnext_external").style.width='347px';
}

//####################################################################################
function apply_to_compare(){
	//$("div_yourdetails").resize({delay:0,to:{width:0,height:391}},function(){
	//$("div_compareunsecured").resize({delay:0,to:{width:453,height:391}});
	//});
	document.getElementById("div_yourdetails").style.display='none';
	document.getElementById("div_compareunsecured").style.display='block';
	document.getElementById("div_comparesecured").style.display='block';
	
	if(document.getElementById("hid_destination").value == "external"){
		document.getElementById("div_whathappensnext_external").style.display='none';
		document.getElementById("div_links").style.display='block';
	}
}



//####################################################################################
function reset4(){
$("ad4").resize({delay:300,to:{width:0,height:391}},function(){
$("div_compareunsecured").resize({delay:300,to:{width:400,height:391}});
});
}


//####################################################################################
function test5(){

$("box5").resize({delay:300,to:{width:0}},function(){
$("ad5").resize({delay:300,to:{width:400}});

});
}

//####################################################################################
function reset5(){
$("box5").resize({delay:300,to:{width:400}});

}


//####################################################################################
function movepic(img_name,img_src) {
	document[img_name].src=img_src;
}

//####################################################################################
function setjustcreated()
{
	document.getElementById("hid_just_created").value = "Yes";
}
//####################################################################################
function div_swap(div_hide, div_show, validate)
{
	var app1YearsAtCurrentAddress = document.getElementById("inp_timeataddress_years").value;
	var app2YearsAtCurrentAddress = document.getElementById("inp_app2_timeataddress_years").value;

	var app1YearsAtCurrentEmployment = document.getElementById("inp_app1_timeatemploymentyears").value;
	var app2YearsAtCurrentEmployment = document.getElementById("inp_app2_timeatemploymentyears").value;
	
	var strappid = "";

	// Applicant 1 personal Details
	if(div_hide == 'div_yourdetails_1'){
		if (document.getElementById("hid_destination").value == 'external'){
			if (validatediv_yourdetails_1()){
				document.getElementById("pop_grossincome").value = document.getElementById("inp_grossincome").value;
				document.getElementById("pop_propertyValue").value = document.getElementById("inp_propertyValue").value;
				document.getElementById("pop_mortgageBalance").value = document.getElementById("inp_mortgageBalance").value;
				
				document.getElementById("current_housename").value = document.getElementById("current_app1_housename1").value;
				document.getElementById("current_postcode").value = document.getElementById("current_app1_postcode1").value;
	
				extURL = document.getElementById("hid_destination_url").value;
				// Submit Form to write customer details to database + Open the provider website			
				document.form1.submit();
				//location.href=extURL;		
			}
		}
		else{	
			if (validatediv_yourdetails_1()){
				strforename = document.getElementById("inp_app1_forename").value;
				strsurname = document.getElementById("inp_app1_surname").value;
				strdateOfBirth = document.getElementById("inp_app1_dob").value;
				strcurrentAddress_postcode = document.getElementById("current_app1_postcode1").value;
				
				var dob_array = strdateOfBirth.split("/");
				strdateOfBirth = dob_array[2] + "-" + dob_array[1] + "-" + dob_array[0];
				
				if(document.getElementById("hid_just_created").value != "Yes"){ // Only check for duplicate if the app has notjust  been created. Required due to the back button from the second div
					strappid = ajax_check_duplicate(strforename, strsurname, strdateOfBirth, strcurrentAddress_postcode);
				}
				pause(1500);
				strexistingappid = document.getElementById("hid_prev_appid").value;

					if(validateCriteria()){
						//if not duplicate
						if(strexistingappid ==''){
							postcodesearch('current_app1_postcode1', 'current','current_postcode','current_housename','current_app1_housename1', 'current_flatno');
							
							// Blank and Disable the current_postcode1 and current_housename1 fields
							document.getElementById("current_app1_postcode1").value = "";
							document.getElementById("current_app1_postcode1").disabled = true;
							document.getElementById("current_app1_postcode1").style.background='#c0c0c0';
							
							document.getElementById("current_app1_housename1").value = "";
							document.getElementById("current_app1_housename1").disabled = true;
							document.getElementById("current_app1_housename1").style.background='#c0c0c0';
							
							//Populate display fields further down the app
							// Only populate income if was single so as not to confuse the customer
							if(document.getElementById("sel_applicationType").value == "Single"){
								document.getElementById("pop_grossincome").value = document.getElementById("inp_grossincome").value;
							}
							document.getElementById("pop_propertyValue").value = document.getElementById("inp_propertyValue").value;
							document.getElementById("pop_mortgageBalance").value = document.getElementById("inp_mortgageBalance").value;
							
					
							//Focus on Property Type field
							document.getElementById(div_hide).style.display='none';
							document.getElementById(div_show).style.display='block';
							document.getElementById("sel_PropertyType").focus();
						}
						//Duplicate
						else{
							chk_ApplicationDuplicate(strexistingappid);
						}
					}
					else{
						//alert('Failed Criteria');
						chk_CriteriaDecline();
						document.getElementById("hid_destination").value = "failedcriteria";
						//document.form1.submit();
					}
			}
		}
		
	}
	//Applicant 1 Residential Details
	else if (div_hide == 'div_yourdetails_2'){
		if(validate){
			if (validatediv_yourdetails_2()){
				document.getElementById(div_hide).style.display='none';
				// If Time At Current Address < 3 Years show Previous Address Details
				if(app1YearsAtCurrentAddress < 3 && div_show == 'div_yourdetails_3'){
					document.getElementById("div_yourdetails_2a").style.display='block';
				}
				else{
					document.getElementById(div_show).style.display='block';
				}
			}
		}
		else{
			document.getElementById(div_hide).style.display='none';
			// If going BACK and Time At Current Address < 3 Years show Previous Address Details
			if(app1YearsAtCurrentAddress < 3 && div_show == 'div_yourdetails_3'){	
				document.getElementById("div_yourdetails_2a").style.display='block';
			}
			else{
				document.getElementById(div_show).style.display='block';
			}
		}
	}
	
	//Applicant 1 Previous Residential Details
	else if (div_hide == 'div_yourdetails_2a'){
		if(validate){
			if (validatediv_yourdetails_2a()){
				document.getElementById(div_hide).style.display='none';
				document.getElementById(div_show).style.display='block';
			}
		}
		else{
				document.getElementById(div_hide).style.display='none';
				document.getElementById(div_show).style.display='block';
		}	}

	//applicant 1 Employment Detials
	else if (div_hide == 'div_yourdetails_3'){
		if(validate){
			if (validatediv_yourdetails_3()){
				if(document.getElementById("sel_applicationType").value == "Joint"){
					document.getElementById(div_hide).style.display='none';
					// If going BACK and Time At Current Address < 3 Years show Previous Address Details
					if(app1YearsAtCurrentAddress < 3 && div_show == 'div_yourdetails_2'){
						document.getElementById("div_yourdetails_2a").style.display='block';
					}
					// If going NEXT and Time At Current Employment < 3 Years show Previous Employment Details
					else if (app1YearsAtCurrentEmployment < 3 && div_show == 'div_yourdetails_4'){
						document.getElementById("div_yourdetails_3a").style.display='block';
					}
					else{
						document.getElementById(div_show).style.display='block';
					}
				}
				else{
					document.getElementById(div_hide).style.display='none';
					// If going BACK and Time At Current Address < 3 Years show Previous Address Details
					if(app1YearsAtCurrentAddress < 3 && div_show == 'div_yourdetails_2'){
						document.getElementById("div_yourdetails_2a").style.display='block';
					}
					// If going NEXT and Time At Current Employment < 3 Years show Previous Employment Details
					else if (app1YearsAtCurrentEmployment < 3 && div_show == 'div_yourdetails_4'){
						document.getElementById("div_yourdetails_3a").style.display='block';
					}
					else{
						document.getElementById("div_yourdetails_8").style.display='block';
					}
				}
			}
		}
		else{
				document.getElementById(div_hide).style.display='none';
				// If going BACK and Time At Current Address < 3 Years show Previous Address Details
				if(app1YearsAtCurrentAddress < 3 && div_show == 'div_yourdetails_2'){
					document.getElementById("div_yourdetails_2a").style.display='block';
				}
					// If going NEXT and Time At Current Employment < 3 Years show Previous Employment Details
					else if (app1YearsAtCurrentEmployment < 3 && div_show == 'div_yourdetails_4'){
						document.getElementById("div_yourdetails_3a").style.display='block';
					}
				else{
					document.getElementById(div_show).style.display='block';
				}
		}
	}
	//applicant 1 Previous Employment Detials
	else if (div_hide == 'div_yourdetails_3a'){
		if(validate){
			if (validatediv_yourdetails_3a()){
				if(document.getElementById("sel_applicationType").value == "Joint"){
					document.getElementById(div_hide).style.display='none';
					document.getElementById(div_show).style.display='block';
				}
				else{
					document.getElementById(div_hide).style.display='none';
					document.getElementById("div_yourdetails_8").style.display='block';
				}
			}
		}
		else{
				document.getElementById(div_hide).style.display='none';
				// If going BACK and Time At Current Address < 3 Years show Previous Address Details
				if(app1YearsAtCurrentAddress < 3 && div_show == 'div_yourdetails_2'){
					document.getElementById("div_yourdetails_2a").style.display='block';
				}
					else if (app1YearsAtCurrentEmployment < 3 && div_show == 'div_yourdetails_4'){
						document.getElementById("div_yourdetails_3a").style.display='block';
					}
				else{
					document.getElementById(div_show).style.display='block';
				}
		}
	}	
	
	// Applicant 2 personal Details
	else if (div_hide == 'div_yourdetails_4'){
		if(validate){
			if (validatediv_yourdetails_4()){
				document.getElementById(div_hide).style.display='none';
				document.getElementById(div_show).style.display='block';
			}
		}
		else{
				document.getElementById(div_hide).style.display='none';
				document.getElementById(div_show).style.display='block';
		}
	}
	
	//Applicant 2 Residential Details
	else if (div_hide == 'div_yourdetails_5'){
		if(validate){
			if (validatediv_yourdetails_5()){
				document.getElementById(div_hide).style.display='none';
				// If Time At Current Address < 3 Years show Previous Address Details
				if(app2YearsAtCurrentAddress < 3 && div_show == 'div_yourdetails_6'){
					document.getElementById("div_yourdetails_5a").style.display='block';
				}
				else{
					document.getElementById(div_show).style.display='block';
				}			}
		}
		else{
				document.getElementById(div_hide).style.display='none';
				document.getElementById(div_show).style.display='block';
		}
	}
	
	
	//Applicant 2 previous Residential Details
	else if (div_hide == 'div_yourdetails_5a'){
		if(validate){
			if (validatediv_yourdetails_5a()){
				document.getElementById(div_hide).style.display='none';
				document.getElementById(div_show).style.display='block';
			}
		}
		else{
				document.getElementById(div_hide).style.display='none';
				document.getElementById(div_show).style.display='block';
		}
	}			

	
	//Applicant 2 Employment Details
	else if (div_hide == 'div_yourdetails_6'){
		if(validate){
			if (validatediv_yourdetails_6()){
				document.getElementById(div_hide).style.display='none';
					// If going NEXT and Time At Current Address < 3 Years show Previous Address Details
					if (app2YearsAtCurrentEmployment < 3 && div_show == 'div_yourdetails_8'){
						document.getElementById("div_yourdetails_6a").style.display='block';
					}	
					// If going BACK and Time At Current Address < 3 Years show Previous Address Details
					else if (app2YearsAtCurrentAddress < 3 && div_show == 'div_yourdetails_5'){
						document.getElementById("div_yourdetails_5a").style.display='block';
					}
					else{
						document.getElementById(div_show).style.display='block';
					}				
			}
		}
		else{
				document.getElementById(div_hide).style.display='none';
					// If going NEXT and Time At Current Address < 3 Years show Previous Address Details
					if (app2YearsAtCurrentEmployment < 3 && div_show == 'div_yourdetails_8'){
						document.getElementById("div_yourdetails_6a").style.display='block';
					}	
					// If going BACK and Time At Current Address < 3 Years show Previous Address Details
					else if (app2YearsAtCurrentAddress < 3 && div_show == 'div_yourdetails_5'){
					document.getElementById("div_yourdetails_5a").style.display='block';
				}
				else{
					document.getElementById(div_show).style.display='block';
				}		
			}
	}	
	
	
	//Applicant 2 previous Employment Details
	else if (div_hide == 'div_yourdetails_6a'){
		if(validate){
			if (validatediv_yourdetails_6a()){
				document.getElementById(div_hide).style.display='none';
				document.getElementById(div_show).style.display='block';
			}
		}
		else{
				document.getElementById(div_hide).style.display='none';
				document.getElementById(div_show).style.display='block';
		}
	}			
	
	
	//Loan Details
	else if (div_hide == 'div_yourdetails_8'){
		document.getElementById(div_hide).style.display='none';
		// If Joint Application
		if(document.getElementById("sel_applicationType").value == "Joint"){
			if (app2YearsAtCurrentEmployment < 3){
				document.getElementById("div_yourdetails_6a").style.display='block';
			}
			else{
				document.getElementById("div_yourdetails_6").style.display='block';
			}		
		}
		// else Single App
		else{
			if (app1YearsAtCurrentEmployment < 3){
				document.getElementById("div_yourdetails_3a").style.display='block';
			}
			else{
				document.getElementById("div_yourdetails_3").style.display='block';
			}		
		}
	}


	else{
		document.getElementById(div_hide).style.display='none';
		document.getElementById(div_show).style.display='block';
	}

}

//####################################################################################
function chk_debtCalculator()
  {
	sumofdebts = document.getElementById("inp_sumofdebts").value;
	extrarequired = document.getElementById("inp_extrarequired").value;
	currentmonthlycommittment = document.getElementById("inp_currentmonthlycommittment").value;
	loanapprovallsapr = document.getElementById("hid_loanapprovallssec").value;

	A = (sumofdebts*1) + (extrarequired*1);
	T = 5;

	R = loanapprovallsapr / 100;
	var P = ((A*R)/12) * (1/(1-(Math.pow(1/(1+R),T))));
	var saving = currentmonthlycommittment - P;
	saving = poundsPence(saving)


	if (P > 0){
		if (P < currentmonthlycommittment){
			// Display div in center of the screen showing how much can save ????
			document.getElementById("html_debtcalc_result").innerHTML = "From what you've told us, your monthly commitments could be as low as <strong>£" +  poundsPence(P) + '</strong> <br/><br/>This could possibly save you up to <strong>£' + saving + '</strong> every month.<br/><br/>These figures are only approximations. To find out exactly how much you could save each month please click on the Tick to continue with an application';
			document.body.scroll='no';
			document.body.style.overflow = 'hidden';
			document.getElementById("PopupResultDiv").style.display='block';
			document.getElementById("PopupResultDivContainer_header").src="images/DebtCalculator.png";
			document.getElementById("PopupResultDiv_buttons").style.display='block';
			document.getElementById("PopupResultDiv_buttons_close").style.display='none';
			document.getElementById("html_debtcalc_result").style.fontSize='17px';
			window.scroll(0,0);

		}
		else{
		document.getElementById("html_debtcalc_result").innerHTML = "From what you have told us, your extra funding could cost you as little as <strong>£" + (0-saving)  +'</strong> extra per month.<br/><br/>These figures are only approximations. To find out exactly how much you could save each month please click on the Tick to continue with an application';
		
		//alert('Unfortunately we cannot save you any money');
			document.body.scroll='no';
			document.body.style.overflow = 'hidden';
			document.getElementById("PopupResultDiv").style.display='block';
			document.getElementById("PopupResultDivContainer_header").src="images/DebtCalculator.png";
			document.getElementById("PopupResultDiv_buttons").style.display='block';
			document.getElementById("PopupResultDiv_buttons_close").style.display='none';
			document.getElementById("html_debtcalc_result").style.fontSize='17px';
			window.scroll(0,0);
		}
	}
	else{
		alert('Please enter values into the above fields');
	}
  }

//####################################################################################
function chk_CriteriaDecline()
 {
		document.getElementById("html_debtcalc_result").innerHTML = "<br/>Your application has been rejected as the information you have provided does not meet the <a href='#' onclick=\"document.getElementById(\'iframe_criteria\').style.display=\'block\';\">minimum criteria</a>. <br/><br/>However, please call us as one of our experts may be able to assist you. <br/><br/>Call now on 0844 4 10 60 61 to find out if we can help you.";
		
		//alert('Unfortunately we cannot save you any money');
			document.body.scroll='no';
			document.body.style.overflow = 'hidden';
			document.getElementById("PopupResultDiv").style.display='block';
			document.getElementById("PopupResultDivContainer_header").src="images/Application_Reject_heading.png";
			document.getElementById("PopupResultDiv_buttons").style.display='none';
			document.getElementById("PopupResultDiv_buttons_close").style.display='block';
			window.scroll(0,0);	 
 }
 
 //####################################################################################
function chk_ApplicationAIP(strAppRef)
 {
		//document.getElementById("html_debtcalc_result").innerHTML = "Your application has been rejected. <br/><br/>However, please call us as one of our experts may be able to assist. <br/><br/>Call now on 0844 4 10 60 61 to find out if we can help you.";
		
			document.body.scroll='no';
			document.body.style.overflow = 'hidden';
			document.getElementById("PopupAIPDiv").style.display='block';
			document.getElementById("PopupResultDivContainer_header").src="images/Application_Reject_heading.png";
			document.getElementById("PopupResultDiv_buttons").style.display='block';
			document.getElementById("span_appref").innerHTML = strAppRef;
			window.scroll(0,0);	 
 }
  //####################################################################################
function chk_ApplicationDuplicate(strAppRef)
 {		
			document.body.scroll='no';
			document.body.style.overflow = 'hidden';
			document.getElementById("PopupAIPDiv").style.display='block';
			document.getElementById("PopupResultDivContainer_header").src="images/Application_Reject_heading.png";
			document.getElementById("PopupResultDiv_buttons").style.display='block';
			document.getElementById("span_appref").innerHTML = strAppRef;
			document.getElementById("html_decline").innerHTML ="Thank you very much. We already have your details on our system from a previous application you made.<br/><br/>Please call us on 0844 4 10 60 62 as soon as possible to discuss this.<br/><br/>Please quote Reference Number:- " + strAppRef + "<br/><br/>Thank you ";			
			window.scroll(0,0);	 
 }
//####################################################################################
function goApplyPopupResultDiv()
{
	document.getElementById("PopupResultDiv").style.display='none';
	document.body.scroll='yes';
	document.body.style.overflow = 'scroll';
	//copy and set application fields
	// Loan Value, type, provider (loan approvalls)
	sumofdebts = document.getElementById("inp_sumofdebts").value;
	extrarequired = document.getElementById("inp_extrarequired").value;
	totalamountrequired = sumofdebts*1 + extrarequired*1;

	document.getElementById("hid_destination").value = "internal";
	document.getElementById("hid_amount").value = totalamountrequired;

	document.getElementById("sel_PurposeOfLoan").value = "Debt Consolidation";
	document.getElementById("inp_chosenAmount").value = totalamountrequired;
	document.getElementById("inp_chosenTerm").value = "5";
	document.getElementById("inp_chosenLoanType").value = "Secured";
	document.getElementById("inp_chosenProvider").value = "Loan Approvalls";
	
	compare_to_applyInternal();
}

//####################################################################################
function cancelPopupResultDiv()
{
	document.getElementById("PopupResultDiv").style.display='none';
	document.getElementById("PopupResultDivContainer_header").src="images/DebtCalculator.png";
	document.body.scroll='yes';
	document.body.style.overflow = 'scroll';
}
//####################################################################################
function cancelPopupAIPDiv()
{
	document.getElementById("PopupAIPDiv").style.display='none';
	document.body.scroll='yes';
	document.body.style.overflow = 'scroll';
}
//##########################################
//checks that data are valid
function checkNumber(input, min, max, msg) {
	input = document.getElementById(input);

	msg = msg + " field has invalid data: " + input.value;

	//this makes sure that the number is a number
	var str = input.value;
	var strname = input.name;
	for (var i = 0; i < str.length; i++) {
		var ch = str.substring( i, i + 1)
		if ((ch < "0" || "9" < ch) && ch != '.') {
			alert(msg);
			alert(strname);
			return false;
		}
	}

	//this makes sure that the number lies between the min and max values allowed
	var num = 0 + str
	if (num < min || max < num) {
		//alert(msg + " not in range [" + min + ".." + max + "]");
		return false;
	}
	input.value = str;
	return true;
}

//####################################################################################
function computeField(input, rownum, min, max) {
	if (input.value != null && input.value.length != 0)
	{
		input.value = "" + eval(input.value);
	}
	computeForm(input.form, input.name, rownum, min, max);
}


//###########################################################
function computeForm(form, field, rownum, min, max) {

// A - Loan amount
// T - Term
// R - Rate
//CMM - Monthly Payment

	var AA = 'A' + rownum;
	var TT = 'T' + rownum;
	var RR = 'R' + rownum;
	var CMM = 'Cm' + rownum;
	var Ill = 'Ill' + rownum;

	var fldname = field.substring(0,1);

	var A=document.getElementById(AA).value;
	var T=document.getElementById(TT).value;
	var R=document.getElementById(RR).value;

 if ((A == null || A == 0) ||
     (T == null || T == 0)
||
     (R == null || R == 0))
 { //document.calc.pay.value = "Incomplete data";
 }
 else
 {
 var princ = A;
 var term  = T*12
 var intr   = R / 1200;
 P = princ * intr / (1 - (Math.pow(1/(1 + intr), term)));
 document.getElementById(CMM).value = poundsPence(P);
 
TR = P*term;
TR = TR.toFixed(2);	

 var illustration = 'The total amount payable is £' + TR + '. The illustrative cost of borrowing £' + princ+ ' over ' + T + ' years at the representitive rate of ' + R + '% APR';
 document.getElementById(Ill).innerHTML = illustration;
 }

// payment = principle * monthly interest/(1 - (1/(1+MonthlyInterest)*Months))

}
//#######################
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)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

//########################################################################
// Deprecated - Replaaced by computeForm(form, field, rownum, min, max) {
function _computeForm(form, field, rownum, min, max) {
	var AA = 'A' + rownum;
	var TT = 'T' + rownum;
	var RR = 'R' + rownum;
	var CMM = 'Cm' + rownum;

	var fldname = field.substring(0,1);

	var A=document.getElementById(AA).value;
	var T=document.getElementById(TT).value;
	var R=document.getElementById(RR).value;

	//making sure that an entry has been made in each field.
	if ((A == null || A.length == 0) ||
		(R == null || R.length == 0))
	{
		//alert('not all fields filled in');
		return;
	}

	if (fldname == "A"){
		// making sure that entries are valid by using check number
		if (!checkNumber(AA, min, max, "Amount"))
		{
			document.getElementById(CMM).value = "";
			//checkStatusUnsec('Unsecured', A, '60');
			return;
		}
	}
	else if (fldname == "T"){
		// making sure that entries are valid by using check number
		if (!checkNumber(TT, min, max, "Months"))
		{
			document.getElementById(CMM).value = "";
			return;
		}
	}

	// maths et al to be computed
	R = R / 100;
	var P = ((A*R)/12) * (1/(1-(Math.pow(1/(1+R),T))));

	// If Repayment is a valid number then write to field
	if(P != 'Infinity'){
		document.getElementById(CMM).value = poundsPence(P);
	}

	//P = ((A*0.12)/12) * (1 / (1-(Math.pow((1/1.12),T))));
	//form.CCm.value = poundsPence( P );
	//P = (A*R)/12;
	//NickB//form.CI.value = poundsPence(P);
	//P = (A*0.12)/12;
	//form.CCI.value = poundsPence(P);
}

//####################################################################################
function poundsPence(N) {
	// dont try this with ie3 because its rubbish
	if ((navigator.appName.indexOf('Microsoft')>-1) && (navigator.appVersion.indexOf('3.0')>-1) )
	{
//		alert('boo');
//		return N;
	}
	S = new String(N);
	var i = S.indexOf('.');
	if (i != -1) {
		S = S.substr( 0, i+3 );
		if (S.length-i < 3)
			S = S + '0';
	}
	return S;
}

//clears form
//####################################################################################
function clearForm(form) {
	form.A.value = "";
	form.T.value = "";
	form.R.value = "";
}

//####################################################################################
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

//####################################################################################
function confirmfilterchange(loantype, loanamount, loanterm, minterm, maxterm, minamount, maxamount, destination, destination_url, lender)
{
loanterm = document.form1.hid_term.value;
loanamount = document.form1.hid_amount.value;
	if (loanamount == '' || loanterm == ''){
		alert('Please enter your required Loan Amount and Loan Term');
	}
	else{
		if(minamount*1 <= loanamount*1  && maxamount*1  >= loanamount*1  && minterm*1 <= loanterm*1  && maxterm*1  >= loanterm*1  ){
			//alert('OK');
			document.getElementById("hid_destination").value = destination;
			document.getElementById("hid_destination_url").value = destination_url;
			document.getElementById("hid_lender").value = lender;
			document.getElementById("hid_loantype").value = loantype;
			
			document.getElementById("inp_chosenAmount").value = loanamount;
			document.getElementById("inp_chosenTerm").value = loanterm;
			document.getElementById("inp_chosenProvider").value = lender;
			document.getElementById("inp_chosenLoanType").value = loantype;

if (destination == "external"){
				compare_to_applyExternal();
			}
			else{
				compare_to_applyInternal();
			}


		}
		else{
			if (loantype == "Unsecured"){
				document.getElementById("tr_unsecOtherLendersMsg").style.display='block';
				checkStatusUnsec(loantype, loanamount, loanterm) ;
				checkStatusSec('Secured', loanamount, loanterm) ;
			}
			else{
				document.getElementById("tr_secOtherLendersMsg").style.display='block';
				checkStatusSec(loantype, loanamount, loanterm) ;
				checkStatusUnsec('Unsecured', loanamount, loanterm) ;
			}
		}
	}
}
	
//####################################################################################
function hideOtherLenderMsg(strType)
{
	if (strType == "Unsecured"){
		if(document.getElementById("tr_unsecOtherLendersMsg")){
			document.getElementById("tr_unsecOtherLendersMsg").style.display='none';
		}	
	}
	if (strType == "Secured"){
		if(document.getElementById("tr_secOtherLendersMsg")){
			document.getElementById("tr_secOtherLendersMsg").style.display='none';
		}	
	}	
}

//######## Postcode Search Code ######################################################
function postcodesearch(strpcode, straddrbox, strpcbox, strnobox, strnamebox, strflatno)
{
	var pcodeid = strpcode;
	var addrbox = straddrbox;
	var pcbox = strpcbox;
	var housename = strnamebox;
	var houseno = strnobox;
	var flatno = strflatno;


	if (strpcode != ''){
		if (document.getElementById(strpcode).value != ''){
			// clear the message if any
			showMessage('');
			// disable the button
			toggleFormButton(true);
			// clear the form
			//clearform();
			// submit the form and data
			document.getElementById("addrbox").value = addrbox;
			document.getElementById("pcbox").value = pcbox;
			document.getElementById("postcode").value = document.getElementById(pcodeid).value;
			document.getElementById("namebox").value = document.getElementById(housename).value;
			//document.getElementById("nobox").value = document.getElementById(houseno).value;
			document.getElementById("flatnobox").value = document.getElementById(flatno).value;;
			document.S2SForm.submit();
		}
		else{
			toggleFormButton(false);
		}
	}
}

//##########################################
function showMessage(str){
	if(document.getElementById){
		document.getElementById('message').innerHTML = str;
	}
	else if (document.all){
    		document.all['message'].innerHTML = str;
	}
}

//##########################################
function toggleFormButton(status) {
	var theform = document.form1;
	var tempobj;
	if (document.all || document.getElementById) {
		var tempobj = document.getElementById("searchbutton");
		if (status == true){
			tempobj.innerHTML = 'Searching...';
		}
		else{
			tempobj.innerHTML = 'Find';
		tempobj.disabled = status;
		}
	}
}

//##########################################
function clearform(){
	var theform = document.contactDetails;
	theform.address.value="";
	//theform.town.value="";
	//theform.county.value="";
	theform.postcode.value="";
}

//##########################################
function newImage(arg) {
	if (document.images) {
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}
//##########################################
function changeImages() {
	if (document.images && (preloadFlag == true)) {
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
		}
	}
}
//##########################################
var preloadFlag = false;
function preloadImages() {
	if (document.images) {
		home_over = newImage("../images/home_over.png");
		preloadFlag = true;
	}
}
 
 //##########################################
 function compare_from_external_page()
 {
	 var loanamount = document.getElementById("inp_loanamount").value;
	 var loanterm = document.getElementById("inp_loanterm").value;

	if (loanamount == "" || loanterm == ""){
		alert('Please enter both Loam Amount and Loan Term');
	}
	else if (!IsNumeric(loanamount)){
			alert('The Loan Amount you have entered is not valid\n\nPlease enter the value in whole pounds only. e.g. 5500');
	}
	else if (!IsNumeric(loanterm)){
			alert('The Loan Term you have entered is not valid\n\nPlease enter the term in whole years only');
	}
	else{
		location.href="index.php?loanamount=" + loanamount + "&loanterm=" + loanterm;
	}
}
  
 //#########################################################################################
 function IsNumeric(sText)
{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }
   
//#########################################################################################
 function IsDecimal(sText)
{
   var ValidChars = "0123456789.";
   var IsDec=true;
   var Char;

   for (i = 0; i < sText.length && IsDec == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsDec = false;
         }
      }
   return IsDec;
   
   }

//#########################################################################################
 function IsAlpha(sText)
{
   //var ValidChars = "0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'-/ \ &";
   var inValidChars = "<>#;:\"!£$%^*\\";

	var Isvalid=true;
   var Char;
   
   for (i = 0; i < sText.length && Isvalid == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (inValidChars.indexOf(Char) >-1) 
         {
         Isvalid = false;
		 alert(sText + ' contains invalid characters');
         }
      }

   return Isvalid;   
}

//#########################################################################################
function validCompare()
{
	var amount = document.getElementById("hid_amount").value
	var term = document.getElementById("hid_term").value
	
	if (!IsNumeric(amount)){
			alert('The Loan Amount you have entered is not valid\n\nPlease enter the value in whole pounds only. e.g. 5500');
			return false;
	}
	else if (!IsNumeric(term)){
			alert('The Loan Term you have entered is not valid\n\nPlease enter the term in whole years only');
			return false;
	}
	else{
		return true;
	}
	
}

 
//#########################################################################################
function chk_EmpStatus(empStatus)
{
	if (empStatus == "Self Employed")
	{
		document.getElementById("div_lbl_accountant").style.display='block';
		document.getElementById("div_sel_accountant").style.display='block';
	}
	else{
		document.getElementById("div_lbl_accountant").style.display='none';
		document.getElementById("div_sel_accountant").style.display='none';
	}
}

//#########################################################################################
function chk_EmpStatus2(empStatus)
{
	if (empStatus == "Self Employed")
	{
		document.getElementById("div_lbl_accountant2").style.display='block';
		document.getElementById("div_sel_accountant2").style.display='block';
	}
	else{
		document.getElementById("div_lbl_accountant2").style.display='none';
		document.getElementById("div_sel_accountant2").style.display='none';
	}
}

//#########################################################################################
function chk_previous_EmpStatus(empStatus)
{
	if (empStatus == "Self Employed")
	{
		document.getElementById("div_lbl_previous_accountant").style.display='block';
		document.getElementById("div_sel_previous_accountant").style.display='block';
	}
	else{
		document.getElementById("div_lbl_previous_accountant").style.display='none';
		document.getElementById("div_sel_previous_accountant").style.display='none';
	}
}

//#########################################################################################
function chk_previous_EmpStatus2(empStatus)
{
	if (empStatus == "Self Employed")
	{
		document.getElementById("div_lbl_previous_accountant2").style.display='block';
		document.getElementById("div_sel_previous_accountant2").style.display='block';
	}
	else{
		document.getElementById("div_lbl_previous_accountant2").style.display='none';
		document.getElementById("div_sel_previous_accountant2").style.display='none';
	}
}

//#########################################################################################
function chk_OtherLoanPurpose(OtherLoanPurpose)
{
	if (OtherLoanPurpose == "Other - Please Specify")
	{
		document.getElementById("div_lbl_otherloanpurpose").style.display='block';
		document.getElementById("div_inp_otherloanpurpose").style.display='block';
	}
	else{
		document.getElementById("div_lbl_otherloanpurpose").style.display='none';
		document.getElementById("div_inp_otherloanpurpose").style.display='none';
	}
}

//#########################################################################################
function chkMarriageStatus (mstatus)
{
	if(mstatus == "Married" || mstatus =="Living with Partner"){
		document.getElementById("lbl_income").innerHTML = "Joint Monthly Income";
		document.getElementById("img_income_info").innerHTML = "The Total Joint Monthly Income, in whole pounds, before tax. E.G. 1250";
		document.getElementById("sel_applicationType").value = 'Joint';
		document.getElementById("span_yourdetails_1_header").innerHTML = "First Applicant "
		document.getElementById("span_yourdetails_2_header").innerHTML = "First Applicant "
		document.getElementById("span_yourdetails_2a_header").innerHTML = "First Applicant "
		document.getElementById("span_yourdetails_3_header").innerHTML = "First Applicant "
		document.getElementById("span_yourdetails_3a_header").innerHTML = "First Applicant "
		//document.getElementById("div_yourdetails_1").style.backgroundImage="url('images/backgrounds/your_details_app1.png')";
		//document.getElementById("div_yourdetails_2").style.backgroundImage="url('images/backgrounds/your_residential_details_app1.png')";
		//document.getElementById("div_yourdetails_3").style.backgroundImage="url('images/backgrounds/your_employment_details_app1.png')";
		//document.getElementById("div_yourdetails_2a").style.backgroundImage="url('images/backgrounds/your_previous_residential_details_app1.png')";
		//document.getElementById("div_yourdetails_3a").style.backgroundImage="url('images/backgrounds/your_previous_employment_details_app1.png')";
	}
	else{
		document.getElementById("lbl_income").innerHTML = "Your Monthly Income";
		document.getElementById("img_income_info").innerHTML = "Your Monthly Income, in whole pounds, before tax. E.G. 1250";
		document.getElementById("sel_applicationType").value = 'Single';
		document.getElementById("span_yourdetails_1_header").innerHTML = "Your "
		document.getElementById("span_yourdetails_2_header").innerHTML = "Your "
		document.getElementById("span_yourdetails_2a_header").innerHTML = "Your "
		document.getElementById("span_yourdetails_3_header").innerHTML = "Your "
		document.getElementById("span_yourdetails_3a_header").innerHTML = "Your "
		//document.getElementById("div_yourdetails_1").style.backgroundImage="url('images/backgrounds/your_details.png')";
		//document.getElementById("div_yourdetails_2").style.backgroundImage="url('images/backgrounds/your_residential_details.png')";
		//document.getElementById("div_yourdetails_3").style.backgroundImage="url('images/backgrounds/your_employment_details.png')";
		//document.getElementById("div_yourdetails_2a").style.backgroundImage="url('images/backgrounds/your_previous_residential_details.png')";
		//document.getElementById("div_yourdetails_3a").style.backgroundImage="url('images/backgrounds/your_previous_employment_details.png')";
	}
}

//#########################################################################################
function chkAppType(apptype)
{
	if(apptype == 'Joint'){
		document.getElementById("div_yourdetails_1").style.backgroundImage="url('images/backgrounds/your_details_app1.png')";		
	}
	else{
		document.getElementById("div_yourdetails_1").style.backgroundImage="url('images/backgrounds/your_details.png')";
	}
}

//#########################################################################################
function chkApp2Address(addressType)
{
	if(addressType == "Yes"){
		// Copy details from App1
		document.getElementById("app2_current_housename").value = document.getElementById("current_housename").value;
		document.getElementById("app2_current_flatno").value = document.getElementById("current_flatno").value;
		document.getElementById("app2_current_postcode").value = document.getElementById("current_postcode").value;
		document.getElementById("app2_current_street").value = document.getElementById("current_street").value;
		document.getElementById("app2_current_locality").value = document.getElementById("current_locality").value;
		document.getElementById("app2_current_town").value = document.getElementById("current_town").value;
		document.getElementById("app2_current_county").value = document.getElementById("current_county").value;
		document.getElementById("inp_app2_timeataddress_years").value = document.getElementById("inp_timeataddress_years").value;
		document.getElementById("inp_app2_timeataddress_months").value = document.getElementById("inp_timeataddress_months").value;
	}
	else{
		//Blank App2 Details	
	}
}

//#########################################################################################
function chkpreviousApp2Address(addressType)
{
	if(addressType == "Yes"){
		// Copy details from App1
		document.getElementById("app2_previous_housename").value = document.getElementById("previous_housename").value;
		document.getElementById("app2_previous_flatno").value = document.getElementById("previous_flatno").value;
		document.getElementById("app2_previous_postcode").value = document.getElementById("previous_postcode").value;
		document.getElementById("app2_previous_street").value = document.getElementById("previous_street").value;
		document.getElementById("app2_previous_locality").value = document.getElementById("previous_locality").value;
		document.getElementById("app2_previous_town").value = document.getElementById("previous_town").value;
		document.getElementById("app2_previous_county").value = document.getElementById("previous_county").value;
		document.getElementById("inp_app2_previous_timeataddress_years").value = document.getElementById("inp_previous_timeataddress_years").value;
		document.getElementById("inp_app2_previous_timeataddress_months").value = document.getElementById("inp_previous_timeataddress_months").value;
	}
	else{
		//Blank App2 Details	
	}
}

//#########################################################################################
/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;
//************************
function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}
//************************
function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    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(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}
//************************
function isDate(dtStr){
	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 i = 1; i <= 3; i++) {
		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){
		alert("The date format should be : dd/mm/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}
//************************
function ValidateDate(dt){
	var dt=document.getElementById(dt);
	var dtval = dt.value;
	if(dtval.length > 0){
		if (isDate(dt.value)==false){
			dt.focus();
			return false;
		}
	}
    return true;
 }

//***********************************************************
function chkGender(fldname, target, app)
{
	strtitle = document.getElementById(fldname).value;
	el =  document.getElementById(target)
	
	if (strtitle == "Mr"){
		gender = "M";
	}
	else if (strtitle == "Dr"){
		gender = "";
	}
	else{
		gender = "F";
	}
	
	el.value = gender;
	
	chkmaidenName(app, gender)	
}
//***********************************************************
function chkmaidenName(app, gender)
{
	if (app == "App1"){
		if (gender == "F"){
			document.getElementById("div_lbl_app1_maidenName").style.display='block';                                 
			document.getElementById("div_lbl_app1_maidenName_blank").style.display='none';     
			document.getElementById("div_fld_app1_maidenName").style.display='block';   
			document.getElementById("div_fld_app1_maidenName_blank").style.display='none';  
		}
		else{
			document.getElementById("div_lbl_app1_maidenName").style.display='none';                                 
			document.getElementById("div_lbl_app1_maidenName_blank").style.display='block';     
			document.getElementById("div_fld_app1_maidenName").style.display='none';   
			document.getElementById("div_fld_app1_maidenName_blank").style.display='block';  
			
		}
	}
	if (app == "App2"){
		if (gender == "F"){
			document.getElementById("div_lbl_app2_maidenName").style.display='block';                                 
			document.getElementById("div_lbl_app2_maidenName_blank").style.display='none';     
			document.getElementById("div_fld_app2_maidenName").style.display='block';   
			document.getElementById("div_fld_app2_maidenName_blank").style.display='none';  
		}
		else{
			document.getElementById("div_lbl_app2_maidenName").style.display='none';                                 
			document.getElementById("div_lbl_app2_maidenName_blank").style.display='block';     
			document.getElementById("div_fld_app2_maidenName").style.display='none';   
			document.getElementById("div_fld_app2_maidenName_blank").style.display='block';  			
		}
	}			
}

//***********************************************************
function chkProperty(proptype)
{
	if (proptype == "Detached" || proptype == "Semi Detached" || proptype == "Terraced" || proptype == "Maisonette"){
		document.getElementById("hid_residencetype").value = "H";
		
		if (proptype == "Detached"){
				document.getElementById("hid_propertystyle").value = "Detached";
		}
		if (proptype == "Semi Detached"){
				document.getElementById("hid_propertystyle").value = "Semi Detached";
		}
		if (proptype == "Terraced"){
				document.getElementById("hid_propertystyle").value = "Terrace";
		}	
	}
	if (proptype == "Bungalow" ){
		document.getElementById("hid_residencetype").value = "B";
		document.getElementById("hid_propertystyle").value = "";
	}
	if (proptype == "Flat" ){
		document.getElementById("hid_residencetype").value = "F";
		document.getElementById("hid_propertystyle").value = "";
	}
	

}

//***********************************************************
function calcAge(birthDay){
      now = new Date();
      bD = birthDay.split('/');
      if(bD.length==3){
              born = new Date(bD[2], bD[1]*1-1, bD[0]);
            years = new Date(now.getTime() - born.getTime());
            base = new Date(0);
			return years.getFullYear()-base.getFullYear();
      }
}

//************************************************************
//// Format Telephone Numbers

function validatePhone(fld){
	var Phone=fld;
	var num = Phone.value;
	
	if (num.length > 0){
		if (checkInternationalPhone(Phone.value)==false){
			alert("Please Enter a Valid Phone Number")
			//Phone.value="";
			Phone.focus();
		}
	}
 }

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = " ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 11;

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

//***************************
function trim(s)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}

//***************************
function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

//***************************
function checkInternationalPhone(strPhone)
{
	var bracket=3;
	strPhone=trim(strPhone);
	s=stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}
//************************************************************
function pause(milliseconds) {
	var dt = new Date();
	while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

//************************************************************
// Validate Email Address
function CheckEmail(fld) {

	email = fld.value;
	
	AtPos = email.indexOf("@");
	StopPos = email.lastIndexOf(".");
	EmailLen = email.length;
	
	Message = "";
		
	if (email.length > 0){
		if (email == "") {
			Message = "The email address entered is invalid. Please amend the email." + "\n";
		}
		
		if (AtPos == -1 || StopPos == -1) {
			Message = "The email address entered is invalid. Please amend the email.";
		}
		
		if (StopPos < AtPos) {
			Message = "The email address entered is invalid. Please amend the email.";
		}
		
		if (StopPos - AtPos == 1) {
			Message = "The email address entered is invalid. Please amend the email.";
		} 
		
		// If the . is last or second to last (there are no single letter TLDs)
		if (StopPos == (EmailLen -1) ||StopPos == (EmailLen -2) ){
			Message = "The email address entered is invalid. Please amend the email.";
		}
		
		if (Message !=""){
			alert(Message);
			fld.value=fld.value;
			fld.focus();
		}
	}

}
