﻿// work out the return from a lump sum investment
function LumpSum()
{
    // get the input numbers
    var sum = Number($('sum').value, 'Lump sum amount');
    var period = Number($('period').value, 'Investment period');
    var rate = Number($('rate').value, 'Annual interest rate');
    
    // if all the numbers are valid
    if (sum !== false && period !== false && rate !== false)
    {
        // generate the interest amount
        var interest = (rate / 100) / 12;
        // calculate the months
        var months = period * 12;
        // calculate the growth
        var x = sum * (Math.pow(1 + interest, months));
		sum = Currency(sum);
        // return the growth amount
        DisplayCalculation(Currency(x), 'An investment of ' + sum + ' over ' + period + ' years would grow to ', 'success');
    }
}

// work out the return from regular savings
function RegularSavings()
{
    // get the input numbers
	var initial = Number($('initial').value, 'Initial investment amount', true);
    var sum = Number($('sum').value, 'Monthly savings amount');
    var period = Number($('period').value, 'Investment period');
    var rate = Number($('rate').value, 'Annual interest rate');
    
    // if all the numbers are valid
    if (sum !== false && period !== false && rate !== false)
    {
        // generate the interest amount
        var interest = (rate / 100) / 12;
        // calculate the months
        var months = period * 12;
        // calculate the growth on initial investment
        var x = initial * (Math.pow(1 + interest, months));
		// calculate the growth on the regular savings
		var y = (sum * ((Math.pow(1 + interest, months)) - 1)) / interest;
		// add the amounts together
		var z = x + y;
		// get the investment amount
		var investment = Currency(sum);
		// get the investment amount
		var initial = Currency(initial);
		// get the growth amount
		var total = Currency(z);
		// if the total is OK
		if (total)
		{
			// return the growth amount
			DisplayCalculation(total, 'The initial investment of ' + initial + ' plus a monthly investment of ' + investment + ' over ' + period + ' years would grow to ', 'success');
		} else {
			alert('The total could not be calculated. Please ensure the numbers are correct.');
		}
    }
}

// work out the savings needed for a target amount
function TargetSavings()
{
	// get the input numbers
	var target = Number($('target').value, 'Target amount');
    var period = Number($('period').value, 'Investment period');
    var rate = Number($('rate').value, 'Annual interest rate');
	
	// if all the numbers are valid
    if (target !== false && period !== false && rate !== false)
    {
        // generate the interest amount
        var interest = rate / 100;
		// calculate the single sum investment needed
		var lump = target / (Math.pow(1 + interest, period));		
        // calculate the months
        var months = period * 12;
		// calculate the monthly savings needed
		interest = Math.pow(1 + interest, 1 / 12) - 1;
		var regular = Math.pow(1 + interest, period * 12);
		regular = (interest * target) / (-1 + regular);
		// get the investment amount
		var investment = Currency(lump);
		// get the regular amount
		var monthly = Currency(regular);
		// get the target
		target = Currency(target);
		// if the totals are OK
		if (target && investment && monthly)
		{
			// return the growth amount
			DisplayCalculation(monthly, 'To reach your target of ' + target + ' over ' + period + ' years you need to invest either <strong>' + investment + '</strong> as a lump sum now, or save a monthly amount of ', 'success');
		} else {
			alert('The total could not be calculated. Please ensure the numbers are correct.');
		}
    }
}

// work out the maximum mortgage amount
function MaximumMortgage()
{
	// get the input numbers
	var salary1 = Number($('salary1').value, 'Your salary');
    var salary2 = Number($('salary2').value, 'Partner salary', true);
    var multiplier = Number($('multiplier').value, 'Salary multiplier');
	
	// if all the numbers are valid
    if (salary1 !== false && salary2 !== false && multiplier !== false)
    {
		// add the salaries
		var salary = parseFloat(salary1) + parseFloat(salary2);
		// multiply the salaries
		var amount = salary * multiplier;
		// get the mortgage
		var mortgage = Currency(amount);
		// if the totals are OK
		if (mortgage)
		{
			// return the mortgage amount
			DisplayCalculation(mortgage, 'Based on you and your partners salary you could borrow ', 'success');
		} else {
			alert('The total could not be calculated. Please ensure the numbers are correct.');
		}
    }
}

