// JavaScript Document

/////////////////////////////////////////////////////////////////////
//How much can I borrow?

function CalculateBorrowing(){
	
//declare income variables
	var	App1Income		=	document.getElementById("Income_app1").value;
	var	App2Income		=	document.getElementById("BorrowingCalc").Income_app2.value;
	var	App1Bonus		=	document.getElementById("BorrowingCalc").Bonus_app1.value;
	var	App2Bonus		=	document.getElementById("BorrowingCalc").Bonus_app2.value;
	App1Income			=	parseFloat(App1Income.replace(/[^0-9.]/g, ''));
	App2Income			=	parseFloat(App2Income.replace(/[^0-9.]/g, ''));
	App1Bonus			=	parseFloat(App1Bonus.replace(/[^0-9.]/g, ''));
	App2Bonus			=	parseFloat(App2Bonus.replace(/[^0-9.]/g, ''));
	
	if (isNaN(App1Income)){		App1Income = 0	}	
	if (isNaN(App2Income)){		App2Income = 0	}	
	if (isNaN(App1Bonus)){		App1Bonus = 0	}	
	if (isNaN(App2Bonus)){		App2Bonus = 0	}
		
//earnings are all of basic and half bonuses
	var	App1Earnings		=	0.5 * App1Bonus + App1Income
	var	App2Earnings		=	0.5 * App2Bonus + App2Income
	
// single or joint application 
	var joint = false
	if (App2Earnings > 1) {
		joint = true
	}
	else {
		joint = false
	}
	
// decide on main income
	var MainIncome
	var SecondIncome
	if (App1Earnings > App2Earnings){ 
	MainIncome = App1Earnings
	SecondIncome = App2Earnings
	} 
	else {
	MainIncome = App2Earnings
	SecondIncome = App1Earnings
	}
	
//declare higher and lower amounts
	var HigherAmount
	var LowerAmount

//Lower Amount
	if (joint == false) {
	LowerAmount = MainIncome * 3.25
	}
	else {
	LowerAmount = (MainIncome + SecondIncome) * 2.5
	}

// Higher Amount
	if (joint == true){
	var JointJoint = (MainIncome + SecondIncome) * 2.8
	var JointSingle = (MainIncome * 4) + SecondIncome
	if (JointJoint > JointSingle) {
	var JointIncome = JointJoint
	}
	else {
	var JointIncome = JointSingle
	}
	}
	if (joint == false) {
	HigherAmount = MainIncome * 4
	}
	else {
	HigherAmount = JointIncome
	}
	
// show results	
	var BorrowingAmount = "\u00A3" + LowerAmount + " and \u00A3" + HigherAmount;

	document.getElementById('results').innerHTML = "Based on the basic information you have provided, an indication of what you can borrow is between: " + BorrowingAmount +"<br><br>"
}
	
	
/////////////////////////////////////////////////////////////////////
//What will it cost?
function borrowingcosts(){

//declare key variables
	var	Loan		=	document.getElementById("MortgageCalc").LoanAmount.value;
	Loan			=	parseFloat(Loan.replace(/[^0-9.]/g, ''));
	var	Rate		=	document.getElementById("MortgageCalc").InterestRate.value;
	Rate			=	parseFloat(Rate.replace(/[^0-9.]/g, ''));
	var	Term		=	new Number(document.getElementById("MortgageCalc").Term.value);
	Loan			=	parseFloat(Loan);
	Term			=	parseFloat(Term);
	
//interest only amount
	var InterestOnly = (Loan * (Rate/100))/12
	InterestOnly = Math.round(InterestOnly);
	
//repayment amount
	var MonthlyRate = Rate/1200 
	var TermMonths = Term * -12
	var Multiplier = 1 + MonthlyRate
	Multiplier = Math.pow(Multiplier, TermMonths)
	Multiplier = 1 - Multiplier
	Multiplier = MonthlyRate / Multiplier
	var RepaymentAmount = Loan * Multiplier
	RepaymentAmount = Math.round(RepaymentAmount)
	document.getElementById("IOresults").innerHTML = "\u00A3" + InterestOnly
	document.getElementById("Rresults").innerHTML  = "\u00A3" + RepaymentAmount
}

/////////////////////////////////////////////////////////////////////	
// Early repayment calc

