var savedValue;

function SaveValue( inCtrl )
{
    var ctrl;
    if ( isIE() )
		ctrl = document.activeElement;
    else
        ctrl = inCtrl.currentTarget;

    if ( ctrl.id == null )
		ctrl = document.activeElement;
	savedValue = ctrl.value;
}

function AppendRow(ctrl)
{
    // row
    var rowCount = new Number(document.getElementById("rowCnt").value);                                     
    // row count
    var newRow = document.getElementById("TableBalances").insertRow(rowCount);                                      
    
    // loan cell
    var newCellLoan = newRow.insertCell(0);
    newCellLoan.innerHTML = "Loan " + rowCount + ":";
    
    // balance cell
    var newCellBalance = newRow.insertCell(1);
    ////newCellBalance.setAttribute("width", 122);
    ////newCellBalance.setAttribute("className", "tbpad2");
    
    // rate cell
    var newCellRate = newRow.insertCell(2);
    ////newCellRate.setAttribute("width", 121);
    
    var spanDollar = document.createElement( "span" );
    spanDollar.innerHTML = "$&nbsp;";

    var spanPct = document.createElement( "span" );
    spanPct.innerHTML= "&nbsp;%";
    
    // balance textbox
    var newBalance = document.createElement("input"); 
    newBalance.setAttribute("id", "Balance" + rowCount);
    newBalance.setAttribute("type", "text");
    newBalance.setAttribute("size", 10);
    if ( isIE()  )
    {
        newBalance.setAttribute("className", "StdTxtbx" );
        newBalance.attachEvent("onchange",Recalculate);
        newBalance.attachEvent("onfocus",SaveValue);
    }
    else    
    {
        newBalance.setAttribute("class", "StdTxtbx" );
        newBalance.addEventListener("change", Recalculate,false);
        newBalance.addEventListener("focus",SaveValue, false);
    }

    //newBalance.setAttribute("value", "0.00");
    
    newCellBalance.appendChild(spanDollar);
    newCellBalance.appendChild(newBalance);

    // rate textbox
    var newRate = document.createElement("input"); 
    newRate.setAttribute("id", "Rate" + rowCount);
    newRate.setAttribute("type", "text");
    //newRate.setAttribute("value", "0.00");
    newRate.setAttribute("size", 5);
    if ( isIE() )
    {
        newRate.setAttribute("className", "StdTxtbx" );
        newRate.attachEvent("onchange",Recalculate);
        newRate.attachEvent("onfocus",SaveValue);
    }
    else // check
    {
        newRate.setAttribute("class", "StdTxtbx" );
        newRate.addEventListener("change",Recalculate,false);
        newRate.addEventListener("focus",SaveValue, false);
    }
    newCellRate.appendChild(newRate);
    newCellRate.appendChild(spanPct);
    
    rowCount += 1;
    document.getElementById("rowCnt").value = rowCount;
}
        
function UnformatControl( ctrl )
{
    if ( (ctrl.value != null ) && (ctrl.value != "") )
    {
        ctrl.value = UnformatValue( ctrl.value );
    }
}

function UnformatValue( value )
{
    return value.replace(",","");
}

function UnformatControlValue( ctrl )
{
    return UnformatValue( ctrl.value );
}

function ToNumericValue( value )
{
    if ( value == null || value == "" )
        value = 0;
    else
    {
        if ( isNaN( value ) )
            value = 0;
    }
    var result = new Number( value );
    return result;
}
        
function calcTotalLoansAmount(rowCount)
{
    // total Amount
    var totalAmount = new Number(0);
    for( var i = 1 ; i < rowCount; i++ )
    {
        var bal = eval("document.getElementById('Balance" + i + "')");
        if ( bal.value != "")
        {
            totalAmount += ToNumericValue(UnformatValue( bal.value ));
            FormatCurrencyControl( bal, null );
        }
    }
    return totalAmount;                             
}
        
function calcWeightedRate(rowCount, totalLoansAmount)
{
	var weightedRate = new Number(0);
	if ( totalLoansAmount == 0)
		return 0;

	for( var ii = 1 ; ii < rowCount; ii++ )
	{
		var bal = eval("document.getElementById('Balance" + ii + "')");
		var rate = eval("document.getElementById('Rate" + ii + "')");

		if ( bal.value != "" && rate.value != "" )
		{
			var nBal = ToNumericValue(UnformatValue( bal.value ));
			var nRate = ToNumericValue(UnformatValue( rate.value ));
			weightedRate += nBal / totalLoansAmount * nRate;
	        
			FormatCurrencyControl( bal, null );
			FormatDecimalsControl( rate, null, 3 );
		}
	}
	return weightedRate;
}

