
function goal(obj) {
	g=Math.abs(obj.SavingsGoal.value)
	t=getListValue(obj.term)
	b=obj.InterestRate.value		
	f=getListValue(obj.frequency)

	r=eval((b/100)/f);			// Rate per period
	n=eval(t*f);				//Number of periods	

	d = eval((g * r)/((1 + r) * (Math.pow((1 + r),n) - 1)));
	
	if (f==1 && f > t) {
		alert('Deposit Frequency cannot be greater than Time Frame');
		obj.contribution.value="Error";
	}
	else {
		obj.contribution.value=formatCurrency(d);
	}
}

function getListValue(obj) {  
	for (var i = 0; i < obj.length; i++) {      
		if (obj.options[i].selected == true) {         
			return obj.options[i].value      
		}   
	}   
	return null
}

function formatCurrency(number) {
	var num = new String(number);
	if(num.indexOf(".") == -1) {
		intLen = num.length;
		toEnd = intLen;
		var strLeft = new String(num.substring(0, toEnd));
		var strRight = new String("00");
	}
	else {
		pos = eval(num.indexOf("."));
		var strLeft = new String(num.substring(0, pos));
		intToEnd = num.length;
		intThing = pos + 1;
		var strRight = new String(num.substring(intThing, intToEnd));
			
		if(strRight.length > 2) {
			nextInt = strRight.charAt(2);
			if (nextInt >= 5) {
				strRight = new String(strRight.substring(0, 2));
				strRight = new String(eval((strRight * 1) + 1));
				if((strRight * 1) >= 100) {
					strRight = "00";
					strLeft = new String(eval((strLeft * 1) + 1));
				}				
				if(strRight.length <= 1) {
					strRight = new String("0" + strRight);
				}
			}
			else {
				strRight = new String(strRight.substring(0, 2));
			}
		}
		else {
			if(strRight.length != 2) {
				strRight = strRight + "0";
			}
		}
	}
	if(strLeft.length > 3) {
		var curPos = (strLeft.length - 3);
		while(curPos > 0) {
			var remainingLeft = new String(strLeft.substring(0, curPos));
			var strLeftLeft = new String(strLeft.substring(0, curPos));
			var strLeftRight = new String(strLeft.substring(curPos, strLeft.length));
			strLeft = new String(strLeftLeft + "," + strLeftRight);
			curPos = (remainingLeft.length - 3);
		}
	}

	strWhole = strLeft + "." + strRight;
	finalValue = "$" + strWhole;
	return(finalValue);
}


function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') {
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (val<min || max<val) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function loanamt(obj) {
	d=Math.abs(obj.RegularRepayment.value)
	b=obj.InterestRate.value	
	y=obj.LoanTerm.value
		
	r = eval(b/1200);
	t = eval(Math.ceil(y*12)) 

	a = eval(d * (1 - Math.pow((r + 1),-t))/r);
	
	if (y <= 0) {
		alert('Loan Term must be greater than 0');
		obj.loan.value = 'Error';
	}
	else {
	 	obj.loan.value = formatCurrency(a);
	}
}

function loanrepay(obj) {
 	a=Math.abs(obj.LoanAmount.value)
	b=obj.InterestRate.value	
	t=obj.Term.value	
		
	r=eval(b/100);

	month = repayment(a,r/12,t*12);
	fnight = repayment(a,r/26,t*26);

	if (t <= 0) {
		alert('The Term must be greater than 0');
		obj.monthly.value = 'Error';
   		obj.fortnightly.value = 'Error';
		obj.weekly.value = 	'Error';
	}
	else {
		obj.monthly.value = formatCurrency(month);
   		obj.fortnightly.value = formatCurrency(fnight);
		obj.weekly.value = 	formatCurrency(fnight/2);
	}
}
// Calculate the repayment amount of a loan.
// If term is months, rate needs to be /12    
function repayment(loanAmt,intRate,term) {
	return (loanAmt*intRate) / (1-Math.pow((1+intRate),-term));
}