function ERC_CALC(){


//declare key variables
	var	Loan		=	document.getElementById("ERC_Calc").Loan.value;
	//Loan			=	parseFloat(Loan.replace(/[^0-9.]/g, ''));
	Loan			=	parseFloat(Loan); 
	var	Rate		=	document.getElementById("Rate").value;
	Rate			=	parseFloat(Rate.replace(/[^0-9.]/g, ''));
	
	var TermYears	= 	new Number(document.getElementById("TermYears").value);
	var TermMonths	= 	new Number(document.getElementById("TermMonths").value);
	var Term		= 	TermYears * 12 + TermMonths
	var PenaltyAmount = document.getElementById("ERCval").value;
	PenaltyAmount 	= 	parseFloat(PenaltyAmount.replace(/[^0-9.]/g, ''));	
	var PenHow = new Number(document.getElementById("PenHow").value);
	var Penalty = 0;
	
// figure out penalty whether it is % or Val
	if (PenHow == 2){
	Penalty = PenaltyAmount * Loan / 100
	}
	else {
	Penalty = PenaltyAmount
	}
	var AddToLoan = document.getElementById("AddCharge").value;
	var Fees = 80000 / Loan
	PenaltyAsPerc = (Penalty / Loan) * 100
// Calculations for if not added to loan
	var NotAddedPayFees =  Rate - (((Fees + PenaltyAsPerc)*12) / Term) 
	// Round to 2 decimal places
		NotAddedPayFees = Math.round(NotAddedPayFees * 100)
		NotAddedPayFees = NotAddedPayFees / 100
		var NotAddedFeesPaid = Rate - ((PenaltyAsPerc*12) / Term)
	// Round to 2 decimal places
		NotAddedFeesPaid = Math.round(NotAddedFeesPaid * 100)
		NotAddedFeesPaid = NotAddedFeesPaid / 100
// Calculations for if added to loan
	var TerminYears = TermMonths/12 + TermYears
	var CostofStaying = Loan * Rate/100 * TerminYears
	var numerator = CostofStaying - Penalty
	var denomiator = (TerminYears/100) * (Loan + Penalty)
	var AddedPayfees = (numerator - 800) / denomiator
	// Round to 2 decimal places
		AddedPayfees = Math.round(AddedPayfees * 100)
		AddedPayfees = AddedPayfees / 100
	var AddedFeesFree = numerator / denomiator
	// Round to 2 decimal places
	AddedFeesFree = Math.round(AddedFeesFree * 100)
	AddedFeesFree = AddedFeesFree / 100
	
// Show results	
	if (AddToLoan == 2){
	document.getElementById("PaidCosts").innerHTML = "The rate that you need to achieve if all remortgage costs are paid on your behalf by the new lender (eg. valuation, legal fees, etc is) " + AddedFeesFree + "%"
	document.getElementById("UnpaidCosts").innerHTML = "The rate that you need to achieve, assuming that you pay for the remortgage costs is: " + AddedPayfees + "%"
	}
	else {
	document.getElementById("PaidCosts").innerHTML = "The rate that you need to achieve if all remortgage costs are paid on your behalf by the new lender (eg. valuation, legal fees, etc) is " + NotAddedFeesPaid + "%"
	document.getElementById("UnpaidCosts").innerHTML = "The rate that you need to achieve, assuming that you pay for the remortgage costs is: " + NotAddedPayFees + "%"
	}
}

/////////////////////////////////////////////////////////////////////
// Endowment Short fall

function RepaymentAmount (Rate, Term, Loan){
//declare key variables
	var MonthlyRate = Rate/12 
	var TermMonths = Term * -12
	var Multiplier = 1 + MonthlyRate
	Multiplier = Math.pow(Multiplier, TermMonths)
	Multiplier = 1 - Multiplier
	Multiplier = MonthlyRate / Multiplier
	var RepaymentVal = Loan * Multiplier
	RepaymentVal = Math.round(RepaymentVal)
	return RepaymentVal
}

