//*************************************************************************************************************************************
function trimAll(sString) 
{
while (sString.substring(0,1) == ' ')
{
sString = sString.substring(1, sString.length);
}
while (sString.substring(sString.length-1, sString.length) == ' ')
{
sString = sString.substring(0,sString.length-1);
}
return sString;
}

function verif_email(email) {
var arobase = email.indexOf("@");
var point = email.lastIndexOf(".");
if((arobase < 3)||(point + 2 > email.lengtd)||(point < arobase+3)) return false;
return true;
}

//*****************************************************************************************************************************************
function externalLinks() { 
 if (!document.getElementsByTagName) return; 
 var anchors = document.getElementsByTagName("a"); 
 for (var i=0; i<anchors.length; i++) { 
   var anchor = anchors[i]; 
   if (anchor.getAttribute("href") && 
       anchor.getAttribute("rel") == "external") 
     anchor.target = "_blank"; 
 } 
} 
window.onload = externalLinks;



function validateQuickQuoteForm()
{
	
	var QuickQuoteForm = document.forms['QuickQuoteForm'];
	var QuickQuoteName = trimAll(QuickQuoteForm.QuickQuoteName.value);
	var QuickQuoteAddress = trimAll(QuickQuoteForm.QuickQuoteAddress.value);
	var QuickQuotePostcode = trimAll(QuickQuoteForm.QuickQuotePostcode.value);
	var QuickQuoteDayTel = trimAll(QuickQuoteForm.QuickQuoteDayTel.value);
	var QuickQuoteEveTel = trimAll(QuickQuoteForm.QuickQuoteEveTel.value);
	var QuickQuoteMobTel = trimAll(QuickQuoteForm.QuickQuoteMobTel.value);
	var QuickQuoteFax = trimAll(QuickQuoteForm.QuickQuoteFax.value);
	var QuickQuoteEmail = trimAll(QuickQuoteForm.QuickQuoteEmail.value);
	var QuickQuoteMortType = trimAll(QuickQuoteForm.QuickQuoteMortType.value);
	var QuickQuoteAddInfo = trimAll(QuickQuoteForm.QuickQuoteAddInfo.value);
	var QuickQuoteMortAmount = trimAll(QuickQuoteForm.QuickQuoteMortAmount.value);
	var QuickQuoteMortTerm = trimAll(QuickQuoteForm.QuickQuoteMortTerm.value);
	var QuickQuoteTerms = QuickQuoteForm.QuickQuoteTerms;
	
	
	if (QuickQuoteName == '')
	{
		alert("You must enter a name")	
		return false;
	}
	
	if (QuickQuoteAddress == '')
	{
		alert("You must enter an address")	
		return false;
	}
	
	if (QuickQuoteDayTel == '')
	{
		alert("You must enter a daytime telephone number")	
		return false;
	}
	
	if (!verif_email(QuickQuoteEmail))
			{
		alert("You must enter a valid email address")	
		return false;
			}

	
	//if (QuickQuoteEmail == '')
	//{
	//	alert("You must enter a valid email address")	
	//	return false;
	//}
	
	if (QuickQuoteMortType == '')
	{
		alert("You must enter the mortgage type required")
		return false;
	}
	
	if (QuickQuoteMortAmount == '')
	{
		alert("You must enter the mortgage amount required")
		return false;
	}

	
	if (QuickQuoteMortTerm == '')
	{
		alert("You must enter the mortgage term")
		return false;
	}
	
	if (QuickQuoteTerms.checked == false)
	{
		alert("You must agree to the terms of use and privacy policy")
		return false;
	}

		return true;
}

//*****************************************************************************************************************************************
function validateContactForm()
{
	
	var ContactForm = document.forms['ContactForm'];
	var ContactName = trimAll(ContactForm.ContactName.value);
	var ContactAddress = trimAll(ContactForm.ContactAddress.value);
	var ContactPostcode = trimAll(ContactForm.ContactPostcode.value);
	var ContactDayTel = trimAll(ContactForm.ContactDayTel.value);
	var ContactEveTel = trimAll(ContactForm.ContactEveTel.value);
	var ContactMobTel = trimAll(ContactForm.ContactMobTel.value);
	var ContactFax = trimAll(ContactForm.ContactFax.value);
	var ContactEmail = trimAll(ContactForm.ContactEmail.value);
	var ContactAddInfo = trimAll(ContactForm.ContactAddInfo.value);
	var ContactSecurityCode = trimAll(ContactForm.ContactSecurityCode.value);
	
	
	
	if (ContactName == '')
	{
		alert("You must enter a name")	
		return false;
	}
	
	if (ContactAddress == '')
	{
		alert("You must enter an address")	
		return false;
	}
	
	if (ContactDayTel == '')
	{
		alert("You must enter a daytime telephone number")	
		return false;
	}
	
	if (!verif_email(ContactEmail))
			{
		alert("You must enter a valid email address")	
		return false;
			}

	if (ContactSecurityCode == '')
	{
		alert("You must enter the security code as shown")	
		return false;
	}
	
		return true;
		//ContactForm.Submit_Bt.disabled = true;
}


