/* calculate.js file contains all the necessary functions required to validate 	*
 * form level fields and the generating the amortization schedule    			*/

function checkData(amount,months)
{
	//Check for non-empty amount and months field
	if (amount=="")
	{
		alert ("Please enter the Loan Amount");
		document.getElementById('amount').select();
		return false;
	}
	else if (isNaN(amount) || (amount<=0)) 
	{
		alert ("Please enter a valid Loan Amount");
		document.getElementById('amount').select();
		return false;
	}
	
	if (months=="")
	{
		alert ("Please enter number of months");
		document.getElementById('term').select();
		return false;
	}
	else if (isNaN(months) || (months<=0) || months!=(Math.round(months)))
	{
		alert ("Please enter valid number of months");
		document.getElementById('term').select();
		return false;
	}
		
	return true;
}

/* This function changes a number into Currency Format */
function formatCurrency(num,delim) // num = number, delim = delimeter
{
	// round to 2 decimals if cents present
	num = (Math.round(num * 100) / 100).toFixed(2).toString().split('.');
	var myNum = num[0].toString();
	var fmtArr = new Array();
        var len = myNum.length;
        var i = 1;
        var decimal = (delim == '.') ? ',' : '.';
  
	for(i; i < len + 1; i++) fmtArr[i] = myNum.charAt(i-1);
 
	fmtArr = fmtArr.reverse();
	for(i = 1; i < len; i++)
	{
		if(i % 3 == 0) 
		{
			fmtArr[i] += delim;
		}
	}
	var val = fmtArr.reverse().join('') +	( num[1] == null ? decimal + '00' : (decimal + num[1]));
	return val;
}
 

/* 	This function populates monthly payment and calls function to calculate 
	amortization and display on the screen */
function calculateAmortization() 
{
	 // Read value from amount field from web page and replace dollars and commas, if they exist, with the blanks
	var amount= document.getElementById('amount').value.toString().replace(/^\$|^\,/g,'').replace(/(\d)(\,)/g,"$1");
	var months=document.getElementById('term').value;
	var interestRate=document.getElementById('apr').value;
	
	// Get a handle to the "Monthly Payment" table
	var result_table = document.getElementById('table1');
	
	if (!checkData(amount,months))
	{
		return;
	}

	document.getElementById('amount').value = (Math.round(amount*100)/100);
	document.getElementById('term').value = months;
	var oPaymentBox=document.getElementById("paymentbox");
	oPaymentBox.style.visibility = "visible";
	var payment = getPayment(amount,months,interestRate);
	oPaymentBox.value = "$"+ formatCurrency(Math.round(payment*100)/100,',');
	draw_table(result_table,amount,months,interestRate);
}

/* This function calculates the monthly payment from annual percentage
  rate, term of loan in months and loan amount. **/

function getPayment(amount,months,interestRate) 
{
		var acc=0;
		var base = 1 + interestRate/1200;
		for (i=1;i<=months;i++) 
			{ acc += Math.pow(base,-i); }
		return amount/acc;
}

// This functions clears the table
function clearTable(table1)
{
		while(table1.rows.length > 1)
		{
		  	  var oRow1=table1.deleteRow(1);         	
		}

}


// This function dynamicaly generates the amortation table
function draw_table(table1,amount,months,interestRate)
{
		var balance=amount;
		var interest=0.0;
		var principal=0.0;
		var totalinterest=0.0;
		var payment = getPayment(amount,months,interestRate);
		
		// Clearing the earlier table
		clearTable(table1);
		
		for(i=1;i<=months;i++)
		{
			interest = balance*interestRate/1200;
			totalinterest += interest;
			principal = payment-interest;
			balance -= principal;

	        var oRow1=table1.insertRow(table1.rows.length);
	       	var aRows=table1.rows;   
	        var aCells=oRow1.cells;
	        var oCell1_1=aRows[oRow1.rowIndex].insertCell(aCells.length);
	        var oCell1_2=aRows[oRow1.rowIndex].insertCell(aCells.length);
	        var oCell1_3=aRows[oRow1.rowIndex].insertCell(aCells.length);
	        var oCell1_4=aRows[oRow1.rowIndex].insertCell(aCells.length);
	        var oCell1_5=aRows[oRow1.rowIndex].insertCell(aCells.length);
	        var oCell1_6=aRows[oRow1.rowIndex].insertCell(aCells.length);
	        var oCell1_7=aRows[oRow1.rowIndex].insertCell(aCells.length);
	        var oCell1_8=aRows[oRow1.rowIndex].insertCell(aCells.length);
	        var oCell1_9=aRows[oRow1.rowIndex].insertCell(aCells.length);
	        var oCell1_10=aRows[oRow1.rowIndex].insertCell(aCells.length);
	        var oCell1_11=aRows[oRow1.rowIndex].insertCell(aCells.length);

			oCell1_1.innerHTML=i.toString();
			oCell1_2.innerHTML="<img src='/images/https-misc/calculator/col_divider.gif' width='3' height ='24'>";
			oCell1_3.innerHTML="$"+formatCurrency(Math.round(balance*100)/100, ',');
			oCell1_4.innerHTML="<img src='/images/https-misc/calculator/col_divider.gif' width='3' height ='24'>";
			oCell1_5.innerHTML="$"+formatCurrency(Math.round(principal*100)/100, ',');
			oCell1_6.innerHTML="<img src='/images/https-misc/calculator/col_divider.gif' width='3' height ='24'>";
			oCell1_7.innerHTML="$"+formatCurrency(Math.round(interest*100)/100, ',');
			oCell1_8.innerHTML="<img src='/images/https-misc/calculator/col_divider.gif' width='3' height ='24'>";
			oCell1_9.innerHTML="$"+formatCurrency(Math.round(i*payment*100)/100, ',');
			oCell1_10.innerHTML="<img src='/images/https-misc/calculator/col_divider.gif' width='3' height ='24'>";
			oCell1_11.innerHTML="$"+formatCurrency(Math.round(totalinterest*100)/100, ',');
		}
	}
	