function suppressPartialTerm(adjustedTerm, maxTerm)
{
	return (adjustedTerm > maxTerm) ? maxTerm : adjustedTerm;
}       

var dialogData;
var debug = false;


function Recalculate(ctrl)
{
	// data to pass to dialog
	dialogData = new Object();
	// number of rows
	var rowCount = document.getElementById("rowCnt").value;
	
	// total loans amount
	var totalLoansAmount = calcTotalLoansAmount(rowCount);
	document.getElementById("CellB12").innerHTML = FormatCurrency(totalLoansAmount.toString());
	// weighted rate
	var weightedRate = calcWeightedRate(rowCount,totalLoansAmount);
	// other balances
	var otherBalancesCtrl = document.getElementById("BalancesOther")
	var otherBalances = ToNumericValue(UnformatValue( otherBalancesCtrl.value ));
	if ( otherBalances > 0)
	{
		FormatCurrencyControl( otherBalancesCtrl, null );
	}
	// discounts
	var discounts = 0;
	var discAutoPayment = document.getElementById("AutoPaymentDisc").checked;
	if (discAutoPayment)
		discounts++;
	var discOnTime = document.getElementById("OnTimeDisc").checked;
	if (discOnTime)
		discounts++;
	var rateDescription = "no discounts";
	if (discounts == 1)
		rateDescription = "one discount";
	if (discounts == 2)
		rateDescription = "both discounts";
	rateDescription = "<strong>Rate</strong> (with " + rateDescription + ")<strong>:</strong>";
	var fld = document.getElementById("RateDescription");
	fld.innerHTML = rateDescription;

	var calc = new calculator(totalLoansAmount, otherBalances, weightedRate,discAutoPayment, discOnTime);								
	//debug = true;
	
	document.getElementById("CellC12").innerHTML = formatDecimals(calc.weightedRate.toString(), 3);              
	document.getElementById("CellD12").innerHTML = formatDecimals(calc.roundedAverageRate().toString(), 3);    
	document.getElementById("CellB14").innerHTML = FormatCurrency(calc.totalBalance().toString());
	document.getElementById("CellD20").innerHTML = formatDecimals(calc.rateWithBenefits().toString(), 3);       

	// terms
	document.getElementById("CellC25").innerHTML = calc.nonSPConsTerm * 12;
	
	document.getElementById("CellC26").innerHTML = suppressPartialTerm(calc.loanTermAdjustedGrad(), calc.gradConsTerm() * 12);
	///var blah = calc.thirdPeriodPmtGrad() + calc.loanValueThirdPeriodGrad();
	///document.getElementById("CellC26").innerHTML = 
	///				"<b>" + calc.loanTermAdjustedGrad() + "</b><br/>"
	///				+ "FTLV1 = " + calc.loanValueFirstPeriodGrad()  + "<br/>"
	///				+ "FTLV2 = " + calc.loanValueSecondPeriodGrad()  + "<br/>"
	///				+ "FTLV3 = " + calc.loanValueThirdPeriodGrad()  + "<br/>"
	///				+ "FTLVF = " + blah ;
					
	document.getElementById("CellC29").innerHTML = suppressPartialTerm(calc.loanTermAdjustedInc(),calc.incConsTerm() * 12);
	//				"<b>" + calc.loanTermAdjustedInc() + "</b><br/>"
	//				+ "FTLV1 = " + calc.loanValueFirstPeriodInc()  + "<br/>"
	//				+ "FTLV2 = " + calc.loanValueSecondPeriodInc() + "<br/>"
	//				+ "PMT_P2 = " + calc.secondPeriodPmtInc();
					
	//document.getElementById("CellC30").innerHTML = calc.stdConsTerm() * 12;
	document.getElementById("CellC30").innerHTML = suppressPartialTerm(calc.loanTermAdjustedStd(),calc.stdConsTerm() * 12);
	///document.getElementById("CellC30").innerHTML = 
	///				"<b>" + calc.loanTermAdjustedStd() + "</b><br/>"
	///				+ "FTLV = " + calc.loanValueFirstPeriodStd() ;
	
	document.getElementById("CellC27").innerHTML = suppressPartialTerm(calc.loanTermAdjustedExt(),calc.extConsTerm() * 12);
	//document.getElementById("CellC27").innerHTML = 
	//				"<b>" + calc.loanTermAdjustedExt() + "</b><br/>"
	//				+ "FTLV = " + calc.loanValueFirstPeriodExt() ;
	
	
	// payments
	// current
	//document.getElementById("CellD25").innerHTML = "Rates " + round(calc.rateWithBenefits(),3)+"% - " + round(calc.roundedAverageRate(),3) +"% <br>Depending on Benefits";
	document.getElementById("CellD25").innerHTML = "Payments 1-120 (" + round(calc.weightedRate.toString(),3)+"%): " + "$" + FormatCurrency(calc.nonSPPmt().toString());
	
	// graduated
	document.getElementById("CellD26").innerHTML = "<b>Payments 1-24"  + " (" + formatDecimals(calc.firstPeriodRate(),3) + "%): $" + FormatCurrency( calc.firstPeriodPmtGrad().toString() ) + "</b><br>Payments 25-60" +  " (" + formatDecimals(calc.secondPeriodRate(),3)+ "%): $" + FormatCurrency( calc.secondPeriodPmtGrad().toString() ) + "<br>Payments 61+" + " (" + formatDecimals(calc.finalPeriodRate(),3) + "%): $" + FormatCurrency( calc.thirdPeriodPmtGrad().toString() );
	// extended
	var extPmt;
	//if (calc.includeBenefits())
	if (calc.includeOnTime)
	{
		extPmt = "<b>Payments 1-24"  + " (" + formatDecimals(calc.firstPeriodRate(),3) + "%): $" + FormatCurrency( calc.firstPeriodPmtExt().toString() ) 
			+ "</b><br>Payments 25+" + " (" + formatDecimals(calc.finalPeriodRate(),3)+ "%): $" + FormatCurrency( calc.finalPeriodPmtExt().toString() );
	}
	else
	{
		extPmt = "<b>Payments 1+  "  + " (" + formatDecimals(calc.firstPeriodRate(),3) + "%): $" + FormatCurrency( calc.firstPeriodPmtExt().toString() ) + "</b>";
	}
	document.getElementById("CellD27").innerHTML = extPmt;
	// income sensitive
	document.getElementById("CellD29").innerHTML = "As low as <b>$" + FormatCurrency( calc.firstPeriodPmtInc().toString() ) + "</b> depending on annually-verified income";
	// standard
	var stdPmt;
	//if (calc.includeBenefits())
	if (calc.includeOnTime)
	{
		stdPmt = "<b>Payments 1-" + (calc.firstPeriodStd())  + " (" +  formatDecimals(calc.firstPeriodRate(),3) + "%): $" + FormatCurrency( calc.firstPeriodPmtStd().toString() ) 
			+ "</b><br>Payments " + (calc.firstPeriodStd()+1) + "+ (" + formatDecimals(calc.finalPeriodRate(),3) +"%): $" + FormatCurrency( calc.finalPeriodPmtStd().toString() );
	}
	else
	{
		stdPmt = "<b>Payments 1+" + " (" +  formatDecimals(calc.firstPeriodRate(),3) + "%): $" + FormatCurrency( calc.firstPeriodPmtStd().toString());
	}
	
	document.getElementById("CellD30").innerHTML = stdPmt;
	// payment reduction
	// current
	// TODO REMOVE document.getElementById("CellH25").innerHTML = "$" + FormatCurrency(calc.nonSPPmt().toString());
	// graduated
	var diffPmt = calc.nonSPPmt() - calc.firstPeriodPmtGrad();
	document.getElementById("CellH26").innerHTML = "<b>$" + FormatCurrency(diffPmt.toString()) + "</b>";
	// extended
	var diffPmt = calc.nonSPPmt() - calc.firstPeriodPmtExt();
	document.getElementById("CellH27").innerHTML = "<b>$" + FormatCurrency(diffPmt.toString()) + "</b>";
	// income sensitive
	var diffPmt = calc.nonSPPmt() - calc.firstPeriodPmtInc();
	document.getElementById("CellH29").innerHTML = "<b>$" + FormatCurrency(diffPmt.toString()) + "</b>";
	// standard
	var diffPmt = calc.nonSPPmt() - calc.firstPeriodPmtStd();
	document.getElementById("CellH30").innerHTML = "<b>$" + FormatCurrency(diffPmt.toString()) + "</b>";

	var finalPeriodStd = suppressPartialTerm(calc.loanTermAdjustedStd(),calc.stdConsTerm() * 12);	//calc.finalPeriodStd();
	var finalPeriodExt = suppressPartialTerm(calc.loanTermAdjustedExt(),calc.extConsTerm() * 12);	//calc.finalPeriodExt();
	//alert("finalPeriodStd=[" + finalPeriodStd + "], finalPeriodExt=[" + finalPeriodExt +"]");
	//if (calc.loansBalance >= 30000 && calc.loansBalance < 40000)
	if (finalPeriodExt > finalPeriodStd)	// show/hide extended row
	{
		document.getElementById("ExtendedRow").style.display = '';
		dialogData.showExtended = true;
	}
	else
	{
		document.getElementById("ExtendedRow").style.display = 'none';
		dialogData.showExtended = false;
	}
	
	// show hide sample terms
    if (calc.totalBalance() <= 0 || calc.weightedRate <= 0)
	    document.getElementById('TableRepaymentTerms').style.display = 'none';  
    else
        document.getElementById('TableRepaymentTerms').style.display = '';      

	var calcNoDisc = new calculator(totalLoansAmount, otherBalances, weightedRate, false, false);
	// set data for details dialog
	dialogData.stdSPPmt = calc.totalPmtStd();
	dialogData.stdSPInt = calc.interestStd();
	dialogData.stdOtherPmt = calcNoDisc.totalPmtStd();
	dialogData.stdOtherInt = calcNoDisc.interestStd();
	
	dialogData.gradSPPmt = calc.totalPmtGrad();
	dialogData.gradSPInt = calc.interestGrad();
	dialogData.gradOtherPmt = calcNoDisc.totalPmtGrad();
	dialogData.gradOtherInt = calcNoDisc.interestGrad();

	dialogData.incSPPmt = calc.totalPmtInc();
	dialogData.incSPInt = calc.interestInc();
	dialogData.incOtherPmt = calcNoDisc.totalPmtInc();
	dialogData.incOtherInt = calcNoDisc.interestInc();
	
	dialogData.extSPPmt = calc.totalPmtExt();
	dialogData.extSPInt = calc.interestExt();
	dialogData.extOtherPmt = calcNoDisc.totalPmtExt();
	dialogData.extOtherInt = calcNoDisc.interestExt();
}