// work out the monthly mortgage repayment amount
function MortgageRepayments()
{
	// get the input numbers
	var mortgage = Number($('mortgage').value, 'Mortgage amount');
    var years = Number($('years').value, 'Mortgage length');
    var interest = Number($('interest').value, 'Average annual interest rate');
	
	// if all the numbers are valid
    if (mortgage !== false && years !== false && interest !== false)
    {
		// divide interest by 100
		var interestamount = interest / 100;
		// work out the capital and interest amount
		var capitalandinterest = ((mortgage * interestamount) / 12) * (1 / (1 - (Math.pow(1 / (1 + interestamount), years))));
		capitalandinterest = Currency(capitalandinterest);
		// work out the interest only amount
		var interestonly = ((mortgage * 0.12) / 12) * (1 / (1 - (Math.pow((1 / 1.12), years))));
		interestonly = (mortgage * interestamount)/12;
		interestonly = Currency(interestonly);
		interest = Round(interest, 2);
		// if the totals are OK
		if (capitalandinterest && interestonly)
		{
			// return the mortgage amount
			DisplayCalculation('', 'With an interest rate of ' + interest + '% on your mortgage of £' + mortgage + ' you can expect to pay <strong>' + capitalandinterest + '</strong> monthly for a capital and interest repayment plan, or <strong>' + interestonly + '</strong> monthly for an interest only repayment plan.', 'success');
		} else {
			alert('The total could not be calculated. Please ensure the numbers are correct.');
		}
    }
}

// work out profit/loss
function ProfitLoss()
{
	// get the input numbers
	var sales = Number($('sales').value, 'Sales amount');
    var costs = Number($('costs').value, 'Costs amount');
	
	// if all the numbers are valid
    if (sales !== false && costs !== false)
    {

		// calculate the amount to break even
		var profitlosspercent = 100 - (100 * (costs / sales));
		var profitloss = sales - costs;
		profitloss = Currency(profitloss);
		profitlosspercent = Round(profitlosspercent, 2);
	
		if (profitloss)
		{
			// return the break even amount
			DisplayCalculation(profitloss, 'Your profit/loss is <strong>' + profitlosspercent + '%</strong> of your sales, an amount of ', 'success');
		} else {
			alert('The total could not be calculated. Please ensure the numbers are correct.');
		}
	}
}

// validate a number
function Number(num, field, passthrough)
{
    // convert number to a string
    num = num.toString();
    // replace pound signs
    num = num.replace('£', '');
    // replace any non-numberic or decimal place characters
    num = num.replace(/[^\.0-9]/g, '');
	// if more than one decimal place has been give, discard everything after the second one
	if (num.indexOf('.') != -1)
	{
		var n = new Array();
		n = num.split('.');
		num = n[0] + '.' + n[1];
	}
    // check the number is OK
    if (num == '')
    {
		// if the script should die
		if (!passthrough)
		{
			// show an error
			alert('Please enter a valid number in the ' + field + ' field');
			return false;
		} else {
			// return 0
			return 0;
		}
    } else {
        // return the number
        return num;
    }
}

// round a number to a specified number of decimal places
function Round(number, decimalplaces)
{
	// see if the number is a power
	var exp = /^([+-])?(\d+).?(\d*)[eE]([-+]?\d+)$/.test(number);
	// if the number is OK
	if (!exp)
	{
		// split up decimal places
	    var parts = number.toString().split('.');
	    // get the decimal places
	    if (parts[1])
	    {
	        number = parts[0] + '.' + Math.round(parts[1].substring(0, decimalplaces) + '.' + parts[1].substring((decimalplaces + 1)));
	    }
		return number;
	} else {
		return false;
	}
}

// format a number as currency
function Currency(number)
{
	// see if the number is a power
	var exp = /^([+-])?(\d+).?(\d*)[eE]([-+]?\d+)$/.test(number);
	// if the number is OK
	if (!exp)
	{
	    // split up the pounds and pence
	    var parts = number.toString().split('.');
	    // get the pence
	    if (!parts[1])
	    {
	        var pence = '00';
	    } else {
	        var pence = parts[1];
	    }
	    if (pence.length > 2){ pence = pence.substring(0, 2); }
	    if (pence.length == 1){ pence = pence + '0'; }
	    // get the pounds
	    var pounds = parts[0];
	    // if the number is more than 999 add commas between thousands
	    if (pounds.length > 3)
	    {
	        var out = '';
	        // split the pounds into parts of three
	        for (commas = 0; commas < (pounds.length / 3); commas++)
	        {
	            // for each thousand group add a comma
	            out = ',' + pounds.substring((pounds.length - ((commas + 1) * 3)), (pounds.length - (commas * 3))) + out;
	        }
	        // remove the extraneous comma from the front of the pounds
	        pounds = out.substring(1);
	    }
	    // return the full amount
	    return '£-€-US$ ' + pounds + '.' + pence;
	} else {
		return false;
	}
}

// display a single amount calculation
function DisplayCalculation(amount, message, className)
{
	var output = $('output');
	if (output)
	{
		output.innerHTML = message + '<strong>' + amount + '</strong>';
		output.className = className;
	}
}