<!--


  //////////////////////////////////////////////////////////
 //  START FUNCTIONS FOR "HOW MUCH CAN I BORROW?" FORM   //
//////////////////////////////////////////////////////////


function moneyFormat(input) {
  var dollars = Math.floor(input)
  var cents  = "" + Math.round(input * 100)
  cents = cents.substring(cents.length-2, cents.length)
  if (cents == "0") {
    input = dollars + ".00"
  }
  else {
    input = dollars + "." + cents
  }
  return input
}

function comma_currency(anynum) {
   //-- Returns passed number as string in $xxx,xxx.xx format.
	 anynum = eval(anynum)

   workNum = Math.abs((Math.round(anynum*100)/100));
	 workStr = ""+ workNum;
	 
   if (workStr.indexOf(".")== -1) { 
	   workStr += ".00"
	 }

	 dStr = workStr.substr(0,workStr.indexOf("."));
	 dNum = dStr-0;
   pStr = workStr.substr(workStr.indexOf("."));
   while (pStr.length < 3) { 
	   pStr+="0"
	 }

   //--- Adds comma in thousands place.
   if (dNum>=1000) {
      dLen=dStr.length
      dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
   }

   //-- Adds comma in millions place.
   if (dNum>=1000000) {
      dLen=dStr.length
      dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
   }
	 
   //retval = dStr + pStr 
	 retval = dStr;
   //-- Put numbers in parentheses if negative.
   if (anynum<0) {retval="("+retval+")"}
	 return "$"+retval;
}

function currency(value, padding, decimals) {
		//value = Math.abs(value);
			var before = Math.floor(value);
			var after  = value - before;
	
		before = before.toString();
		if (before == 'NaN') before = '0';
		while(before.length < padding)
						before = ' ' + before;
			
		after = Math.round(after * Math.pow(10,decimals));
		after = after.toString();
		if (after == 'NaN') after = '0';
		while (after.length < decimals)
						after = '0' + after;
	
		var string = (before + '.' + after);
		return string;
	}


// Given an income, return the 
// cost of living per annum
function getCostOfLiving(incomeValue, whichIncome) {
  
  var livingCosts = 0;
  var numAdults    = Math.ceil(document.how_much.num_adults.value);
  var numKids      = Math.ceil(document.how_much.num_kids.value);

  if (incomeValue >= 55001) {
    livingCosts = (incomeValue/100) * 40;
  }
  else if (incomeValue >= 20001) {
    livingCosts = (incomeValue/100) * 35;
  }
  else if (incomeValue >= 15001) {
    livingCosts = (incomeValue/100) * 25;
  }
  else if (incomeValue >= 10001) {
    livingCosts = (incomeValue/100) * 15;
  }
  else {
    livingCosts = (incomeValue/100) * 10;
  }

	return livingCosts;  
}

function update(fieldIndex, readableName) {
  
	// check for valid number
  data = document.how_much[fieldIndex].value;

	if (data == '') {
    if ((fieldIndex == 0) || 
	    (fieldIndex == 1) ||
			(fieldIndex == 2) ||
			(fieldIndex == 3) ||
			(fieldIndex == 4) ||
			(fieldIndex == 5) ||
			(fieldIndex == 6)) {
	    return 0;
	  }
	}
	
	if (!(data >= 0)) {
		alert(readableName + ' contains invalid data: ' + data);
	  document.how_much[fieldIndex].value = '';
	  document.how_much[fieldIndex].focus();
	  return 0;
  }
}

function get_net_income(income) {
  // Find max tax value for income1

	var tax1 = ((income - 6000) * 0.15);
	var tax2 = ((income - 34000) * 0.3)  + 4200;
	var tax3 = ((income - 80000) * 0.4) +  18000;
	var tax4 = ((income - 180000) * 0.45) + 58000;

	var maxTax = tax1;
	if (tax2 > maxTax) maxTax = tax2;
	if (tax3 > maxTax) maxTax = tax3;
	if (tax4 > maxTax) maxTax = tax4;		  
	return (income - maxTax);
}