///////////////////////////////////////////	                    
function showDetails()
{
    //window.showModalDialog('paymentcalculatordetails.aspx',dialogData,'dialogWidth:668px;dialogHeight:170px;status:no;help:no;scroll:no');
    var params = "";
    params += dialogData.gradSPPmt;
	params += ';' + dialogData.gradSPInt;
	params += ';' + dialogData.gradOtherPmt;
	params += ';' + dialogData.gradOtherInt;
	
	params += ';' + dialogData.stdSPPmt;
	params += ';' + dialogData.stdSPInt;
	params += ';' + dialogData.stdOtherPmt;
	params += ';' + dialogData.stdOtherInt;
	
	params += ';' + dialogData.incSPPmt;
	params += ';' + dialogData.incSPInt;
	params += ';' + dialogData.incOtherPmt;
	params += ';' + dialogData.incOtherInt;
	
	params += ';' + dialogData.extSPPmt;
	params += ';' + dialogData.extSPInt;
	params += ';' + dialogData.extOtherPmt;
	params += ';' + dialogData.extOtherInt;
	params += ';' + dialogData.showExtended;

    window.open('calculatordetails.html?' + params,'loanpop','width=660,height=160');
}
        
function calculator(loansBalance, otherBalance, weightedRate, includeACH, includeOnTime)
{
	this.loansBalance = loansBalance;
	this.otherBalance = otherBalance;
	this.totalBalance = calcTotalBalance;
	this.totalForTermCalc = calcTotalForTermCalc;
	this.loanAmountUnAdjusted = calcLoanAmountUnAdjusted;
	this.loanAmount = calcLoanAmount;
	this.weightedRate = weightedRate;
	this.roundedAverageRate = calcRoundedAverageRate;
	this.achDiscount = 0.5;
	this.onTimeDiscount = 1;
	this.includeACH = includeACH;
	this.includeOnTime = includeOnTime;
	this.includeBenefits = calcIncludeBenefits;
	this.rateWithACH = calcRateWithACH;
	this.rateWithOnTime	= calcRateWithOnTime;
	this.rateWithBenefits = calcRateWithBenefits;
	
	this.nonSPConsTerm = 10;
	this.gradConsTerm = calcGradConsTerm;
	this.extConsTerm = calcExtConsTerm;
	this.stdConsTerm = calcStdConsTerm;
	this.incConsTerm = calcIncConsTerm;
	
	this.firstPeriodRate = calcFirstPeriodRate;
	this.secondPeriodRate = calcSecondPeriodRate;
	this.finalPeriodRate = calcFinalPeriodRate;
	
	this.firstPeriodGrad = calcFirstPeriodGrad;
	this.firstPeriodExt = calcFirstPeriodExt;
	this.firstPeriodInc = calcFirstPeriodInc;
	this.firstPeriodStd = calcFirstPeriodStd;
	
	this.secondPeriodGrad = calcSecondPeriodGrad;
	this.secondPeriodExt = calcSecondPeriodExt;
	this.secondPeriodInc = calcSecondPeriodInc;
	this.secondPeriodStd = calcSecondPeriodStd;
	
	this.finalPeriodGrad = calcFinalPeriodGrad;
	this.finalPeriodExt = calcFinalPeriodExt;
	this.finalPeriodInc = calcFinalPeriodInc;
	this.finalPeriodStd = calcFinalPeriodStd;
	
	this.firstPeriodPmtGrad = calcFirstPeriodPmtGrad;
	this.secondPeriodPmtGrad = calcSecondPeriodPmtGrad;
	this.thirdPeriodPmtGrad = calcThirdPeriodPmtGrad;
	this.finalPeriodPmtGrad = calcFinalPeriodPmtGrad;
	
	this.firstPeriodPmtExt = calcFirstPeriodPmtExt;
	this.finalPeriodPmtExt = calcFinalPeriodPmtExt;
	
	this.firstPeriodPmtInc = calcFirstPeriodPmtInc;
	this.secondPeriodPmtInc = calcSecondPeriodPmtInc;

	
	this.firstPeriodPmtStd = calcFirstPeriodPmtStd;
	this.finalPeriodPmtStd = calcFinalPeriodPmtStd;
	
	this.nonSPPmt = calcNonSPPmt;
	
	this.totalPmtGrad = calcTotalPmtGrad;
	this.totalPmtExt = calcTotalPmtExt;
	this.totalPmtInc = calcTotalPmtInc;
	this.totalPmtStd = calcTotalPmtStd;
	
	this.interestGrad = calcInterestGrad;
	this.interestExt = calcInterestExt;
	this.interestInc = calcInterestInc;
	this.interestStd = calcInterestStd;
	
	this.loanTermAdjustedStd = calcLoanTermAdjustedStd;
	this.loanTermAdjustedExt = calcLoanTermAdjustedExt;
	this.loanTermAdjustedGrad = calcLoanTermAdjustedGrad;
	this.loanTermAdjustedInc = calcLoanTermAdjustedInc;
	
	this.loanValueFirstPeriodStd = calcLoanValueFirstPeriodStd;
	this.loanValueSecondPeriodStd = calcLoanValueSecondPeriodStd;
	this.loanValueFirstPeriodExt = calcLoanValueFirstPeriodExt;
	this.loanValueSecondPeriodExt = calcLoanValueSecondPeriodExt;
	this.loanValueFirstPeriodGrad = calcLoanValueFirstPeriodGrad;
	this.loanValueSecondPeriodGrad = calcLoanValueSecondPeriodGrad;
	this.loanValueThirdPeriodGrad = calcLoanValueThirdPeriodGrad;
	this.loanValueFirstPeriodInc = calcLoanValueFirstPeriodInc;
	this.loanValueSecondPeriodInc = calcLoanValueSecondPeriodInc;
	this.loanValueFinalPeriodInc = calcLoanValueFinalPeriodInc;
}