function CalculateNewMonthlyAmount (Loan, Term, Rate, Shortfall){
	var RepaymentVal = RepaymentAmount(Rate, Term, Shortfall)
	var IOnlyPayment = (Loan - Shortfall)*Rate/12
	var TotalNewPayment = RepaymentVal + IOnlyPayment
	return TotalNewPayment
}
function CalculateNewRate(){
	//This is the current market rate that we make comparisons on later
	var	MarketRate		=	new Number 
	MarketRate = 4.34
	//Define other key variables
	var Loan			=	document.getElementById("BorrowingCalc").Loan.value;
		Loan			=	parseFloat(Loan.replace(/[^0-9.]/g, ''));
	var Term			=	document.getElementById("BorrowingCalc").Term.value;
		Term 			=	parseFloat(Term.replace(/[^0-9.]/g, ''));
	var Rate			=	document.getElementById("BorrowingCalc").Rate.value;
		Rate			=	parseFloat(Rate.replace(/[^0-9.]/g, ''));
	var Shortfall		=	document.getElementById("BorrowingCalc").Shortfall.value;
		Shortfall		=	parseFloat(Shortfall.replace(/[^0-9.]/g, ''));
	Rate = Rate/100
	var CurPayment 		= Loan*(Rate)/12
	var newAmount    	=  CalculateNewMonthlyAmount (Loan, Term, Rate, Shortfall)
	while (newAmount > CurPayment){
	Rate = Rate - 0.0001
	newAmount = CalculateNewMonthlyAmount (Loan, Term, Rate, Shortfall)
	}
	Rate = Math.round(Rate * 10000);
	Rate = Rate/100
	document.getElementById("TargetRate").innerHTML = "The mortgage calculator has worked out that in order to transfer your current shortfall to a repayment basis without increasing your monthly payment, you will need to achieve a rate of:  " + Rate + "% <br/><br/>"
}
/////////////////////////////////////////////////////////////////////
// Rate Change
function RateChanges(){
// DECLARE VARIABLES
	var	Loan			=	(document.getElementById("Repayment").value);
		Loan 			= 	parseFloat(Loan.replace(/[^0-9.]/g, ''));
		if (isNaN(Loan)){
		
		Loan = 0
		}; 
	var InterestOnly 	=	document.getElementById("InterestOnly").value;
		InterestOnly	= 	parseFloat(InterestOnly.replace(/[^0-9.]/g, ''));
		if (isNaN(InterestOnly)){InterestOnly = 0}; 
	var Rate 			=  document.getElementById("InterestRate").value;
		Rate			= 	parseFloat(Rate.replace(/[^0-9.]/g, ''));
	var Term			= 	new Number(document.getElementById("Term").value);
// GET CURRENT INTEREST ONLY PAYMENT
	var InterestOnlyPayment = getInterestOnlyPayment (InterestOnly, Rate, Term)
// GET CURRENT REPAYMENT PAYMENT	
	var dailyorannual = document.getElementById("InterestCalc").value
	if (dailyorannual == 1){
	Rate = Rate/1200
	Term = Term*12
	var repaymentamount = RepaymentCalc(Loan, Rate, Term)
	}
	else {
	Rate = Rate/100
	var repaymentamount = RepaymentCalc(Loan, Rate, Term)/12
	}
// Get current monthly payment
	var CurrentMonthlyPayment = repaymentamount + InterestOnlyPayment
	CurrentMonthlyPayment = Math.round(CurrentMonthlyPayment)

	
// Change
	var Multiplier = new Number(document.getElementById("ChangeDirection").value);
	var AmountofChange = new Number(document.getElementById("RateChange").value);
		
	var NewRate = new Number(document.getElementById("InterestRate").value) + (AmountofChange * Multiplier)
// Get new interest only payment
	var NewInterestOnlyPayment = getInterestOnlyPayment (InterestOnly, NewRate, Term)
// Get new repayment payment
	if (dailyorannual == 1){
	NewRate = NewRate/1200
	Term = document.getElementById("Term").value * 12
	var Newrepaymentamount = RepaymentCalc(Loan, NewRate, Term)
	}
	else {
	NewRate = NewRate/100
	var Newrepaymentamount = RepaymentCalc(Loan, NewRate, Term)/12
	}
// Get new monthly payment
	var NewMonthlyPayment = Newrepaymentamount + NewInterestOnlyPayment
	NewMonthlyPayment = Math.round(NewMonthlyPayment)
	/*document.getElementById.("NewPayment").value = NewMonthlyPayment*/
// Monthly difference
	var monthlydifference = NewMonthlyPayment - CurrentMonthlyPayment 
	/*document.getElementById.("MonthlyDiff").value = monthlydifference*/
// Annual difference 
	var Annualdifference = monthlydifference * 12
	/*document.getElementById.("AnnualDif").value = Annualdifference*/


document.getElementById("results").innerHTML = "Your current monthly payment is: \u00A3" + CurrentMonthlyPayment + "<br> Your new monthly payment would be: \u00A3" + NewMonthlyPayment + "<br> This is a monthly difference of: \u00A3" + monthlydifference + " and an annual difference of: \u00A3" + Annualdifference + "<br><br>"

}
function getInterestOnlyPayment (Loan, Rate, Term){
	var InterestOnlyPayment = (Loan * (Rate/100))/12
	return InterestOnlyPayment
	}
	function RepaymentCalc(Loan, Rate, Term){
	var MonthlyRate = Rate
	var TermMonths = Term * -1
	var Multiplier = 1 + MonthlyRate
	Multiplier = Math.pow(Multiplier, TermMonths)
	Multiplier = 1 - Multiplier
	Multiplier = MonthlyRate / Multiplier
	var RepaymentAmount = Loan * Multiplier
	return RepaymentAmount
}

/////////////////////////////////////////////////////////////////////
//stamp duty calculator

function getStampDutyOnHouse(){
	var	house_price		=document.getElementById("price_house").value;
	house_price	=	parseFloat(house_price.replace(/[^0-9.]/g, ''));
	house_price			=	parseFloat(house_price);
	var	stampDuty		=	new Number(0);
	if(house_price<125001){
		stampDuty		=	0;
	}
	else if(house_price<250001){
		stampDuty		= .01 * house_price;
	}
	else if(house_price <500001){
		stampDuty		= .03 * house_price;
	}
	else{
		stampDuty		= .04 * house_price;
	}
	
	var SD2 = "Stamp duty on a house valued at \u00A3" + house_price + " would be: \u00A3" + stampDuty + "<br><br>"
document.getElementById("results").innerHTML = SD2
}

/////////////////////////////////////////////////////////////////////
// How much can I borrow on a buy to let mortgage
function CalculateB2LBorrowing(){
//declare variables
var	PropertyValue		=	 document.getElementById("PropValue").value;
PropertyValue = parseFloat(PropertyValue.replace(/[^0-9.]/g, ''));
var	MonthlyRent		=	 document.getElementById("MonthlyRent").value;
MonthlyRent	=	parseFloat(MonthlyRent.replace(/[^0-9.]/g, ''));
var MaxLoanLtv = 0
var MaxLoantoRent  = 0
var MaxLoan = 0
if (MonthlyRent > 0) {
	MaxLoantoRent = (MonthlyRent * 12)/ 0.06875;
	MaxLoantoRent = parseFloat(MaxLoantoRent);
	MaxLoan = MaxLoantoRent;
		}
if (PropertyValue > 0) {
	MaxLoanLtv = PropertyValue * 0.85;
	MaxLoan = MaxLoanLtv;
}
if (MonthlyRent > 0 && PropertyValue > 0){
	if (MaxLoanLtv > MaxLoantoRent) { MaxLoan = MaxLoantoRent }
	else {MaxLoan = MaxLoanLtv}
	}
	MaxLoan = Math.round(MaxLoan * 100)
		MaxLoan = MaxLoan / 100
	
	var MaxLoan2 = "A conservative estimate of what you could borrow, based on the information you have provided the mortgage calculator is \u00A3" + MaxLoan +"<br>"
document.getElementById("results").innerHTML = MaxLoan2
}

