// Creates a namespace for "inabeo"
var mortBkDown; 

function init() {
	YAHOO.namespace ("inabeo");
	var tabView = new YAHOO.widget.TabView('tabset');
	getBreakdown();
		
	YAHOO.util.Event.addListener("principal", "change", getBreakdown); 
	YAHOO.util.Event.addListener("rate", "change", getBreakdown); 
	YAHOO.util.Event.addListener("term", "change", getBreakdown); 
	
}

function getBreakdown() {	
	principal = document.getElementById("principal").value;
	rate = document.getElementById("rate").value;
	term = document.getElementById("term").value;
	
	document.getElementById("principal").value = addCommas(principal);
	
	principal = stripNonNumeric(principal);
	rate = stripNonNumeric(rate);
	term = stripNonNumeric(term);
	
	if (term < 1 || term > 45) {
		alert("Your term entered is: " + term + "\nTerm must be between 1 and 45 Years");
		document.getElementById("term").value = "";
		document.getElementById("term").focus();
		return;
	}

	repayment = monthlyRepayment(principal, rate, term);
	document.getElementById("repayment").value = addCommas(Math.round(repayment));
	
	annualRepayment = repayment * 12;
	document.getElementById("annualRepayment").value = addCommas(Math.round(annualRepayment));
	
	totalPaid = repayment * term * 12;
	document.getElementById("totalPaid").value = addCommas(Math.round(totalPaid));
	
	totalInterest = interestRepaid(principal, rate, term);
	document.getElementById("totalInterest").value = addCommas(Math.round(totalInterest));
	
	mortBkDown = mortgageBreakdown(principal, rate, term);
	drawMortgageTable();
	drawChart1();
	drawChart2();
	
}


/**
rate = nominal interest rate
numPeriods = years
principal = amount borrowed
*/
function monthlyRepayment(principal, rate, numPeriods) {	
	r = rate / 100 / 12;
	n = numPeriods * 12;
	p0 = principal;

	/* Monthly Repayment */
	payment = p0 * (r / (1- Math.pow(1/(1+r), n)));

	return payment;
}

/**
i = periodExamined
pi = Current principal outstanding at period i
*/
function currentPrincipal(principal, rate, numPeriods, period) {
	r = rate / 100 / 12;
	n = numPeriods * 12;
	p0 = principal;
	i = (period == null) ? n : period;
	
	payment = monthlyRepayment(principal, rate, numPeriods);
	
	pi = Math.pow(1+r, i) * p0 - ((Math.pow(1+r, i)-1)/r) * payment; 
	
	return pi;

}

/**
i = periodExamined
pi = Current principal outstanding at period i
*/
function interestRepaid(principal, rate, numPeriods, period) {
	r = rate / 100 / 12;
	n = numPeriods * 12;
	p0 = principal;
	i = (period == null) ? n : period;

	payment = monthlyRepayment(principal, rate, numPeriods);
	
	ii = payment * i + ((r * p0) - payment) * ((Math.pow(1+r, i)-1) / r);
	
	return ii;

}

/**
rate = nominal interest rate
numPeriods = years
principal = amount borrowed
type = breakdown yearly or monthly
*/
function mortgageBreakdown(principal, rate, numPeriods, type) {
	var mortBkDown = new Array();
	
	type = (type == null) ? "Y" : type;	
	r = rate / 100 / 12;
	n = numPeriods * 12;
	p0 = principal;
	
	payment = monthlyRepayment(principal, rate, numPeriods);
	
	/**
	i = periodExamined
	pi = Current principal outstanding at period i
	ii = total interest paid at period i

	Current Principal Value
	$pi = pow(1+$r, $i) * $p0 - ((pow(1+$r, $i)-1)/$r) * $payment; 
	
	Interest Repaid
	$ii = $payment * $i + (($r * $p0) - $payment) * ((pow(1+$r, $i)-1) / $r);
	
	*/
	for (j=0; j < n ; j++) {
		if (type=="Y") {
			i = ( j ) * 12;

			if ( i > n ) {
				break;
			}
		}
		else {
			i = j;
		}
		
		pi = Math.pow(1+r, i) * p0 - ((Math.pow(1+r, i)-1)/r) * payment; 
		ii = payment * i + ((r * p0) - payment) * ((Math.pow(1+r, i)-1) / r);

		previousInterest = ( j > 1 ) ? mortBkDown[j-1].totalInterest : 0 ;
		
		intersetPaidInCurrentPeriod = ii - previousInterest;

		previousPrincipal = ( j > 1 ) ? mortBkDown[j-1].principal : principal ;
		principalRepaidInCurrentPeriod = Math.abs(pi - previousPrincipal);
		
		periodBkDown = new Object();
		periodBkDown.period = j;
		periodBkDown.principal = (Math.round(pi));
		periodBkDown.totalRepayments = (Math.round(payment * i));
		periodBkDown.totalInterest = (Math.round(ii));
		periodBkDown.totalPrincipal = (Math.round((payment * i) - ii));
		periodBkDown.principalCurrent = (Math.round(principalRepaidInCurrentPeriod));
		periodBkDown.interestCurrent = (Math.round(intersetPaidInCurrentPeriod));
		
		mortBkDown.push( periodBkDown );
	}

	return mortBkDown;
}