function calcTotalBalance()
{
	return this.loansBalance + this.otherBalance;
}

function calcTotalForTermCalc()
{
	var total = this.otherBalance;
	if (total > this.loansBalance)
		total = this.loansBalance;
	return total + this.loansBalance;
}

function calcLoanAmount()
{
	//return this.loansBalance;
	return FV((this.roundedAverageRate() / 365) / 100, 15 ,0, this.loanAmountUnAdjusted());
}

function calcLoanAmountUnAdjusted()
{
	return this.loansBalance;
}

function calcRoundedAverageRate()
{
    if (this.weightedRate  > 8.25)
		return 8.25;
	else
		return ceiling(this.weightedRate,0.125);
}

function calcIncludeBenefits()
{
	return this.includeACH & this.includeOnTime;
}

function calcRateWithACH()
{
	var rate = this.roundedAverageRate();
	if (this.includeACH == true)
	{
		rate -= this.achDiscount;
		if (rate < 0.125)
		{
			rate = 0.125;
		}
	}
	return rate;
}

function calcRateWithOnTime()
{
	var rate = this.roundedAverageRate();
	if (this.includeOnTime == true)
	{
		rate -= this.onTimeDiscount;
		if (rate < 0.125)
		{
			rate = 0.125;
		}
	}
	return rate;
}

