

function amortizationObject(formName, valueSource) {
    this.formName             = new Object();
    this.formName             = formName;
    this.loanAmount           = 5000.0;
    this.nrOfMonths           = 60;
    this.interestRate         = 6.0;
    this.unroundedPayment     = 87.92;
    this.paymentMonths        = new Array();
	this.paymentPeriod		   = 12;
	this.nrOfYears            = 30;
    this.paymentNr            = this.paymentPeriod * this.nrOfYears;
    this.payment              = new Array();
    this.interestPaid         = new Array();
    this.totalInterest        = new Array();
    this.principalPaid        = new Array();
    this.balance              = new Array();
    this.startDate            = new Date();
    this.args                 = new Object();
    this.valueSource          = valueSource;
    this.clearPayment         = clearPayment;
    this.getValues            = getValues;
    this.putValues            = putValues;
    this.doAmortization       = doAmortization;
    this.printString          = '';
	this.doAmortization();
    return;
}

function doAmortization() {
    var returnValue  = this.getValues();
    if (!returnValue) return returnValue;
    var blnc         = this.loanAmount;
    var rate         = this.interestRate / (12 * 100);// 12=monthly, 4=quartly, 1=yearly
    var totInt       = 0.0;
    var factr        = 1;
    var ratePlusOne  = rate + 1;
	var numPeriods   = 12 * this.nrOfYears;

	for (var i = 0; i < this.nrOfMonths; i++){
        factr *= ratePlusOne;
    }
    if (factr > 1) {
		switch (this.valueSource) {
			case 'monthly':
				this.unroundedPayment = (this.loanAmount * rate * exp(1+rate,numPeriods)) / (exp(1+rate,numPeriods) - 1);
				returnValue = true;
				this.payment[0]       = 0;
				this.balance[0]       = displayDec(blnc, 2);
				this.interestPaid[0]  = 0;
				this.totalInterest[0] = 0;
				this.principalPaid[0] = 0;
				break;
				
			case 'amount':
				this.loanAmount = (this.unroundedPayment / rate) * (1 - 1/(exp(1+rate,numPeriods)));
				returnValue = true;
				this.payment[0]       = 0;
				this.balance[0]       = displayDec(blnc, 2);
				this.interestPaid[0]  = 0;
				this.totalInterest[0] = 0;
				this.principalPaid[0] = 0;
				break;
				
			default:
				returnValue = false;
				break;
		}

    }else{
        returnValue = false;
    }
	this.putValues(returnValue);
    return returnValue;
}

function validateNumber(localItem, minValue, maxValue, msg) {
    var decPtAt = 0;
    for (var i = 0; i < localItem.value.length; i++){
        var localChar  = localItem.value.charAt(i);
        if (localChar < "0" || localChar > "9"){
            if (localChar == "." && decPtAt == 0){
                decPtAt = i + 1;
            }else{
                if (localChar == " "){
                    localChar = "Spaces cannot";
                }else if (localChar == "."){
                    localChar = "Only one decimal point can";
                }else{
                    localChar = "The character \"" + localChar
                                + "\" cannot";
                }
                alert(localChar + " be used in the " + msg + " field." +
                    "  Please correct your entry to use only numerical" +
                    " values, a single decimal point, and no spaces or" +
                    " commas.");
                localItem.focus();
                localItem.select();
                return false;
            }
        }
    }
    return checkLimits(localItem, minValue, maxValue, msg);
}

function checkLimits(localItem, minValue, maxValue, msg) {
    if (localItem.value < minValue || localItem.value > maxValue){
        alert("Value for the " + msg + " field must be between "
            + minValue + " and " + maxValue + ".");
        localItem.focus();
        localItem.select();
        return false;
    }
    return true;
}

function displayDec(val, decs){
    var factr = 1;
    for (var i = 0; i < decs; i++){
        factr *= 10;
    }
    var outputStr = Math.round(factr * val) + '';
    while (outputStr.length - decs < 1){
        outputStr = '0' + outputStr;
    }
    var pos = outputStr.length - decs;
    return outputStr.substring(0, pos) + '.' + outputStr.substring(pos);
}