function drawMortgageTable() {
	//Datasource
        var myDataSource = new YAHOO.util.DataSource(mortBkDown);
        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        myDataSource.responseSchema = {
            fields: ["period", "principal","totalRepayments","totalInterest","totalPrincipal","principalCurrent", "interestCurrent"]
        };
	
	//Build Table Data
	var myColumnDefs = [
            {key:"period", label:"Year", sortable:true, width: 28, className: "tdAlign"},
           {key:"principalCurrent", label:"Principal Paid", formatter:YAHOO.widget.DataTable.formatNumber, sortable:true, resizeable:true, width: 85, className: "tdAlign" },
            {key:"interestCurrent", label:"Interest Paid",  formatter:YAHOO.widget.DataTable.formatNumber, sortable:true, resizeable:true, width: 85, className: "tdAlign"},
             {key:"principal", label:"Principal<br/>Remaining", formatter:YAHOO.widget.DataTable.formatNumber, sortable:true, resizeable:true, width: 90, className: "tdAlign"},
             {key:"totalPrincipal", label:"Total Principal", formatter:YAHOO.widget.DataTable.formatNumber, sortable:true, resizeable:true, width:90, className: "tdAlign" },
            {key:"totalInterest", label:"Total Interest", formatter:YAHOO.widget.DataTable.formatNumber, sortable:true, resizeable:true, width: 90, className: "tdAlign" },
           {key:"totalRepayments", label:"Total<br/>Repayments", formatter:YAHOO.widget.DataTable.formatNumber, sortable:true, resizeable:true, width:90, className: "tdAlign"}
        ];

        var myDataTable = new YAHOO.widget.ScrollingDataTable("mortTable",
                myColumnDefs, myDataSource, {height:"31.15em", width: "722px"});
		
}
function drawChart1() {
	//Datasource
        var myDataSource = new YAHOO.util.DataSource(mortBkDown);
        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        myDataSource.responseSchema = {
            fields: ["period", "principal","totalRepayments","totalInterest","totalPrincipal","principalCurrent", "interestCurrent"]
        };

	//Build Chart 1
	YAHOO.widget.Chart.SWFURL = "http://yui.yahooapis.com/2.7.0/build/charts/assets/charts.swf";
	var seriesDef =
	[
		{ 	displayName: "Total Principal", 
			yField: "principal"
		},
		{ 	displayName: "Total Interest", 
			yField: "totalInterest" 
		},
		{ 	displayName: "Total Repayments", 
			yField: "totalRepayments" 
		}
	];
	
	YAHOO.inabeo.formatCurrencyAxisLabel = function( value )
	{
		return YAHOO.util.Number.format( value,
		{
			prefix: "$",
			thousandsSeparator: ",",
			decimalPlaces: 2
		});
	}

	YAHOO.inabeo.formatNumberAxisLabel = function( value )
	{
		return YAHOO.util.Number.format( value,
		{
			thousandsSeparator: ","
		});
	}

	YAHOO.inabeo.getDataTipText = function( item, index, series )
	{
		var toolTipText = series.displayName + " for Year " + item.period;
		toolTipText += "\n" + YAHOO.inabeo.formatNumberAxisLabel( item[series.yField] );
		return toolTipText;
	}

	var currencyAxis = new YAHOO.widget.NumericAxis();
	currencyAxis.minimum = 0;
	currencyAxis.labelFunction = YAHOO.inabeo.formatNumberAxisLabel;

	var mychart = new YAHOO.widget.LineChart( "chart1", myDataSource,
	{
		series: seriesDef,
		xField: "period",
		yAxis: currencyAxis,
		dataTipFunction: YAHOO.inabeo.getDataTipText,
		style:
		{
			padding: 20,
			legend:
			{
				display: "bottom",
				padding: 10,
				spacing: 5,
				font:
				{
					family: "Arial",
					size: 13
				}
			}
		},
		//only needed for flash player express install
		expressInstall: "assets/expressinstall.swf"
	});

}