function calcRateWithBenefits()
{
	var rate = this.roundedAverageRate();
	if (this.includeACH == true)
	{
		rate -= this.achDiscount;
	}
	if (this.includeOnTime == true)
	{
		rate -= this.onTimeDiscount;
	}
	if (rate < 0.125)
	{
		rate = 0.125;
	}
	return rate;
}

function calcGradConsTerm()
{
	//return this.totalBalance() < 7500 ? 10 : (this.totalBalance() < 10000 ? 12 : (this.totalBalance() < 20000 ? 15 : (this.totalBalance() < 40000 ? 20 : (this.totalBalance() < 60000 ? 25 : 30))));								
	return this.stdConsTerm();
}

function calcExtConsTerm()
{
	var result = 0;
	if( this.loansBalance >= 30000 && this.loansBalance < 40000)
	{
		result = 25;
	}
	return result;
}

function calcStdConsTerm()
{
	var total = this.totalForTermCalc();
	yrs = total < 7500 ? 10 : (total < 10000 ? 12 : (total < 20000 ? 15 : (total < 40000 ? 20 : (total < 60000 ? 25 : 30))));
	if (debug)
	{	debug = false;
		alert("bal0=" + this.loansBalance + ", other=" + this.otherBalance + ", total=" + total + ", yrs=" + yrs);
	}
	return yrs;
}