function getValid(obj, val){
    var val1 = val;
    if (parseFloat("0.0") != null && obj.value != null && obj.value.length > 0)
            val = parseFloat(obj.value);
    if (isNaN(0) != null && isNaN(val)) return val1;
    return val;
}

function clearPayment(){
    this.formName.monthlyPayment.value = "";
}

function clearAmount(){
    this.formName.loanAmount.value = "";
}

function getValues(){
    var returnValue = false;
    if (this.valueSource == 'monthly'){
        if ((this.formName.nrOfYears.value == null
                || this.formName.nrOfYears.value.length == 0)
            || (this.formName.interestRate.value == null
                || this.formName.interestRate.value.length == 0)
            || (this.formName.loanAmount.value == null
                || this.formName.loanAmount.value.length == 0)) {
            return returnValue;
        }
        if (!validateNumber(   this.formName.nrOfYears, 0.08333,       40, "Loan Term (years)")
            || !validateNumber(this.formName.interestRate,    1,       99, "Annual Interest Rate")
            || !validateNumber(this.formName.loanAmount,      1, 10000000, "Loan Amount")) {
            return returnValue;
        }
        this.interestRate      = parseFloat(this.formName.interestRate.value);
        this.loanAmount        = parseFloat(this.formName.loanAmount.value);
		this.nrOfYears         = parseFloat(this.formName.nrOfYears.value);
        this.nrOfMonths        = Math.round(this.nrOfYears * 12);
		this.paymentNr         = this.paymentPeriod * this.nrOfYears;
        returnValue = true;
    }else if (this.valueSource == 'amount'){
        if ((this.formName.nrOfYears.value == null
                || this.formName.nrOfYears.value.length == 0)
            || (this.formName.interestRate.value == null
                || this.formName.interestRate.value.length == 0)
            || (this.formName.monthlyPayment.value == null
                || this.formName.monthlyPayment.value.length == 0)) {
            return returnValue;
        }
        if (!validateNumber(   this.formName.nrOfYears, 0.08333,       40, "Loan Term (years)")
            || !validateNumber(this.formName.interestRate,    1,       99, "Annual Interest Rate")
            || !validateNumber(this.formName.monthlyPayment,      1, 10000000, "Monthly Payment")) {
            return returnValue;
        }
        this.interestRate      = parseFloat(this.formName.interestRate.value);
        this.unroundedPayment    = parseFloat(this.formName.monthlyPayment.value);
		this.nrOfYears         = parseFloat(this.formName.nrOfYears.value);
        this.nrOfMonths        = Math.round(this.nrOfYears * 12);
		this.paymentNr         = this.paymentPeriod * this.nrOfYears;
        returnValue = true;
    }else{
        this.args = getArgs();
        if (this.args.nrOfMonths != null)
            this.nrOfMonths = Math.round(parseFloat(this.args.nrOfMonths));
        if (this.args.interestRate != null)
            this.interestRate = parseFloat(this.args.interestRate);
        if (this.args.loanAmount != null)
            this.loanAmount = parseFloat(this.args.loanAmount);
        if (this.args.unroundedPayment != null)
            this.unroundedPayment = parseFloat(this.args.unroundedPayment);
        returnValue = true;
    }
    return returnValue;
}

function putValues(noError){
    if (noError){
        this.formName.nrOfYears.value
            = displayDec(this.nrOfYears, 2);
        this.formName.interestRate.value
            = displayDec(this.interestRate, 2);
        this.formName.loanAmount.value
            = displayDec(this.loanAmount, 2);
        this.formName.unroundedPayment.value
            = this.unroundedPayment;
        this.formName.monthlyPayment.value
            = displayDec(this.unroundedPayment, 2);
    }else{
        this.formName.monthlyPayment.value = "Error";
    }
}

function exp(a,b){
t = 1;
 for(x = 1; x <= b; x++) {
     t = t * a;
    }
EXP = t;
return(EXP);
}