function term(obj) {
 	a=Math.abs(obj.LoanAmount.value)
	d=Math.abs(obj.RegularRepayment.value)
	b=obj.InterestRate.value	
		
	minpay = minRepay(a,b);
	r=eval(b/1200);
	
    m = eval(Math.log(d/(d - a * r)) / Math.log(r + 1))
    m = eval(Math.ceil(m))

    y = eval(Math.floor(m / 12))
    m = eval(m - (y * 12))
	
	if (d  < minpay) {
		alert('Minimum repayment must be greater than ' + formatCurrency(minpay));
		obj.years.value = "Error";
		obj.months.value = "Error";	
	}
	else {
	   	obj.years.value = y;
		obj.months.value = m;
	}
}

function minRepay(amount,rate) {
	r=rate/100; 			// Loan term is calculated as 25 years (300 months)
	return (repayment(amount,r/12,300));
}
    

function savings(obj) {
 	p=Math.abs(obj.InitialDeposit.value)
	b=obj.InterestRate.value		
	f=getListValue(obj.frequency)
	d=Math.abs(obj.RegularDeposit.value)
	m=obj.Term.value         	

	r=eval((b/100)/f);			
	n=eval(m/12*f)				

        if (p != 0) {
            x1 = compdInt(p, r, n)
        }
		else {
            x1 = 0
        }
		
        x2 = (d * (1 + r) * (Math.pow((1 + r),n) - 1)) / r;
		x = eval(x1 + x2);

		if ((f==1 && m < 12) || (f==4 && m < 3)) {
			alert('Deposit Frequency cannot be greater than the Term');
	        obj.total.value="Error";
		}
		else {
	    	obj.total.value=formatCurrency(x);
		}
}

function compdInt(pv,rt,np) {
	return eval(pv * Math.pow((1+rt),np));
}

function termdep(obj) {
 	p=Math.abs(obj.DepositAmount.value)
	r=obj.InterestRate.value
	m=getListValue(obj.month)
	n=m/12

	totalann = compdInt(p,r/100,n);   		
	interest = eval(p * r/100 * n);
	totalmon = eval(p) + interest;

	if (n <= 1) {
		obj.totalann.value = "N/A";
	}
	else {
		obj.totalann.value = formatCurrency(totalann);
	}
	
	obj.totalmon.value = formatCurrency(totalmon)
}

function rounding(num,places) {
	var a = Math.pow(10,places);
	return (Math.round(a*num))/a;
}

/* **********************************************************************
 *  Functions for AAPR Comparison Calculator							*
 ***********************************************************************/

var prodName = new Array()
var prodVariableRate = new Array();
var prodFixedRate = new Array();
var prodFixedPeriod = new Array();
var prodUpfrontFee = new Array();
var prodMortIns = new Array();
var prodOngoingFee = new Array();
var prodFeeFrequency = new Array();
var prodEndFee = new Array();

prodName[1] = "Standard Variable";
prodVariableRate[1] = "6.55";
prodFixedRate[1] = "0";
prodFixedPeriod[1] = "0";
prodUpfrontFee[1] = "1080";
prodMortIns[1] = "0";
prodOngoingFee[1] = "0";
prodFeeFrequency[1] = "0";
prodEndFee[1] = "250";

prodName[2] = "First Step Home Loan";
prodVariableRate[2] = "6.10";
prodFixedRate[2] = "0";
prodFixedPeriod[2] = "0";
prodUpfrontFee[2] = "1080";
prodMortIns[2] = "0";
prodOngoingFee[2] = "0";
prodFeeFrequency[2] = "0";
prodEndFee[2] = "250";

prodName[3] = "Equity Loan";
prodVariableRate[3] = "7.05";
prodFixedRate[3] = "0";
prodFixedPeriod[3] = "0";
prodUpfrontFee[3] = "1330";
prodMortIns[3] = "0";
prodOngoingFee[3] = "0";
prodFeeFrequency[3] = "0";
prodEndFee[3] = "250";

prodName[4] = "Bridging Loan";
prodVariableRate[4] = "7.05";
prodFixedRate[4] = "0";
prodFixedPeriod[4] = "0";
prodUpfrontFee[4] = "1580";
prodMortIns[4] = "0";
prodOngoingFee[4] = "0";
prodFeeFrequency[4] = "0";
prodEndFee[4] = "250";