function calcIncConsTerm()
{
	//return this.totalBalance() < 7500 ? 10 : (this.totalBalance() < 10000 ? 12 : (this.totalBalance() < 20000 ? 15 : (this.totalBalance() < 40000 ? 20 : (this.totalBalance() < 60000 ? 25 : 30))));
	return this.stdConsTerm();
}

function calcFirstPeriodRate()
{
	var result = 0;
	if (this.includeACH == true)
	{
		result = this.rateWithACH();
	}
	else
	{
		result = this.roundedAverageRate();
	}
	return result;
}

function calcSecondPeriodRate()
{
	return this.rateWithBenefits();
}

function calcFinalPeriodRate()
{
	return this.rateWithBenefits();
}

function calcFirstPeriodGrad()
{
	return 24;
}

function calcFirstPeriodExt()
{
	var result = 0;
	if (this.loansBalance >= 30000 && this.loansBalance < 40000)
	{
		if (this.includeOnTime)
		{
			result = 24;
		}
		else
		{
			result = this.extConsTerm() * 12;
		}
	}
	return result;
}

function calcFirstPeriodInc()
{
	return 24;
}

function calcFirstPeriodStd()
{
	var result = 0;
	if (this.includeOnTime)
	{
		result = 24;
	}
	else
	{
		result = this.stdConsTerm() * 12;
	}
	return result;
}

function calcSecondPeriodGrad()
{
	return 36;
}

function calcSecondPeriodExt()
{
	return 0;
}

function calcSecondPeriodInc()
{
	return 0;
}

function calcSecondPeriodStd()
{
	return 0;
}

function calcFinalPeriodGrad()
{
	return this.gradConsTerm() * 12 - this.firstPeriodGrad() - this.secondPeriodGrad();
}

function calcFinalPeriodExt()
{
	var result = 0; // N/A
	if (this.loansBalance >= 30000 && this.loansBalance < 40000)
	{
		result = this.extConsTerm() * 12 - this.firstPeriodExt();
	}
	return result; 
}

function calcFinalPeriodInc()
{
	return this.incConsTerm() * 12 - this.firstPeriodInc();								
}

function calcFinalPeriodStd()
{
	return this.stdConsTerm() * 12 - this.firstPeriodStd();
}

function calcFirstPeriodPmtGrad()
{
	var result = this.roundedAverageRate() / 100 / 12 * this.loanAmount();
	return round(result, 2);
}

function calcSecondPeriodPmtGrad()
{
	var result = (
					PMT(
						this.roundedAverageRate() / 12 / 100, 
						(this.gradConsTerm() * 12 - 24) - (360 / (this.gradConsTerm() * 12)) * 5, 
						FV(
							this.roundedAverageRate() / 12 / 100, 
							24, 
							-this.firstPeriodPmtGrad(), 
							this.loanAmount()
						)
					) - this.firstPeriodPmtGrad()) / 1.9 + this.firstPeriodPmtGrad();
	
	return round(result,2);
}