function process_loan() {

	var inc1 = parseFloat(document.how_much.gross_income_1.value);
	var inc2 = parseFloat(document.how_much.gross_income_2.value);

	var cost1, cost2 =0;
	var total_utilised_pm = 0;

	if (!(inc1 > 0) && !(inc2 > 0)){
	  alert ('You must enter at least one income.');
		document.how_much.gross_income_1.focus();
		return;
	}

	if (inc1 > 0) 
		cost1 = getCostOfLiving(inc1, '1');
	if (inc2 > 0) 
		cost2 = getCostOfLiving(inc2, '2');

	if ((inc1 > 0) && !(inc2 > 0)){
		total_utilised_pm = cost1/12;
	}
	if ((inc2 > 0) && !(inc1 > 0)){
		total_utilised_pm = cost2/12;
	}
	if ((inc1 > 0) && (inc2 > 0))  {
		total_utilised_pm = (cost1 + cost2)/12;
	}

//	total_utilised_pm = getCostOfLiving((inc1+inc2), '3')/12;

	// Term can't be empty:
	var term = parseFloat(document.how_much.term.value);

	if (!(term > 0 ))	{
		alert('You must enter a loan term.');
		document.how_much.term.focus();
		return 0;
	}

	var rent = parseFloat(document.how_much.rental_income.value);
	if (!(rent > 0)) rent = 0;

	var allowed_repayment = moneyFormat(total_utilised_pm + rent);

	var c = parseFloat(document.how_much.cc_limits.value) * 0.025;
	var o = parseFloat(document.how_much.other_monthly_loans.value);
	if (!(c > 0)) c = 0;
	if (!(o > 0)) o = 0;
	var outgoings = c + o;

	var rate1 = parseFloat(document.how_much.rate1.value);
	var pmt  = allowed_repayment - outgoings;
	var rate1 = rate1 / 1200;
	term = term * 12;
	var loan_amnt1 = pmt * ( (1 - Math.pow(1 + rate1, -term)) / rate1);
	var loan_amnt2 = get_alternate_max_loan();

	if (loan_amnt1 < 0) loan_amnt1 = 0;
	if (loan_amnt2 < 0) loan_amnt2 = 0;

	var most = 0;
	if (loan_amnt1 > loan_amnt2)
		document.how_much.result.value = '$' + comma_currency(loan_amnt1);
	else
		document.how_much.result.value = comma_currency(loan_amnt2);
}



function get_alternate_max_loan() {

	var f = document.how_much;

	var base_income1 = currency(f.gross_income_1.value, 7, 2);
	var base_income2 = currency(f.gross_income_2.value, 7, 2);
	if (!(base_income1 > 0)) base_income1 = 0;
	if (!(base_income2 > 0)) base_income2 = 0;

	var total_income = base_income1 + base_income2;
	var rate2 = parseFloat(f.rate2.value) / 1200;
	var term = parseFloat(f.term.value) * 12;

	var c = parseFloat(f.cc_limits.value) * 0.02;
	var o = parseFloat(f.other_monthly_loans.value);
	if (!(c > 0)) c = 0;
	if (!(o > 0)) o = 0;
	var total_outgo = (c + o) * 12;

	var rent = parseFloat(f.rental_income.value);
	if (!(rent > 0)) rent = 0;

	var net_income1      = 0;
	var net_income2      = 0;
	var net_income_total = 0;
	if (base_income1 > 0) net_income1 = get_net_income(base_income1);
	if (base_income2 > 0) net_income2 = get_net_income(base_income2);
	net_income_total = net_income1 + net_income2;

	var living_expenses  = 0;
	var first_adult      = 13836;
	var first_child      = 4908;
	var subsequent_adult = 6240;
	var subsequent_child = 4908;
	var medical_expenses = 0;

	var num_adults       = parseInt(f.num_adults.value);
	var num_kids         = parseInt(f.num_kids.value);
	if (!(num_adults > 0)) num_adults = 1; // we need at least one adult!
	if (!(num_kids > 0))   num_kids = 0;

	if (num_adults > 0) {
		living_expenses += (num_adults - 1) * subsequent_adult + first_adult;
		living_expenses += medical_expenses;
	}
	if (num_kids > 0) {
		living_expenses += (num_kids - 1) * subsequent_child + first_child;
	}
	var net_available_total	= net_income_total - living_expenses;

	var pmt = ((net_available_total/1.05) - total_outgo) / 12;
	var pv  = pmt * ((1 - Math.pow(1 + rate2, -term)) / rate2);
	return pv;
}


  ////////////////////////////////////////////////////////
 //  END FUNCTIONS FOR "HOW MUCH CAN I BORROW?" FORM   //
////////////////////////////////////////////////////////


  //////////////////////////////////////////////////////
 //  START CODE FOR "QUICK LOAN CALCULATIONS" FORM   //
//////////////////////////////////////////////////////
gtotalmonth = 0

function isFieldBlank(theField) {
  if(theField.value.length == 0) {
   alert("All fields must be completed.")
   theField.focus()
   return true
  }
  else
   return false
}

function checkNumber(input, msg) {
  msg = msg + " field has invalid data: " + input.value;
  var str = input.value;
  for (var i = 0; i < str.length; i++) {
   var ch = str.substring(i, i + 1)
   if ((ch < "0" || "9" < ch) && ch != '.') {
     alert(msg);
     input.focus()
     input.select()
     return false;
   }
  }
  input.value = str;
  return true;
}

function balanceFormat(input) {
  var dollars = 0
  var cents = 0
  if (input < 0) {
    dollars = Math.ceil(input)
  }
  else {
   dollars = Math.floor(input)
  }
  cents  = "" + Math.round(input * 100)
  cents = cents.substring(cents.length-2, cents.length)
  if ((input < 0) && (input > -1) && (cents == "0")) {
   input = "-" + dollars + ".00"
  }
  else if ((input < 0) && (input > -1) && (cents != "0")) {
   input = "-" + dollars + "." + cents
  }
  else if ((input >=0) || (input < -1)) {
   if (cents == "0") {
     input = dollars + ".00"
   }
   else {
     input = dollars + "." + cents
   }
  }
  return input
}