/////////////////////////////////////////////////////////////////////
//How much rent should I charge on a buy to let mortgage
function CalculateRent(){
//declare variables
var	PropertyValue		=	document.getElementById("PropValue").value;
PropertyValue	=	parseFloat(PropertyValue.replace(/[^0-9.]/g, ''));
var	Deposit		=	new Number(document.getElementById("Deposit").value);
var Loan = PropertyValue - Deposit;
var Rent = Loan *1.25 * 0.065 / 12;
Rent = parseFloat(Rent);
Rent = Math.round(Rent * 100)
		Rent = Rent / 100
document.getElementById("results").innerHTML = " You need at least \u00A3" + Rent + " per month in rent";
}
function defaultdeposit (){
var	PropertyValue		=	document.getElementById("PropValue").value;
PropertyValue	=	parseFloat(PropertyValue.replace(/[^0-9.]/g, ''));
var	Deposit		=	PropertyValue * 0.15
document.getElementById("Deposit").value = Deposit
}

/////////////////////////////////////////////////////////////////////
//Effects of overpayments

function calculate_payment(PV, IR, NP) {
  var PMT = (PV * IR) / (1 - Math.pow(1 + IR, -NP))
  return round_decimals(PMT, 2)
}
function round_decimals(original_number, decimals) {
  var result1 = original_number * Math.pow(10, decimals)
  var result2 = Math.round(result1)
  var result3 = result2 / Math.pow(10, decimals)
  return (result3)
}
function overpayments(){
var present_value = new Number(document.getElementById("loan").value);
var interest_rate = new Number(document.getElementById("interest_rate").value) / 100;
var loan_term = new Number(document.getElementById("term").value);
var monthly_payment = new Number(calculate_payment(present_value, interest_rate / 12, loan_term * 12));
var overpayment = new Number(document.getElementById("overpayment").value);

var monthlyoverpayment = overpayment + monthly_payment;
monthlyoverpayment = Math.round(100*monthlyoverpayment)/100;
var curcost = Math.round(100*(monthly_payment * loan_term * 12))/100;

  	pp = new Number(document.getElementById("loan").value);
  	rr = new Number(document.getElementById("interest_rate").value); 
  	var ii = rr/1200;
  	xx = monthlyoverpayment;
  	var nn = Math.log(xx/(xx-pp*ii))/Math.log(1+ii);
	nn1 = nn/12;
  	nn = Math.floor(nn1);
	nn_months = (nn - nn1) * -12;
	nn_months = Math.round(nn_months);
	
	
	var newcost = Math.round(100*(monthlyoverpayment * 12 * nn1))/100;
	var mp1 = Math.round(100*monthly_payment)/100;
	var mp2 = Math.round(100*monthlyoverpayment)/100;
	var tc1 = Math.round(100*(monthly_payment * loan_term * 12))/100; 
	var tc2 = Math.round(100*(curcost - newcost))/100; 
	var y1 = Math.round(100*(loan_term - nn))/100;
	var y2 = "error"
	y1 = y1 - 1
	var m2 = 12 - nn_months 
	if (y1==1){	y2 = y1 + " year";}
	else {y2 = y1 + " years"	}
	var result = 
	"<strong> Effect on Monthly Payments: </strong><br><br>  By overpaying by \u00A3"
	 + overpayment +
	 " per month your monthly payments will increase from \u00A3" 
	 + mp1 + 
	" to \u00A3" 
	+ mp2 +
	"<br><br> <strong> Total cost over lifetime of mortgage:  </strong><br><br> By overpaying by \u00A3" 
	+ overpayment +
	" per month the total cost of your mortgage will decrease from \u00A3" 
	+ tc1 + 
	" to \u00A3" 
	+ newcost +
	" saving \u00A3"
	+ tc2 + 
	" <br><br><strong> Term of mortgage: </strong><br><br> By overpaying by \u00A3" 
	+ overpayment +
	" per month the term of your mortgage will decrease from " 
	+ loan_term +
	" years to " 
	+ nn +  
	" years and "
	+ nn_months + 
	 " months. A saving of "
	+ y2 + 
	" and "
	+ m2 + 
	" months."
	
	document.getElementById("results").innerHTML = result
}

/////////////////////////////////////////////////////////////////////
//savings calculator 1 - savings goal

function floor(number) {
return Math.floor(number*Math.pow(10,2))/Math.pow(10,2);
}