function calcThirdPeriodPmtGrad()
{
	var  result = PMT(
						this.roundedAverageRate() / 12 /100, 
						this.gradConsTerm() * 12 - 60, 
						FV(
							this.roundedAverageRate() / 12 / 100, 
							36, 
							-this.secondPeriodPmtGrad(), 
							FV(
								this.roundedAverageRate() / 12 /100, 
								24,
								-this.firstPeriodPmtGrad(), 
								this.loanAmount()
							)
						)
					);
	
	return round(result, 2);
}

function calcFinalPeriodPmtGrad()
{
	var result = this.thirdPeriodPmtGrad() + this.loanValueThirdPeriodGrad();
	return round(result, 2);
}

function calcFirstPeriodPmtExt()
{
	var result = PMT(this.roundedAverageRate() / 12 / 100, this.extConsTerm() * 12, this.loanAmount());
	return round(result, 2);
}

function calcFinalPeriodPmtExt()
{
	var result = 0;
	if(this.includeOnTime)
	{
		result = PMT(
						this.roundedAverageRate() / 12 /100, 
						this.extConsTerm() * 12 - this.firstPeriodExt(), 
						FV(
							this.roundedAverageRate() / 12 / 100, 
							this.firstPeriodExt(), 
							-round(
									PMT(
										this.roundedAverageRate() / 12 / 100, 
										this.extConsTerm() * 12, 
										this.loanAmount()
									),
							2),
							this.loanAmount()
						)
					);
	}
	return round(result, 2);
}

function calcFirstPeriodPmtInc()
{
	var result = this.roundedAverageRate() * this.loanAmount() / 12 /100;
	return round(result, 2);
}

function calcSecondPeriodPmtInc()
{
	var result = PMT(
						this.roundedAverageRate() / 12 /100, 
						(this.incConsTerm() * 12) - 12, 
						FV(this.roundedAverageRate() / 12 / 100, 24, -round(this.firstPeriodPmtInc(),2),this.loanAmount())
					);
	return round(result, 2);
}                       
								
function calcFirstPeriodPmtStd()
{
	var result = PMT(this.roundedAverageRate() / 12 /100, this.stdConsTerm() * 12, this.loanAmount());
	return round(result, 2);
}

function calcFinalPeriodPmtStd()
{
	var result = 0;
	if (this.includeOnTime)
		result = PMT(this.roundedAverageRate() / 12 /100, this.stdConsTerm() * 12, this.loanAmount());

	return round(result, 2);
}
								
function calcNonSPPmt()
{
	var result = PMT(this.weightedRate / 12 / 100 ,120,this.loanAmountUnAdjusted());
	return result;
}

function calcTotalPmtGrad()
{
	var result = (this.firstPeriodPmtGrad() * 24)
				+ (this.secondPeriodPmtGrad() * (60 - 24))
				+ (this.thirdPeriodPmtGrad() * ((this.loanTermAdjustedGrad() - 60)- 1))
				+ (this.thirdPeriodPmtGrad() + this.loanValueThirdPeriodGrad());
	return round(result,2);
}
								
function calcTotalPmtExt()
{
	var result = (this.firstPeriodPmtExt() * (this.loanTermAdjustedExt() - 1))
				+ (this.firstPeriodPmtExt() + this.loanValueSecondPeriodExt());
	return round(result,2);
	//return result;
}

function calcTotalPmtInc()
{
	var result = (this.firstPeriodPmtInc() * 12)
				+ (this.secondPeriodPmtInc() * (this.loanTermAdjustedInc() - 13))
				+ (this.secondPeriodPmtInc() + this.loanValueFinalPeriodInc());
	return result;
}

function calcTotalPmtStd()
{
	var result = (this.firstPeriodPmtStd() * (this.loanTermAdjustedStd() - 1))
				+ (this.firstPeriodPmtStd() + this.loanValueSecondPeriodStd());
	return round(result,2);
	//return result;
}
								
function calcInterestGrad()
{
	return this.totalPmtGrad() - this.loanAmount();
}

function calcInterestExt()
{
	return this.totalPmtExt() - this.loanAmount();
}

function calcInterestInc()
{
	return this.totalPmtInc() - this.loanAmount();
}