function calc_repayment(form) {

// Validate Input
 if  (isFieldBlank(form.borrow) == true) 
 return false

 if  (!checkNumber(form.borrow, "Borrow Amount"))
   return false
 if  (!checkNumber(form.years, "Years"))
   return false
 if  (!checkNumber(form.intRate, "Interest Rate"))
   return false
  
 if (form.borrow.value == 0) {
	alert('Borrow amount cannot be zero!');
	form.borrow.focus();	
	form.borrow.select();	
        return false;
 }
 if (form.intRate.value == 0) {
	alert('Cannot have 0% interest rate!');
	form.intRate.focus();	
	form.intRate.select();	
        return false;
 }
 if (form.years.value == 0) {
	alert('Cannot have 0 years!');
	form.years.focus();	
	form.years.select();	
        return false;
 }
// Get Input values
gborrow = parseFloat(form.borrow.value)
gyears = parseFloat(form.years.value)
gintRatemonth= (parseFloat(form.intRate.value) / 100) / 12

// Perform calculations
gintfullmonth =  gintRatemonth + 1
gtotaltimemonth = -(gyears * 12)
gexpmonth =  Math.pow(gintfullmonth, gtotaltimemonth)
gbtmmonth = 1 - gexpmonth
gtotalmonth = (gborrow * gintRatemonth) / gbtmmonth
//gtotalmonth = balanceFormat(gtotalmonth)
//gtotalmonth = moneyFormat(gtotalmonth)
gborrow = moneyFormat(gborrow)
form.borrow.value = gborrow
form.monthly.value = comma_currency(gtotalmonth);
 
return true

}

function calcPeriod() {

  LoanAmt = parseFloat(document.calc.loan_value.value);
  Rate = parseFloat(document.calc.rate.value);
  Payment = parseFloat(document.calc.repayment_value.value);


 if  (!checkNumber(document.calc.loan_value, "Borrow Amount"))
   return false
 if  (!checkNumber(document.calc.rate, "Interest Rate"))
   return false
 if  (!checkNumber(document.calc.repayment_value, "Repayment Amount"))
   return false
  
 if (document.calc.loan_value.value == 0) {
	alert('Borrow Amount cannot be zero!');
	document.calc.loan_value.focus();	
	document.calc.loan_value.select();	
   return false;
 }
 if (document.calc.rate.value == 0) {
	alert('Cannot have 0% interest rate!');
	document.calc.rate.focus();	
	document.calc.rate.select();	
   return false;
 }
 if (document.calc.repayment_value.value == 0) {
	alert('Repayment Amount cannot be 0!');
	document.calc.repayment_value.focus();	
	document.calc.repayment_value.select();	
   return false;
 }

  if (Rate >= 1) { Rate /= 100; }
  Rate /= 12;

  if (Payment - LoanAmt*Rate < 0) {
    alert("Payment amount too small.\nIt must be at least $" +
          (Math.ceil(LoanAmt*Rate)).toString());
    return;
  }
  
  with (Math) {
    months = ceil(log(Payment / (Payment - LoanAmt*Rate)) /
                  log(1 + Rate));
  }

  /*
  LoanAmt = balanceFormat(LoanAmt);
  LoanAmt = moneyFormat(LoanAmt);
  Rate    = balanceFormat(Rate);
  Rate    = moneyFormat(Rate);
  Payment = balanceFormat(Payment);
  Payment = moneyFormat(Payment);
  */

  //alert('months: ' + Period);
  //alert('years: ' + years);
	var modulus = months % 12;  
	var years   = (months - modulus) / 12;
  var month_q = "";
	var year_q  = "";
  var result  = "";
	
	if (modulus == 1) month_q = "month";
	else month_q = "months";

  if (years == 1) year_q = "year";
	else year_q = "years";

  if (modulus == 0)
	  result = years + " " + year_q;
	if (years == 0)
	  result = modulus + " " + month_q;
	if ((modulus > 0) && (years > 0))
	  result = years + " " + year_q + ", " + modulus + " " + month_q;

	document.calc.term.value = result;

}

function clearRepaymentForm(form) {
 form.borrow.value = "350000.00"
 form.intRate.value = "5.79"
 form.years.value = "30"
 form.monthly.value = ""
}

function clearTermForm(form) {
 form.loan_value.value = "300000.00"
 form.rate.value = "5.79"
 form.repayment_value.value = "1900.00"
 form.term.value = ""
}

  ////////////////////////////////////////////////////
 //  END CODE FOR "QUICK LOAN CALCULATIONS" FORM   //
////////////////////////////////////////////////////

//-->