prodName[5] = "Bridging Loan with Interest Capitalisation";
prodVariableRate[5] = "8.05";
prodFixedRate[5] = "0";
prodFixedPeriod[5] = "0";
prodUpfrontFee[5] = "1580";
prodMortIns[5] = "0";
prodOngoingFee[5] = "0";
prodFeeFrequency[5] = "0";
prodEndFee[5] = "250";

prodName[6] = "Other Loan";
prodVariableRate[6] = "0";
prodFixedRate[6] = "0";
prodFixedPeriod[6] = "0";
prodUpfrontFee[6] = "0";
prodMortIns[6] = "0";
prodOngoingFee[6] = "0";
prodFeeFrequency[6] = "0";
prodEndFee[6] = "0";



function populateCalc(){
	if (!DHTML) return;
	var e3 = new getObj("EstabFee")
	var e4 = new getObj("MortInsurance")
	var e5 = new getObj("TerminationFee")
	var e6 = new getObj("OngoingFee")
	var e7 = new getObj("FeeFrequency")
	var e8 = new getObj("HoneymoonRate")
	var e9 = new getObj("HoneymoonPeriod")
	var e10 = new getObj("VariableRate")
	var e12 = new getObj("LoanType")
	var selectedItem =  e12.obj.value
	
	e3.obj.value = prodUpfrontFee[selectedItem];
	e4.obj.value = prodMortIns[selectedItem];
	e5.obj.value = prodEndFee[selectedItem];
	e6.obj.value = prodOngoingFee[selectedItem];
	e7.obj.value = prodFeeFrequency[selectedItem];
	e8.obj.value = prodFixedRate[selectedItem];
	e9.obj.value = prodFixedPeriod[selectedItem];
	e10.obj.value = prodVariableRate[selectedItem];

 	if (selectedItem != 6) {
		e3.obj.disabled = true;
		e4.obj.disabled = true;
		e5.obj.disabled = true;
		e6.obj.disabled = true;
		e7.obj.disabled = true;	
		e8.obj.disabled = true;	
		e9.obj.disabled = true;	
		e10.obj.disabled = true;	
	}
}


function IRRCalc(CArray, guess) { 
   if (!guess) { 
         guess = 0.0; 
    } 
    inc =0.0001; 
    do 
    { 
		 guess += inc; 
         NPV = 0; 
         for (var j=0; j<CArray.length; j++) 
         { 
              NPV += CArray[j]/Math.pow((1+guess),j); 
         } 
    }while(NPV > 0); 
    return guess * 100; 
} 
/* 
function IRRCalc(CArray) {
	// irr formula
//	document.cashflowcalculator.elements[3].value = "please wait";
	var result;
	var ir = .0001;
	var incr = .10;
	var temp = 0;
	var loop = true;
	while (loop == true) {
		var nt = 0;
		var pv = 0;
		for (m=1; m<=360; m++) {
			for (n=nt+1; n<=nt+CArray[m+1]; n++) {
				pv += CArray[m] / Math.pow((1 + ir), n);
			}
			nt += CArray[m+1];
		}

		// check how close pv is to initial outlay
		if (Math.abs(pv - Math.abs(CArray[0])) <= .0000001) {
			result = rounding((ir * 100),3);
			loop = false;
		}
		if (pv <= Math.abs(CArray[0])) {
			ir -= incr;
			incr *= .10;
		}
		if (pv > Math.abs(CArray[0])) {
			ir += incr;
		}

	}	
	return result;
}
*/

//function repayment(loanAmt,intRate,term) {
//	return (loanAmt*intRate) / (1-Math.pow((1+intRate),-term));
//
// To calc PMT use function repayment defined above