function savingsgoal() {
//declare variables
document.getElementById("results").value = "Year : Savings balance\n";
var balance = document.getElementById("LumpSum").value;
var growth = document.getElementById("EstGrowth").value;
var deposit = document.getElementById("requiredamount").value;
var monthlyinvestment = document.getElementById("MonthlyAmount").value;
var monthlyinterest = Number(growth)/1200;
var months = 0;
var yr=0;

if (isNaN(balance) || isNaN(growth) || isNaN(deposit) || isNaN(monthlyinvestment)) {alert('Please insert only numbers')
} else 
//whilst we haven't yet hit the required amount, keep going in months
{
if (Number(document.getElementById("LumpSum").value) < Number(document.getElementById("requiredamount").value) ) 
	{
while ( Number(balance) < Number(deposit) ) 
		{
	var lastbalance = balance;
	if (months < 12)
			{
		balance = Number(balance) + (Number(balance)*monthlyinterest) + Number(monthlyinvestment);
		months++;
			} 
	else 	{
		yr++;
		document.getElementById("results").value = document.getElementById("results").value + "\nYear " + yr + " : " + floor(balance);
		months=0;
			};
		};
yr++;
if (isNaN(balance))
		{
	alert('Please insert numbers only');
	document.getElementById("display").value = "Form submissions not valid";
		}else
		{
	if (months!=1)
		{
		var prev_m_yr = yr;
		var prev_month = months - 1;
		document.getElementById("results").value = document.getElementById("results").value + "\nYear " + prev_m_yr + " : " + floor(lastbalance) + "(month " + prev_month + ")";
		}
	}
}
}
}

/////////////////////////////////////////////////////////////////////
//Online interest calculator

function calculate() {
//declare variables
var balance = document.getElementById("balance").value;
var rate = document.getElementById("rate").value;
var tax = document.getElementById("tax").value;
var annualinterest = balance * (rate/100) * tax
var monthlyinterest = annualinterest / 12
monthlyinterest = Math.round(monthlyinterest * 100)/100

document.getElementById("results").innerHTML = "Annual Interest: \u00A3" + annualinterest + "<br> Monthly Interest (not all accounts offer this): \u00A3" + monthlyinterest
}

/////////////////////////////////////////////////////////////////////
//savings goal and date

function payment(rate, nper, pv, fv, type)
{
   nper = parseFloat(nper);
   pv = parseFloat(pv);
   fv = parseFloat(fv);
   rate = parseFloat(rate);
   type = parseFloat(type);
   if ( rate == 0 )
   {
        pmt_value = -((fv + pv)/nper);
   }
   else 
   {
        pmt_value = -((fv+(pv*(Math.pow((1+rate),nper))))/((1+rate*type)*((Math.pow((1+rate),nper)-1)/rate)));
   }
   return (pmt_value);
}
function regsavings() {
//declare variables
var balance = Number(document.getElementById("balance").value);
var rate = Number(document.getElementById("rate").value);
var target = Number(document.getElementById("target").value);
var months = Number(document.getElementById("termmths").value);
var years = Number(document.getElementById("termyears").value);
rate = rate/1200
if (isNaN(months))
{months = 0}
var term = (years * 12) + months
var result = Math.round(payment(rate, term, balance,target*-1,1) * 100) /100
var displayyears = Number(document.getElementById("termyears").value);
var displaymonths = Number(document.getElementById("termmths").value);
if (parseFloat(displayyears) <= 0 || displayyears=='' || displayyears==' ') { displayyears = '0' }
if (parseFloat(displaymonths) <= 0 || displaymonths=='' || displaymonths==' ') { displaymonths = '0' }
if (parseFloat(result) < 0)
		{
			alert ("Over " + displayyears +" years and " + displaymonths + " months, the amount would exceed \u00A3" + target)
			result = 0
		}
var resultoutput = ' '
var decplacelen = 0
var doadd = 0
result = result.toString();
		// Add a decimal places to the output if it has only 1 decimal place
		for (var i=-1; i < result.length; i++)
		{			
			dchar = result.substring(i,i+1)		
			if (doadd == 1){
				decplacelen = decplacelen + 1
			}
			if (dchar == "."){
				doadd = 1
			}
		}
		if (decplacelen == 0) {	resultoutput = result + '.00'}		
		if (decplacelen == 1) { resultoutput = result + '0'	}
		if (decplacelen == 2) {	resultoutput = result }
result = result.toString();
		document.getElementById("result").value = resultoutput
}


/////////////////////////////////////////////////////////////////////
// Calculate BMI Calculator