//*************************************************************************************************************************************
function formatNumber(number,precision,commas) {
   if (precision==null) precision = 2;
   number = formatRound(number,precision);
   var llSign = number<0;
   number = Math.abs(number);
   var ln = precision+1;
   var lc = "";
   number = Math.floor(number*Math.pow(10,precision));
   while (((ln--)>0) || (number>0)) {
      lc = (number%10)+lc;
      number = Math.floor(number/10);
      if (ln==1) lc = "."+lc;
   }
   if (llSign) lc = "-"+lc;
   var lc2 = "";
   if (commas) {
      var lc3 = lc;
      ln = lc.length;
      if (lc.indexOf(".")!=-1) {
         lc2 = lc.substring(lc.indexOf("."),ln);
         lc3 = lc.substring(0,lc.indexOf("."));
      }
      ln = lc3.length;
      var lnCount = 0;
      while (ln>0) {
         lnCount++;
         if (lnCount==4) {
            lc2 = ","+lc2;
            lnCount = 1;
         } 
         lc2 = lc3.substring(ln-1,ln)+lc2;
         ln--;
      }
   } else {
      lc2 = lc;
   }
   return lc2;
}

function formatRound(number,precision) {
   if (precision==null) precision = 2;
   if (precision==0) {
      return Math.round(number);
   }
   lnFactor = Math.floor(Math.pow(10,precision));
   if (precision<0) {
      return  Math.round(number/lnFactor)*lnFactor;
   }
   
   return Math.round(number*lnFactor)/lnFactor;
}

function calcBand(Type,Income){

	if (Type == "single"){
		if (Income > 0 && Income < 10000){
			return 3.15;
		}
		 if (Income > 10001 && Income < 17500){
			return 3.25;
		}
		 if (Income > 17501 && Income < 25000){
			return 3.35;
		}
		 if (Income > 25001 && Income < 32500){
			return 3.50;
		}
		 if (Income > 32501 && Income < 100000){
			return 3.75;
		}
		 if (Income > 100001){
			return 4.00;
		}
				

	}
	else
	{
		if (Income > 0 && Income < 10000){
			return 2.4;
		}
		 if (Income > 10001 && Income < 17500){
			return 2.5;
		}
		 if (Income > 17501 && Income < 25000){
			return 2.55;
		}
		 if (Income > 25001 && Income < 32500){
			return 2.65;
		}
		 if (Income > 32501 && Income < 100000){
			return 2.80;
		}
		 if (Income > 100001){
			return 3.00;
		}
	}
}

function oneortwo(objectToUse){
	if (objectToUse.checked){
		document.LoanCalc.Income2.disabled = true;
		document.LoanCalc.Expence2.disabled = true;
	}
	else
	{
		document.LoanCalc.Income2.disabled = false;
		document.LoanCalc.Expence2.disabled = false;
	}
}
//*************************************************************************************************************************************




function calc(){
	with(document.forms['Calculator'])
	{
		
		var amount = parseFloat(MortgageAmount.value);
		var term = parseFloat(MortgageTerm.value);
		var rate = parseFloat(MortgageRate.value);
		rate = rate/1200;
		
		
		var error = false;
			
		var aryValues = new Array();
		aryValues[0] = parseFloat(MortgageAmount.value);
		aryValues[1] = parseFloat(MortgageRate.value/1200);
		aryValues[2] = parseFloat(MortgageTerm.value);
			
		
			
		aryNames = new Array();
		aryNames[0] = "Loan Amount";
		aryNames[1] = "Interest Rate";
		aryNames[2] = "Loan Term";
			
		
		var msg = "Please check the below:\n\n";
			
		
		for (i=0;i<3;i++)
		{
			//check value is a number
			if (isNaN(aryValues[i]) == true){
				aryValues[i] = "Please enter a number";
				error = true;
				msg = msg+aryNames[i]+" is not a number\n";
			}//if
			
			//Check value is not null
			if (aryValues[i] == "" ) {
				aryValues[i] = "Please enter a value";
				error = true;
				msg = msg+aryNames[i]+" has no value\n";
			}//if
		}//for
		
		if (error == true){
			alert(msg);
		}// if
		else
		{
			
			
				MortgageInterestOnly.value = formatNumber(aryValues[0]*aryValues[1],2,1);
				//MortgageInterestOnly.value = formatNumber(aryValues[0]*aryValues[1]*aryValues[2]*12,2,1);
				
			
				var ln = Math.pow(1+aryValues[1],aryValues[2]*12);
				
				var answer = (aryValues[0]-0/ln)/((1-(1/ln))/aryValues[1]);
						
				var intrest = formatNumber((answer*aryValues[2]*12)-aryValues[0],2,1);
				
				answer = formatNumber(answer,2,1)
				
				MortgageRepayment.value = answer
				
				//MortgageInterestOnly.value = intrest
		
			
			
		}//else
	}//with
}// function