function calcInterestStd()
{
	return this.totalPmtStd() - this.loanAmount();
}

function calcLoanTermAdjustedStd()
{
	var result = 0;
	result = roundUpAdjustedTerm((NPER(12,(this.finalPeriodRate() / 100),this.loanValueFirstPeriodStd(), this.firstPeriodPmtStd())) + 24);
	return result;
}

function calcLoanTermAdjustedExt()
{
	var result = 0;
	result = roundUpAdjustedTerm(
									(
										NPER(
												12,
												(this.finalPeriodRate() / 100),
												this.loanValueFirstPeriodExt(), 
												this.firstPeriodPmtExt()
											)
										) + 24);
	return result;
}
								
function calcLoanTermAdjustedGrad()
{
	var result = 0;
	result = roundUpAdjustedTerm((NPER(12,(this.finalPeriodRate() / 100),this.loanValueSecondPeriodGrad(), this.thirdPeriodPmtGrad())) + 60);
	return result;
}

function calcLoanTermAdjustedInc()
{
	var result = 0;
	result = roundUpAdjustedTerm(
									(NPER(12,(this.finalPeriodRate() / 100),this.loanValueSecondPeriodInc(), this.secondPeriodPmtInc())
								) + 24);
	return result;
}

function calcLoanValueFirstPeriodStd()
{
	var result = 0;
	result = FV(this.rateWithACH() / 12 / 100, 24, -round(this.firstPeriodPmtStd(),2),this.loanAmount());
	return result;
}
								
function calcLoanValueSecondPeriodStd()
{
	var result = 0;
	result = FV(
				this.secondPeriodRate() / 12 / 100, 
				(this.loanTermAdjustedStd() - 24), 
				-round(this.firstPeriodPmtStd(),2),
				this.loanValueFirstPeriodStd()
			);
	return result;
}

function calcLoanValueFirstPeriodInc()
{
	var result = 0;
	result = FV(this.rateWithACH() / 12 / 100, 12, -round(this.firstPeriodPmtInc(),2),this.loanAmount());
	return result;
}

function calcLoanValueSecondPeriodInc()
{
	var result = 0;
	result = FV(this.rateWithACH() / 12 / 100, (24 - 12), -round(this.secondPeriodPmtInc(),2),this.loanValueFirstPeriodInc());
	return result;
}
								
function calcLoanValueFinalPeriodInc()
{
	var result = 0;
	result = FV(
				this.finalPeriodRate() / 12 /100, 
				this.loanTermAdjustedInc() - 24, 
				-round(this.secondPeriodPmtInc(),2),
				this.loanValueSecondPeriodInc()
				);
	return result;
}
								
function calcLoanValueFirstPeriodExt()
{
	var result = 0;
	result = FV(this.rateWithACH() / 12 / 100, 24, -round(this.firstPeriodPmtExt(),2),this.loanAmount());
	return result;
}
								
function calcLoanValueSecondPeriodExt()
{
	var result = 0;									
	result = FV(
				this.secondPeriodRate() / 12 / 100, 
				(this.loanTermAdjustedExt() - 24), 
				-round(this.firstPeriodPmtExt(),2),
				this.loanValueFirstPeriodExt()
			);
	return result;
}
								
function calcLoanValueFirstPeriodGrad()
{
	var result = 0;
	result = FV(this.rateWithACH() / 12 / 100, 24, -round(this.firstPeriodPmtGrad(),2),this.loanAmount());
	return result;
}
								
function calcLoanValueSecondPeriodGrad()
{
	var result = 0;
	result = FV(this.secondPeriodRate() / 12 / 100, 60 - 24, -round(this.secondPeriodPmtGrad(),2),this.loanValueFirstPeriodGrad());
	return result;
}
								
function calcLoanValueThirdPeriodGrad()
{
	var result = 0;
	result = FV(
				this.secondPeriodRate() / 12 / 100, 
				(this.loanTermAdjustedGrad() - 60), 
				-round(this.thirdPeriodPmtGrad(),2),
				this.loanValueSecondPeriodGrad()
			);
	return result;
}
						
function roundUpAdjustedTerm(adjustedTerm, defaultTerm)
{
	var result = 0;
	if (adjustedTerm > 0)
	{
		if(adjustedTerm > defaultTerm)
		{
			result = defaultTerm;
		}
		else
		{
			var remainder = adjustedTerm % 1;
			result = (remainder > 0) ? (adjustedTerm - remainder) + 1 : adjustedTerm;
		}
	}
	return result;
}