function calculateBMI(){

//declare variables
var heightm = 	parseFloat(document.getElementById("heightm").value);
var heightf = 	parseFloat(document.getElementById("heightf").value);
var heighti = 	parseFloat(document.getElementById("heighti").value);
var weightkg = 	parseFloat(document.getElementById("weightkg").value);
var weights = 	parseFloat(document.getElementById("weights").value);
var weightp = 	parseFloat(document.getElementById("weightp").value);
if (isNaN(weightp)){weightp = 0;}
if (isNaN(heighti)){heighti = 0;}


// calculate height
var height = 0;
if (isNaN(heightm)) 
	{
		height = ((heightf * 12) + heighti) * 0.0254	
	}
else
	{
	height = heightm
	}

// calculate weight

var weight = 0;
if (isNaN(weightkg)) 
	{
		weight = ((weights * 14) + weightp) * 0.45359237	
	}
else
	{
	weight = weightkg
	}

// calculate BMI

var BMI = weight / (height * height)
BMI = parseInt(BMI*100)/100

// calculate target weights
var targetlower = 18.5 * (height * height)
targetlower = parseInt(targetlower*100)/100
var targethigher = 25 * (height * height)
targethigher = parseInt(targethigher*100)/100

var targetlowerstone = parseInt(targetlower/0.45359237)
var targetlowerstonewhole = parseInt(targetlowerstone/14)
var targetlowerponds = targetlowerstone - (targetlowerstonewhole*14)
var targetlowerstonepounds = targetlowerstonewhole + " stone " + targetlowerponds + "lb"


var targethigerstone = parseInt(targethigher/0.45359237)
var targethigherstonewhole = parseInt(targethigerstone/14)
var targethigherponds = targethigerstone - (targethigherstonewhole*14)
var targethigherstonepounds = targethigherstonewhole + " stone " + targethigherponds + "lb"




// build message
var message = 0;


if (BMI<18.5){
message = "Your Body Mass Index is " + BMI + ". This falls in to the 'Underweight' category.  The target weight range for someone of your height is between " + targetlower + "kg and " + targethigher +"kg. (" + targetlowerstonepounds + " to " + targethigherstonepounds + ".)"
}
else if (BMI<25){
message = "Your Body Mass Index is " + BMI + ". This falls in to the 'Healthy Weight' category.  The target weight range for someone of your height is between " + targetlower + "kg and " + targethigher +"kg. (" + targetlowerstonepounds + " to " + targethigherstonepounds + ".)"
}
else if (BMI<30){
message = "Your Body Mass Index is " + BMI + ". This falls in to the 'Overweight' category.  The target weight range for someone of your height is between " + targetlower + "kg and " + targethigher +"kg. (" + targetlowerstonepounds + " to " + targethigherstonepounds + ".)"
}
else if (BMI<40){
message = "Your Body Mass Index is " + BMI + ". This falls in to the 'Obese' category.  The target weight range for someone of your height is between " + targetlower + "kg and " + targethigher +"kg. (" + targetlowerstonepounds + " to " + targethigherstonepounds + ".)"
}
else if (BMI>39.99){
message = "Your Body Mass Index is " + BMI + ". This falls in to the 'Severely obese' category.  The target weight range for someone of your height is between " + targetlower + "kg and " + targethigher +"kg. (" + targetlowerstonepounds + " to " + targethigherstonepounds + ".)"
}
document.getElementById("results").innerHTML = message
}

///////////////////////////////////////////////////
// Life shortfall calculator

function lifeshortfall(){
// declare variables
var lumpsum = document.getElementById("lumpsum").value; 
lumpsum = parseFloat(lumpsum.replace(/[^0-9.]/g, ''));
var mortgage = document.getElementById("mortgage").value; 
mortgage = parseFloat(mortgage.replace(/[^0-9.]/g, ''));
var loans = document.getElementById("loans").value; 
loans = parseFloat(loans.replace(/[^0-9.]/g, ''));
var funeral = document.getElementById("funeral").value; 
funeral = parseFloat(funeral.replace(/[^0-9.]/g, ''));
var education = document.getElementById("education").value; 
education = parseFloat(education.replace(/[^0-9.]/g, ''));
var other = document.getElementById("other").value; 
other = parseFloat(other.replace(/[^0-9.]/g, ''));
var existing_cover = document.getElementById("existing_cover").value; 
existing_cover = parseFloat(existing_cover.replace(/[^0-9.]/g, ''));

var shortfall = lumpsum + mortgage + loans + funeral + education + other - existing_cover

var message = "<strong> Based on the figures you have given us, the amount of cover you should consider is: \u00A3" + shortfall + ".</strong> <br><br>Detailed information is below: <br><br><table width='500' border='1' cellspacing='0' cellpadding='0'><tr><td width='50%'> <strong>Cover area</strong></td><td width='50%'><strong>Amount</strong></td></tr><tr><td>Lump sum for your dependants</td><td>\u00A3" + lumpsum  + "</td></tr><tr><td>Outstanding mortgage or debts</td><td>\u00A3" + mortgage +  "</td></tr><tr><td>Other outstanding loans</td><td>\u00A3" + loans + "</td></tr><tr><td>Funeral expenses</td><td>\u00A3" + funeral + "</td></tr><tr><td>Education costs</td><td>\u00A3" + education  + "</td></tr><tr><td>Other expenses</td><td>\u00A3" + other +  "</td></tr><tr><td>Life insurance and savings</td><td>\u00A3" + existing_cover + "</td></tr><tr><td><strong>Total life insurance cover</strong></td><td>\u00A3" + shortfall + "</td></tr></table>The figures above are indicative only, if you require advice you should speak to one of our advisers"


document.getElementById("results").innerHTML = message
}

//////////////////////////////////////////////////////////

//Life style Calculator