function aaprCalc(){
if (!DHTML) return;
var e1 = new getObj("AmountBorrowed")
var e2 = new getObj("LoanPeriod")
var e3 = new getObj("EstabFee")
var e4 = new getObj("MortInsurance")
var e5 = new getObj("TerminationFee")
var e6 = new getObj("OngoingFee")
var e7 = new getObj("FeeFrequency")
var e8 = new getObj("HoneymoonRate")
var e9 = new getObj("HoneymoonPeriod")
var e10 = new getObj("VariableRate")
var e11 = new getObj("aapr")

var Btmp = new Array(); // Total monthly Payments
var H = new Array(); // Principal Remaining
var N = new Array(); // Interest Component
var T = new Array(); // Principal Component
var Z = new Array(); // Other Monthly Charges
var AD = new Array(); // Ongoing Fee per period

var AmountBorrowed = eval(e1.obj.value)
var LoanPeriod = eval(e2.obj.value)
var EstabFee = eval(e3.obj.value)
var MortInsurance = eval(e4.obj.value)
var TerminationFee = eval(e5.obj.value)
var OngoingFee = eval(e6.obj.value)
var FeeFrequency = eval(e7.obj.value)
var HoneymoonRate = eval(e8.obj.value)
var HoneymoonPeriod = eval(e9.obj.value)
var VariableRate = eval(e10.obj.value)

Btmp[0] = EstabFee + MortInsurance - AmountBorrowed;
H[0] = AmountBorrowed;

var HoneymoonMonthlyPayment = (HoneymoonPeriod > 0) ? (repayment(AmountBorrowed, HoneymoonRate/100/12, LoanPeriod * 12)) : 0;

var a = 0
var b = 0
var c = 0
var d = 0

if (FeeFrequency % 1 == 0) {
	d = OngoingFee;
}
if (FeeFrequency % 2 == 0) {
	c = OngoingFee;
}
if (FeeFrequency % 4 == 0) {
	b = OngoingFee;
}
if (FeeFrequency % 12 == 0) {
	a = OngoingFee;
}

for (var i = 1; i <= 360; i++){
	if (i%12 == 0) {		// Determining fee type
		AD[i] = d;
	} else if (i%12 == 6) {
		AD[i] = c;
	} else if ((i%12 == 3) || (i%12 == 9)){
		AD[i] = b;
	} else {
		AD[i] = a;
	}
}
var HoneymoonCharges = 0;

if (HoneymoonPeriod > 0) {
	for (var j = 1;  j <= HoneymoonPeriod; j++){
		N[j] = (HoneymoonRate /100 / 12) * H[j-1];
		T[j] = HoneymoonMonthlyPayment - N[j];
		Z[j] = AD[j];

		Btmp[j] = N[j] + T[j] + Z[j];
		H[j] = H[j-1] - T[j];
		HoneymoonCharges  = HoneymoonCharges + Z[j]
	}
}
//var PrincEndHoneymoon = H[HoneymoonPeriod];
var PrincEndHoneymoon = AmountBorrowed - (HoneymoonMonthlyPayment * HoneymoonPeriod) - HoneymoonCharges


var SubsequentMonthlyPayment = repayment(PrincEndHoneymoon, VariableRate/100/12, (LoanPeriod * 12) - HoneymoonPeriod)

for (var k = HoneymoonPeriod + 1; k <= 360; k++){
	if (k <= (LoanPeriod * 12)) {
			N[k] = (VariableRate /100 / 12) * H[k-1];
			T[k] = SubsequentMonthlyPayment - N[k];
			Z[k] = (k == (LoanPeriod * 12)) ? (AD[k] + TerminationFee) : AD[k];
	} else {
		N[k] = 0;
		T[k] = 0;
		Z[k] = 0;
	}
	Btmp[k] = N[k] + T[k] + Z[k];
	H[k] = H[k-1] - T[k];
}

//alert("HoneymoonMonthlyPayment: " + HoneymoonMonthlyPayment)
//alert("PrincEndHoneymoon: " + PrincEndHoneymoon)
//alert("SubsequentMonthlyPayment: " + SubsequentMonthlyPayment)
//alert("Z: " + Z)
//alert("T: " + T)
//alert("N: " + N)
//alert("H:" + H)
//alert("Btmp is:" + Btmp)
e11.obj.value = rounding((IRRCalc(Btmp))*12,2)
}