function Clear(w) {
	if (w == 'loan'){
		document.LoanCalc.Income1.value="";
		document.LoanCalc.Income2.value="";
		document.LoanCalc.Expence1.value="";
		document.LoanCalc.Expence2.value="";
		document.LoanCalc.loanamount.value="";
	}
	else
	{
		document.Calculator.MortgageAmount.value= "";
		document.Calculator.MortgageRate.value= "";
		document.Calculator.MortgageTerm.value = "";
		document.Calculator.MortgageInterestOnly.value = "";
		document.Calculator.MortgageRepayment.value = "";
	}
}

function loanCalc() {

	// Income and expences for both applicants.
	var Income1 = parseFloat(document.LoanCalc.Income1.value);
	var Income2 = parseFloat(document.LoanCalc.Income2.value);
	var Expence1 = parseFloat(document.LoanCalc.Expence1.value);
	var Expence2 = parseFloat(document.LoanCalc.Expence2.value);
	
	
	//Validation
	
	var error = false;
			
	var aryValues = new Array();
	aryValues[0] = parseFloat(document.LoanCalc.Income1.value);
	aryValues[1] = parseFloat(document.LoanCalc.Expence1.value);
	aryValues[2] = parseFloat(document.LoanCalc.Income2.value);
	aryValues[3] = parseFloat(document.LoanCalc.Expence2.value);
		
	aryNames = new Array();
	aryNames[0] = "Income 1";
	aryNames[1] = "Expence 1";
	aryNames[2] = "Income2";
	aryNames[3] = "Expence 2";

	var msg = "These errors have occured:\n";
			
	if (document.LoanCalc.Method.checked){
		 var type = 2
	}
	else
	{
		var type = 4
	}
		
	for (i=0;i<type;i++)
	{
		//check value is a number
		if (isNaN(aryValues[i]) == true){
			aryValues[i] = "Please enter a number";
			error = true;
			msg = msg+aryNames[i]+" is not a number!\n";
		}//if
		
		//Check value is not null
		if (aryValues[i] == "" ) {
			aryValues[i] = "Please enter a value";
			error = true;
			msg = msg+aryNames[i]+" has no value!\n";
		}//if
	}//for

	if (error == true)
	{
		alert(msg);
	}// if
	else
	{
		//check for single or double loan
		if (document.LoanCalc.Method.checked){
			//SINGLE 
			
			disposableincome  = parseFloat(document.LoanCalc.Income1.value) - (parseFloat(document.LoanCalc.Expence1.value)*12);
			
			if (disposableincome <= 0){
				alert("you have no disposable income!")
			}
			else
			{
				band = calcBand("single",disposableincome);
				
				total = disposableincome*band;
				
				display = formatNumber(total,2,1);
				
				document.LoanCalc.loanamount.value = "£"+display;
			}
		}
		else
		{
			//DOUBLE
			//get the disposable income for the applicants
			disposableincome1 = parseFloat(document.LoanCalc.Income1.value) - (parseFloat(document.LoanCalc.Expence1.value)*12);
			disposableincome2 = parseFloat(document.LoanCalc.Income2.value) - (parseFloat(document.LoanCalc.Expence2.value)*12);
			
			if (disposableincome1 + disposableincome2<=0){
				alert("you have no disposable income!")
			}
			else
			{
				//Find the Highest value
				Highestvalue = Math.max(disposableincome1,disposableincome2);
				Lowestvalue = Math.min(disposableincome1,disposableincome2);
				
				// method 1
				Method1Total = (Highestvalue*calcBand("single",Highestvalue))+Lowestvalue;
				// method 2
				Method2Total = (disposableincome1 + disposableincome2)* calcBand("double", (disposableincome1 + disposableincome2));
				
				// find the Largest amount the loan can be
				var Loanamount = Math.max(Method1Total,Method2Total);
				
				
				document.LoanCalc.loanamount.value = "£"+formatNumber(Loanamount,2,1);
			}
		}
	}
}

function affordCalc()
{
	document.forms['affordForm'].AffordAmount.value=((Math.floor(parseInt(document.forms['affordForm'].CashAvailable.value)*10000/parseInt(document.forms['affordForm'].AffordPropertyPrice.value)))/100).toString().replace('NaN','');
}

function depositCalc()
{
	document.forms['depositForm'].DepositAmount.value=(parseInt(document.forms['depositForm'].DepositPropertyPrice.value)*parseInt(document.forms['depositForm'].DepositRequired.value)/100).toString().replace('NaN','');
}

function borrowCalc()
{
	var fi=0+parseInt(document.forms['borrowForm'].MainSalary.value);
	var si=0+parseInt(document.forms['borrowForm'].SecondSalary.value);
	if (si>fi) 
	{
		var t=fi; fi=si; si=t;
	}
	t=fi*4;
	if (si>0) 
	{
		t=3*(fi+si);
		if (fi*4>t)	
		t=fi*4;
	}
	document.forms['borrowForm'].BorrowAmount.value=t.toString().replace('NaN','');
}

function stampCalc()
{
	var pprice=parseInt(document.forms['stampForm'].PropertyPrice.value);
	document.forms['stampForm'].StampDutyAmount.value=((document.forms['stampForm'].DisadvantagedArea.checked&&pprice<=150000)? 0 :(pprice>500000)? 4 : (pprice>250000)? 3 : (pprice>120000)? 1 : 0).toString().replace('NaN','');
}