function drawChart2() {
	YAHOO.widget.Chart.SWFURL = "http://yui.yahooapis.com/2.7.0/build/charts/assets/charts.swf";
	//Datasource
	//Copy the mortBKDown object
	chart2DS = new Array();
	for (key in mortBkDown) {
		chart2DS[key] = mortBkDown[key];
        }
	
	//Kick off the 0 record (doesn't make sense in graph)
	chart2DS.shift();
		
        var myDataSource = new YAHOO.util.DataSource(chart2DS);
        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        myDataSource.responseSchema = {
            fields: ["period", "principal","totalRepayments","totalInterest","totalPrincipal","principalCurrent", "interestCurrent"]
        };


	//Build Chart 2
	var seriesDef2 =
	[
		{ 	displayName: "Principal", 
			yField: "principalCurrent"
		},
		{ 	displayName: "Interest", 
			yField: "interestCurrent" 
		}
	];

	YAHOO.inabeo.formatCurrencyAxisLabel = function( value )
	{
		return YAHOO.util.Number.format( value,
		{
			prefix: "$",
			thousandsSeparator: ",",
			decimalPlaces: 2
		});
	}

	YAHOO.inabeo.formatNumberAxisLabel = function( value )
	{
		return YAHOO.util.Number.format( value,
		{
			thousandsSeparator: ","
		});
	}

	YAHOO.inabeo.getDataTipText = function( item, index, series )
	{
		var toolTipText = series.displayName + " for Year " + item.period;
		toolTipText += "\n" + YAHOO.inabeo.formatNumberAxisLabel( item[series.yField] );
		return toolTipText;
	}


	var currencyAxis = new YAHOO.widget.NumericAxis();
	currencyAxis.minimum = 0;
	currencyAxis.labelFunction = YAHOO.inabeo.formatNumberAxisLabel;

	var mychart = new YAHOO.widget.LineChart( "chart2", myDataSource,
	{
		series: seriesDef2,
		xField: "period",
		yAxis: currencyAxis,
		dataTipFunction: YAHOO.inabeo.getDataTipText,
		style:
		{
			padding: 20,
			legend:
			{
				display: "bottom",
				padding: 10,
				spacing: 5,
				font:
				{
					family: "Arial",
					size: 13
				}
			}
		},
		//only needed for flash player express install
		expressInstall: "assets/expressinstall.swf"
	});	
}

function addCommas(nStr) {
  nStr += "";
  x = nStr.split(".");
  x1 = x[0];
  x2 = x.length > 1 ? "." + x[1] : "";
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, "$1" + "," + "$2");
  }
  return x1 + x2;
}


// This function removes non-numeric characters
function stripNonNumeric( str ) {
  str += "";
  var rgx = /^\d|\.|-$/;
  var out = "";
  for( var i = 0; i < str.length; i++ )
  {
    if( rgx.test( str.charAt(i) ) ){
      if( !( ( str.charAt(i) == "." && out.indexOf( "." ) != -1 ) ||
             ( str.charAt(i) == "-" && out.length != 0 ) ) ){
        out += str.charAt(i);
      }
    }
  }
  return out;
}


// JavaScript Document
var numericDecimal = '0123456789.';
var numericDecimalComma = '0123456789.,';
var integer = '0123456789';

function okpNumericDecimalComma(e){
	var unicode=e.charCode? e.charCode : e.keyCode;
	if (unicode!=8 && unicode!=9 && unicode!=44 && unicode!=46){ //if the key isn't the backspace key, comma or dot (which we should allow)
		if (unicode<48||unicode>57) //if not a number
			return false //disable key press
	}
}

function okpNumericDecimal(e){
	var unicode=e.charCode? e.charCode : e.keyCode;
	if (unicode!=8  && unicode!=9 && unicode!=46){ //if the key isn't the backspace key  or dot (which we should allow)
		if (unicode<48||unicode>57) //if not a number
			return false //disable key press
	}
}

function okpInteger(e){
	var unicode=e.charCode? e.charCode: e.keyCode;
	if (unicode!=8 && unicode!=9){ //if the key isn't the backspace key (which we should allow)
		if (unicode<48||unicode>57) //if not a number
			return false //disable key press
	}
}