function lifestyle() {
// alcohol consumption

// declare variables
var beerunits = document.getElementById("alc_beer").value;
var wineunits = document.getElementById("alc_wine").value;
var spiritunits = document.getElementById("alc_spirit").value;
var nullcheck = 0
beerunits			=	parseFloat(beerunits.replace(/[^0-9.]/g, ''));
wineunits			=	parseFloat(wineunits.replace(/[^0-9.]/g, ''));
spiritunits			=	parseFloat(spiritunits.replace(/[^0-9.]/g, ''));
if (isNaN(beerunits)){		beerunits = 0; nullcheck = nullcheck + 1	}
if (isNaN(wineunits)){		wineunits = 0; nullcheck = nullcheck + 1	}
if (isNaN(spiritunits)){		spiritunits = 0; nullcheck = nullcheck + 1	}

var genderindex = document.getElementById("gender").selectedIndex;
var gender = document.getElementById('gender')[genderindex].value;
var units = wineunits + spiritunits + (2*beerunits)
var alcscore = 0 
var alcimage = "http://www.lcplc.co.uk/assets/calculators/images/0.gif"

if (gender=="male")
{
	if (units<29) {alcimage="http://www.lcplc.co.uk/assets/calculators/images/5.gif"; alcscore=5; }
	else if (units<36) {alcimage="http://www.lcplc.co.uk/assets/calculators/images/4.gif"; alcscore=4}
	else if (units<41) {alcimage="http://www.lcplc.co.uk/assets/calculators/images/3.gif"; alcscore=3}
	else if (units<46) {alcimage="http://www.lcplc.co.uk/assets/calculators/images/2.gif"; alcscore=2}
	else if (units<51) {alcimage="http://www.lcplc.co.uk/assets/calculators/images/1.gif"; alcscore=1}
	else {alcimage="http://www.lcplc.co.uk/assets/calculators/images/0.gif"; alcscore=0;}
}

else if (gender=="female")
{
	if (units<22) {alcimage="http://www.lcplc.co.uk/assets/calculators/images/5.gif"; alcscore=5}
	else if (units<26) {alcimage="http://www.lcplc.co.uk/assets/calculators/images/4.gif"; alcscore=4}
	else if (units<31) {alcimage="http://www.lcplc.co.uk/assets/calculators/images/3.gif"; alcscore=3}
	else if (units<36) {alcimage="http://www.lcplc.co.uk/assets/calculators/images/2.gif"; alcscore=2}
	else if (units<41) {alcimage="http://www.lcplc.co.uk/assets/calculators/images/1.gif"; alcscore=1}
	else {alcimage="http://www.lcplc.co.uk/assets/calculators/images/0.gif"; alcscore=0}
}
if (nullcheck == 3) {alcimage="http://www.lcplc.co.uk/assets/calculators/images/error.gif";}
document.getElementById("result_alc").innerHTML = '<img src="' + alcimage +'" width="204" height="43">'
//Excersise

// declare variables

var excerhours = document.getElementById("excer").value;
var excerimage = "http://www.lcplc.co.uk/assets/calculators/images/0.gif"
var excerscore = 0
var excererror = 0

excerhours			=	parseFloat(excerhours.replace(/[^0-9.]/g, ''));
if (isNaN(excerhours)){		excererror = 1; }

	if (excerhours>2.5) {excerimage="http://www.lcplc.co.uk/assets/calculators/images/5.gif"; excerscore=5}
	else if (excerhours>2) {excerimage="http://www.lcplc.co.uk/assets/calculators/images/4.gif"; excerscore=4}
	else if (excerhours>1.5) {excerimage="http://www.lcplc.co.uk/assets/calculators/images/3.gif"; excerscore=3}
	else if (excerhours>1) {excerimage="http://www.lcplc.co.uk/assets/calculators/images/2.gif"; excerscore=2}
	else if (excerhours>0.5) {excerimage="http://www.lcplc.co.uk/assets/calculators/images/1.gif"; excerscore=1}
	else {excerimage="http://www.lcplc.co.uk/assets/calculators/images/0.gif"; excerscore=0}
	if (excererror == 1 ) {excerimage="http://www.lcplc.co.uk/assets/calculators/images/error.gif";}

document.getElementById("result_exer").innerHTML = '<img src="' + excerimage +'" width="204" height="43">'

//Excersise

// declare variables

var bmi = document.getElementById("bmi").value;
bmi			=	parseFloat(bmi.replace(/[^0-9.]/g, ''));

var bmiimage = "http://www.lcplc.co.uk/assets/calculators/images/0.gif"
var bmiscore = 0
var bmierror = 0
if (isNaN(bmi)){		bmierror = 1	}
	if (bmi>13.5) {bmiimage="http://www.lcplc.co.uk/assets/calculators/images/1.gif"; bmiscore=1} 
	if (bmi>14.5) {bmiimage="http://www.lcplc.co.uk/assets/calculators/images/2.gif"; bmiscore=2}
	if (bmi>15.5) {bmiimage="http://www.lcplc.co.uk/assets/calculators/images/3.gif"; bmiscore=3}
	if (bmi>16.5) {bmiimage="http://www.lcplc.co.uk/assets/calculators/images/4.gif"; bmiscore=4}
	if (bmi>18.5) {bmiimage="http://www.lcplc.co.uk/assets/calculators/images/5.gif"; bmiscore=5}
	if (bmi>24.9) {bmiimage="http://www.lcplc.co.uk/assets/calculators/images/4.gif"; bmiscore=4}
	if (bmi>26.9) {bmiimage="http://www.lcplc.co.uk/assets/calculators/images/3.gif"; bmiscore=3}
	if (bmi>27.9) {bmiimage="http://www.lcplc.co.uk/assets/calculators/images/2.gif"; bmiscore=2}
	if (bmi>28.9) {bmiimage="http://www.lcplc.co.uk/assets/calculators/images/1.gif"; bmiscore=1}
	if (bmi>29.9) {bmiimage="http://www.lcplc.co.uk/assets/calculators/images/0.gif"; bmiscore=0}
	if (bmierror == 1 ) {bmiimage="http://www.lcplc.co.uk/assets/calculators/images/error.gif";}
	
	document.getElementById("result_bmi").innerHTML = '<img src="' + bmiimage +'" width="204" height="43">'

//Diet

// declare variables

var diet = document.getElementById("fruit").value;
diet			=	parseFloat(diet.replace(/[^0-9.]/g, ''));

var dietimage = "http://www.lcplc.co.uk/assets/calculators/images/0.gif"
var dietscore = 0
var dieterror = 0
if (isNaN(diet)){		dieterror = 1	}
	
	if (diet>0.9) {dietimage="http://www.lcplc.co.uk/assets/calculators/images/1.gif"; dietscore=1}
	if (diet>1.9) {dietimage="http://www.lcplc.co.uk/assets/calculators/images/2.gif"; dietscore=2}
	if (diet>2.9) {dietimage="http://www.lcplc.co.uk/assets/calculators/images/3.gif"; dietscore=3}
	if (diet>3.9) {dietimage="http://www.lcplc.co.uk/assets/calculators/images/4.gif"; dietscore=4}
	if (diet>4.9) {dietimage="http://www.lcplc.co.uk/assets/calculators/images/5.gif"; dietscore=5} 
	if (dieterror == 1 ) {dietimage="http://www.lcplc.co.uk/assets/calculators/images/error.gif";}
	
	document.getElementById("result_fruit").innerHTML = '<img src="' + dietimage +'" width="204" height="43">'
	
	//Water

// declare variables

var water = document.getElementById("water").value;
water			=	parseFloat(water.replace(/[^0-9.]/g, ''));

var waterimage = "http://www.lcplc.co.uk/assets/calculators/images/0.gif"
var waterscore = 0
var watererror = 0
if (isNaN(water)){		watererror = 1	}
	
	if (water>0.9) {waterimage="http://www.lcplc.co.uk/assets/calculators/images/1.gif"; waterscore=1}
	if (water>2) {waterimage="http://www.lcplc.co.uk/assets/calculators/images/2.gif"; waterscore=2}
	if (water>3) {waterimage="http://www.lcplc.co.uk/assets/calculators/images/3.gif"; waterscore=3}
	if (water>4) {waterimage="http://www.lcplc.co.uk/assets/calculators/images/4.gif"; waterscore=4}
	if (water>5) {waterimage="http://www.lcplc.co.uk/assets/calculators/images/5.gif"; waterscore=5} 
	if (watererror == 1 ) {waterimage="http://www.lcplc.co.uk/assets/calculators/images/error.gif";}
	
	document.getElementById("result_water").innerHTML = '<img src="' + waterimage +'" width="204" height="43">'
	
	//Smoker

// declare variables

var smokerindex = document.getElementById("smoker").selectedIndex;
var smoker = document.getElementById('smoker')[smokerindex].value;

var smokerimage = "http://www.lcplc.co.uk/assets/calculators/images/0.gif"
var smokerscore = 0

	
	if (smoker == "yes") {smokerimage="http://www.lcplc.co.uk/assets/calculators/images/0.gif"; smokerscore=1}
	if (smoker == "no") {smokerimage="http://www.lcplc.co.uk/assets/calculators/images/5.gif"; smokerscore=5}
	
	document.getElementById("result_smoking").innerHTML = '<img src="' + smokerimage +'" width="204" height="43">'
	
	// Summary
	
	var AlcoholSummary
	var ExcersiseSummary
	var BMISummary
	var DietSummary
	var WaterSummary
	var SmokingSummary
	
	
	if (alcscore<5){
	if (gender=="male"){
	AlcoholSummary="<li>You drink more Alcohol than the recommended 28 units for a male </li>"
	}
	else{AlcoholSummary="<li>You drink more Alcohol than the recommended 21 units for a female.</li>"}
	} else AlcoholSummary=""
	
	
	if (excerscore<5){ExcersiseSummary="<li>You don't get enough excercise, it is recommended that you take a minimum of 30 minutes moderate intensity excercise at least 5 times per week - that's a minimum of 2.5 hours. </li>"} else ExcersiseSummary=""
	
	if (dietscore<5){DietSummary="<li>You eat less than the recommended 5 portions of fruit per day. </li>"} else DietSummary=""
	if (waterscore<5){WaterSummary="<li>You drink less than the recommended 2.5 litres (6/7 glasses) of water per day. </li>"} else WaterSummary=""
	if (smokerscore<5){SmokingSummary="<li>You smoke, eating 5 portions of fruit or doing regular excercise means little if you continue to smoke</li>"} else SmokingSummary=""
	
	if (bmiscore<5)
	{
	if (bmi<21){BMISummary="<li>You are considered under weight for your height. </li>"}
	else{BMISummary="<li>You are considered over weight for your height. </li>"}
	} else {BMISummary=""}
	
	
	
	var score = smokerscore +  waterscore + dietscore + bmiscore + excerscore + alcscore
	var avgscore = Math.round(score / 6);
	var avgscoreimage = "<img src='http://www.lcplc.co.uk/assets/calculators/images/" + avgscore + ".gif' width='204' height='43'>"
	
	
	var summary = avgscoreimage +  "<div style='clear:both;'>Your overall score is <b> " + score + " out of 30. </b> You could improve on the following areas:<br> <ul>" + AlcoholSummary + ExcersiseSummary + BMISummary + DietSummary + WaterSummary + SmokingSummary + "</ul></div>"
	
	document.getElementById("result_summary").innerHTML = summary
	
}