var CALCIMG_URLPREFIX = MEDIA_URL + '/res/img/calculators/';

// Generic function for any calculator with a 'SEE YOUR OPTIONS' area to update all of its columns
function updateOptionsDisplay(calculatorType, updateColumn) {
    if (calculatorType == 'simple') {
        var columns = [ 'interest', 'rates', 'years' ];
        var calcTableBody = $('calcTableBody');
    }
    else if (calculatorType == 'debtrepayment') {
        var columns = [ 'balance', 'debtRates', 'payments' ];
        var calcTableBody = $('Calc2');
    }
    else {
        throw new Exception('Unknown calculator type');
    }

    columns.each(function(thisCol) {
        var header = $(thisCol + 'Header');
        var button = $(thisCol + 'Btn');

        if (updateColumn == thisCol) {
            header.addClassName('selected');
            button.src = CALCIMG_URLPREFIX + thisCol + 'Inactive.png';
            button.style.cursor = 'default';
        }
        else {
            header.removeClassName('selected');
            button.src = CALCIMG_URLPREFIX + thisCol + 'Active.png';
            button.style.cursor = 'pointer';
        }
    });

    if (calcTableBody.style.display == 'none') {
        calcTableBody.style.display = 'block';
		calcTableBody.style.paddingBottom = '20px';
    }
}






// Simple Loan Calculator
function LoanValues() {
    this.loan = getNumber('loanVal');
    this.yearlyRate = getNumber('rateVal');
    this.year = getNumber('monthVal');
    this.pay = calculateMoPayment(this.loan, this.yearlyRate, this.year);
}
LoanValues.prototype.invalid = function() {
    return !this.loan || !this.yearlyRate || !this.year;
}

// Simple Loan Calculator: Calculate simple loan monthly payment, based on loan amount, yearly rate, and number of years
function calculateMoPayment(loanAmt, yearlyRate, numYears) {
    var numMonths = numYears * 12;
    var monthlyRate = yearlyRate / 1200;

    return loanAmt * (monthlyRate / (1 - (Math.pow((1 + monthlyRate), -numMonths))));
}
// Simple Loan Calculator: Used by updateLoanResults to update each element under the 'Monthly Payments' column
function updateMoPay(i, plusOrMinus, loanAmt, yearlyRate, numYears) {
    var moPay = calculateMoPayment(loanAmt, yearlyRate, numYears);
    $('colMoPay' + plusOrMinus + i).update(formatCurrency(moPay));
}

// Simple Loan Calculator: 'Calculate' button enters here, as does any click on 'See Additional Amounts'
// This is the function that does 'Lower by 5, Lower by 10, ...'
function updateLoanResults(updateColumn) {
    var vals = new LoanValues();

    if (vals.invalid()) {
        alert('Please provide non-zero values for loan amount, interest rate, and number of years');
        return;
    }

    // Update the 'Your Monthly Payments' area, which displays results for your inputs unadjusted
    $("colAmountBox").update(formatCurrency(vals.loan));
    $("colInterestBox").update(vals.yearlyRate + '%');
    $("colYearsBox").update(vals.year);

    // Update the most important number - what the user asked for - under "Monthly Payments" (2. Your Monthly Payments)
	var palVal = $('payVal');
	palVal.update(formatCurrency(vals.pay));
    //if (palVal.style.fontWeight && palVal.style.fontWeight != "700") {
	if (palVal) {
		palVal.style.fontWeight = "700";
        palVal.style.color = "#000";
        palVal.style.fontSize = "20px";
        palVal.style.padding = "0";
        palVal.style.padding = ".52em 0";
    }

    // Setup callback functions for each +/- operation
    if (updateColumn == 'interest') {
        var amountMinusCbk = function(i) { $('colAmountMinus' + i).update(formatCurrency(vals.loan - vals.loan * (i/100))); $('colAmountMinus' + i).style.backgroundColor = "#f1ffed";};
        var intMinusCbk = function(i) { $('colIntMinus' + i).update(vals.yearlyRate + '%'); $('colIntMinus' + i).style.backgroundColor = "#fff";};
        var yearMinusCbk = function(i) { $('colYearMinus' + i).update(vals.year); $('colYearMinus' + i).style.backgroundColor = "#fff"; };
        var moPayMinusCbk = function(i) {
            updateMoPay(i, 'Minus', vals.loan - vals.loan * (i/100), vals.yearlyRate, vals.year);
        };

        var amountPlusCbk = function(i) { $('colAmountPlus' + i).update(formatCurrency(vals.loan + vals.loan * (i/100)));  $('colAmountPlus' + i).style.backgroundColor = "#f1ffed";};
        var intPlusCbk = function(i) { $('colIntPlus' + i).update(vals.yearlyRate + '%'); $('colIntPlus' + i).style.backgroundColor = "#fff";};
        var yearPlusCbk = function(i) { $('colYearPlus' + i).update(vals.year); $('colYearPlus' + i).style.backgroundColor = "#fff";};
        var moPayPlusCbk = function(i) {
            updateMoPay(i, 'Plus', vals.loan + vals.loan * (i/100), vals.yearlyRate, vals.year);
        };
    }

    else if (updateColumn == 'rates') {
        var calcInt = function(i, isPlus) {
            if (isPlus) {
                var multiplier = 1;
            }
            else {
                var multiplier = -1;
            }
            var value = vals.yearlyRate + (multiplier * vals.yearlyRate * (i/100));
            return value.toFixed(2);
        }

        var amountMinusCbk = function(i) { $('colAmountMinus' + i).update(formatCurrency(vals.loan)); $('colAmountMinus' + i).style.backgroundColor = "#fff"; };
        var intMinusCbk = function(i) { $('colIntMinus' + i).update(calcInt(i, false) + '%'); $('colIntMinus' + i).style.backgroundColor = "#f1ffed";};
        var yearMinusCbk = function(i) { $('colYearMinus' + i).update(vals.year);$('colYearMinus' + i).style.backgroundColor = "#fff"; };
        var moPayMinusCbk = function(i) {
            updateMoPay(i, 'Minus', vals.loan, calcInt(i, false), vals.year);
        };

        var amountPlusCbk = function(i) { $('colAmountPlus' + i).update(formatCurrency(vals.loan)); $('colAmountPlus' + i).style.backgroundColor = "#fff"; };
        var intPlusCbk = function(i) { $('colIntPlus' + i).update(calcInt(i, true) + '%'); $('colIntPlus' + i).style.backgroundColor = "#f1ffed"; };
        var yearPlusCbk = function(i) { $('colYearPlus' + i).update(vals.year); $('colYearPlus' + i).style.backgroundColor = "#fff";};
        var moPayPlusCbk = function(i) {
            updateMoPay(i, 'Plus', vals.loan, calcInt(i, true), vals.year);
        };
    }

    else if (updateColumn == 'years') {
        var amountMinusCbk = function(i) { $('colAmountMinus' + i).update(formatCurrency(vals.loan)); $('colAmountMinus' + i).style.backgroundColor = "#fff"; };
        var intMinusCbk = function(i) { $('colIntMinus' + i).update(vals.yearlyRate.toFixed(2) + '%'); $('colIntMinus' + i).style.backgroundColor = "#fff"; };
        var yearMinusCbk = function(i) { $('colYearMinus' + i).update(vals.year - vals.year*(i/100)); $('colYearMinus' + i).style.backgroundColor = "#f1ffed";};
        var moPayMinusCbk = function(i) {
            updateMoPay(i, 'Minus', vals.loan, vals.yearlyRate, vals.year - vals.year * (i/100));
        }

        var amountPlusCbk = function(i) { $('colAmountPlus' + i).update(formatCurrency(vals.loan));$('colAmountPlus' + i).style.backgroundColor = "#fff"; };
        var intPlusCbk = function(i) { $('colIntPlus' + i).update(vals.yearlyRate.toFixed(2) + '%');  $('colIntPlus' + i).style.backgroundColor = "#fff"; };
        var yearPlusCbk = function(i) { $('colYearPlus' + i).update(vals.year + vals.year*(i/100));  $('colYearPlus' + i).style.backgroundColor = "#f1ffed";};
        var moPayPlusCbk = function(i) {
            updateMoPay(i, 'Plus', vals.loan, vals.yearlyRate, vals.year + vals.year * (i/100));
        }
    }

    for (var i = 15; i >= 5; i -= 5) {
        amountMinusCbk(i);
        intMinusCbk(i);
        yearMinusCbk(i);
        moPayMinusCbk(i);

        amountPlusCbk(i);
        intPlusCbk(i);
        yearPlusCbk(i);
        moPayPlusCbk(i);
    }

    updateOptionsDisplay('simple', updateColumn);
}





// Home Affordability Calculator: This is the entry point.
// The home affordability calculator is a straightforward calculation with no see-your-options area.
function updateAffordability() {
    var monthlyIncome = getNumber('income');
    var debtPmts = getNumber('debtpmts');
    var downPmt = getNumber('downpmt');
    var intrRate = getNumber('intrrate');

    var loanStats = new LoanStats(monthlyIncome, debtPmts, downPmt, intrRate);
    if (!loanStats.isReady()) {
        alert('Please provide values for monthly income, down payment, debt payments, and interest rate.');
        return;
    }

    if (loanStats.totalMonthlyPayment <= 0 || loanStats.loanAmt <= 0) {
        alert('Your monthly debt to income ratio is too high. Please reduce your debt payments and try again.');
        return;
    }

    $('calcResults').style.display = 'none';
    $('Calc3').style.display = 'block';

    var displayTMP = formatCurrency(loanStats.totalMonthlyPayment);

    $('pmi').update(formatCurrency(loanStats.pmi));
    $('monthlyTotal').update(displayTMP);
    $('monthlyPrinc').update(formatCurrency(loanStats.monthlyPrincAndIntr));
    $('loanAmount').update(formatCurrency(loanStats.loanAmt));
    $('homeowners').update(formatCurrency(LoanStats.insurance));
    $('proptax').update(formatCurrency(LoanStats.propertyTaxes));
    $('homePurchasePrice').update(formatCurrency(loanStats.maxAllowableHouseValue))
    $('downPaymentPrcnt').update(loanStats.downPmtPercentage + '%');
	var monthlyPayments = $('monthlyPayments');
	monthlyPayments.update(displayTMP);
	if (monthlyPayments) {
		monthlyPayments.style.fontWeight = "700";
		monthlyPayments.style.color = "#000";
		monthlyPayments.style.fontSize = "20px";
		monthlyPayments.style.padding = "0";
		monthlyPayments.style.padding = ".52em 0";
	}
}

// Home Affordability Calculator: Preps data for the formula that calculates affordability
function LoanStats(monthlyIncome, debtPmts, downPmt, intrRate) {
    this.mortgageInterestRate = intrRate / (12 * 100);
    this.monthlyIncome = monthlyIncome;
    this.debtPmts = debtPmts;
    this.downPmt = downPmt;
    this.totalMonthlyPayment = this.monthlyIncome * 0.39 - this.debtPmts;

    if (this.downPmt == false) {
        this.downPmt = 0;
    }
    if (this.debtPmts == false) {
        this.debtPmts = 0;
    }

    this.pmi = 0;
    this.calcLoanAmtStats();

    if (this.downPmtPercentage < 20) {
        this.pmi = this.loanAmt / 100000 * 75;
        this.calcLoanAmtStats();
    }
}
// Home Affordability Calculator: The function that actually calculates affordability.
LoanStats.prototype.calcLoanAmtStats = function() {
    this.monthlyPrincAndIntr = this.totalMonthlyPayment - this.pmi - LoanStats.insurance - LoanStats.propertyTaxes;
    this.loanAmt = (this.monthlyPrincAndIntr) * (1 - Math.pow(1 + this.mortgageInterestRate, -LoanStats.duration)) / this.mortgageInterestRate;
    this.maxAllowableHouseValue = this.loanAmt + this.downPmt;
    var downPmtPrcnt = 100 * this.downPmt / this.maxAllowableHouseValue;
    this.downPmtPercentage =  downPmtPrcnt.round();
};
LoanStats.prototype.isReady = function() {
    if (!this.monthlyIncome || this.monthlyIncome < 800 || !this.mortgageInterestRate || isNaN(this.loanAmt)) {
        return false;
    }
    return true;
}
LoanStats.propertyTaxes = 292;
LoanStats.insurance = 41;
LoanStats.duration = 360;




// Debt Repayment Calculator
function DebtValues() {
    this.balance = getNumber('balanceVal'); // Balance Owed
    this.yearlyRate = getNumber('debtRateVal'); // Interest Rate
    this.fixedPmt = getNumber('debtMonthVal'); // Expected Monthly Payment
    this.payoffMonths = getNumber('payoffTime'); // Desired Payoff Timeframe
}
DebtValues.prototype.invalid = function() {
    return !this.balance || !this.yearlyRate || (!this.fixedPmt && !this.payoffMonths);
}
DebtValues.prototype.updateRow = function(i, highlightColumn, newBalance, newYearlyRate, newFixedPmt) {
    newBalance = newBalance || this.balance;
    newYearlyRate = newYearlyRate || this.yearlyRate;
    newFixedPmt = newFixedPmt || this.fixedPmt;

    newBalance = Math.round(newBalance);
    newYearlyRate = Math.round(newYearlyRate * 100) / 100;
    newFixedPmt = Math.round(newFixedPmt);

    var payoffTime = calculatePayoffTime(newBalance, newYearlyRate, newFixedPmt);

    if (isNaN(payoffTime)) {
        payoffTime = "Payment is too low";
    }
    else {
        payoffTime += " months";
    }

    var colBalance = $('colBalance' + i);
    colBalance.update(formatCurrency(newBalance));

    var colInt = $('colInt' + i);
    colInt.update(newYearlyRate + "%");

    var colPayments = $('colPayments' + i);
    colPayments.update(formatCurrency(newFixedPmt));

    var colMoToPay = $('colMoToPay' + i);
    colMoToPay.update(payoffTime);

    var eleToHighlight;
    switch (highlightColumn) {
        case 'balance':
            eleToHighlight = colBalance;
            var blackBackgroundAry = [ colInt, colPayments ];
        break;

        case 'int':
            eleToHighlight = colInt;
            var blackBackgroundAry = [ colBalance, colPayments ];
            break;

        default:
            eleToHighlight = colPayments;
            var blackBackgroundAry = [ colBalance, colInt ];
            break;
    }

    var j;
    for (j = 0; j < blackBackgroundAry.length; j++) {
        blackBackgroundAry[j].style.backgroundColor = "#fff";
    }

    eleToHighlight.style.backgroundColor = "#f1ffed";
}
function calculatePayoffTime(balance, yearlyRate, fixedPmt) {
    var monthlyRate = yearlyRate / 1200;

    return Math.round(Math.log(1 - (balance / fixedPmt) * monthlyRate) / Math.log(1 + monthlyRate)) * -1;
}
function calculateMinimumPayment(balance, yearlyRate, months, noRound) {
    var monthlyRate = yearlyRate / 1200;

    var pmt = balance * monthlyRate / (1 - (Math.pow((1 + monthlyRate), -months)));

    if (!noRound) {
        return Math.round(pmt);
    }
    else {
        return pmt;
    }
}
var gHaveRunDebtRepayment = false;
var gDataDebtRepayment = "";
function updateDebtResults(updateColumn) {
    var vals = new DebtValues();

    if (vals.invalid()) {
        alert('Please provide non-zero values for balance amount, interest rate, and amount of monthly payments');
        return;
    }

    // If the user specifies a "desired payoff timeframe" instead of an "expected monthly payment" then we
    // figure out the minimum payment for that timeframe, set fixedPmt to that, and proceed as normal
    if (!vals.fixedPmt) {
        vals.fixedPmt = calculateMinimumPayment(vals.balance, vals.yearlyRate, vals.payoffMonths);
    }

    var payoffTime = calculatePayoffTime(vals.balance, vals.yearlyRate, vals.fixedPmt);

    // If the "expected monthly payment" is too low, then payoffTime comes back NaN and we have to suggest a minimum payment for the user
    if (isNaN(payoffTime) || (payoffTime == Infinity)) {
        var minPmt = calculateMinimumPayment(vals.balance, vals.yearlyRate, 36);
        alert('Expected monthly payment is too low. For example, the minimum payment on a 36 month plan would be $' + minPmt);
        return;
    }

    // Update the Amortization Chart first
    var i, monthlyInterestAmt, loanAmt = vals.balance, monthlyRate = vals.yearlyRate / 1200;
    var principalPaid, cumulativeInterest = 0, cumulativePrincipal = 0;
    for (i = 1; i <= payoffTime; i++) {
        //step1: calculate current monthly interest
        //  = LA * InterestRate/1200
        monthlyInterestAmt = loanAmt * monthlyRate;

        //step2: calculate monthly payment minus monthly interest, ie principal paid
        // = P-MonthlyInterest (step1)
        principalPaid = vals.fixedPmt - monthlyInterestAmt;

        //step3: calculate new loan balance
        // = LA- principal paid(step2)
        //step4: set loan amount to be equal to new loan balance(step3) and go back to step1
        loanAmt = loanAmt - principalPaid;

        cumulativeInterest += monthlyInterestAmt;
        cumulativePrincipal += principalPaid;
    }

    var roundedPrincipal = Math.round(cumulativePrincipal);
    var roundedInterest = Math.round(cumulativeInterest);
    gDataDebtRepayment = "Principal;" + roundedPrincipal + "\nInterest;" + roundedInterest;

    if (gHaveRunDebtRepayment) {
        amChartInited('debtrepayment');
    }
    else {
        gHaveRunDebtRepayment = true;
    }

    $('chartprincipal').update(formatCurrency(roundedPrincipal));
    $('chartinterest').update(formatCurrency(roundedInterest));
    // Done updating Amortization Chart

    $('CalcGraphs').style.display = 'block';
    $('CalcGraphsInactive').style.display = "none";

    // Update the summary
    $('balance').update(formatCurrency(vals.balance));
    $('interestRate').update(vals.yearlyRate + "%");
    $('expectedMonthlyPayment').update(formatCurrency(vals.fixedPmt));
    var payoffTimeSummary = $('payoffTimeSummary');
    payoffTimeSummary.update(payoffTime + " months");
    payoffTimeSummary.style.fontSize = "21px";
    payoffTimeSummary.style.fontWeight = "bold";
    $('payoffOptions').update('Click on a column to see results for similar loan amounts, interest rates, and durations');

    if (updateColumn == 'balance') {
        var callback = function(i) {
            vals.updateRow(i, 'balance', vals.balance + (vals.balance * i / 100), null, null);
        };
    }

    else if (updateColumn == 'debtRates') {
        var callback = function(i) {
            vals.updateRow(i, 'int', null, vals.yearlyRate + (vals.yearlyRate * i / 100), null);
        }
    }

    else {
        var callback = function(i) {
            vals.updateRow(i, 'fixedpmt', null, null, vals.fixedPmt + (vals.fixedPmt * i / 100));
        }
    }

    for (var i = 30; i >= -30; i -= 10) {
        if (i) {
            callback(i);
        }
    }

    //$('Calc2').style.display = "block";


    updateOptionsDisplay('debtrepayment', updateColumn)
}
function debtRepaymentInputChg(chgdId) {
    if (chgdId == 'debtMonthVal') {
        var otherInput = 'payoffTime';
    }
    else {
        var otherInput = 'debtMonthVal';
    }

    if (getNumber(chgdId)) {
        $(chgdId + 'Label').removeClassName('payoffInactive');

        $(otherInput + 'Label').addClassName('payoffInactive');
        $(otherInput).value = '';
    }
    else {
        $(chgdId + 'Label').addClassName('payoffInactive');

        if (getNumber(otherInput)) {
            $(otherInput + 'Label').removeClassName('payoffInactive');
        }
    }
}


// Debt Amortization Calculator
var gHaveRunAmortization = false;
var gDataAmortization = "";
var gDataIntrPrin = "";
var gDataIntrPrinMaxPmt = "";
function amortization() {
    var loanAmt = getNumber('loanVal');
    var yearlyRate = getNumber('rateVal');
    var numYears = getNumber('monthVal');
    var numMonths = numYears * 12;
	$('loanAmortizationChart').style.display = 'block';
	$('principalPaymentChart').style.display = 'block';
	$('scrollableDiv').style.display = 'block';
	$('loanAmortizationChartStatic').style.display = 'none';
	$('principalPaymentChartStatic').style.display = 'none';
	$('amortizationNote').style.display = 'none';

    if (!loanAmt || !yearlyRate || !numYears) {
        alert('Please provide non-zero values for Loan Amount, Interest Rate, and Number of Years');
        return;
    }

    if (yearlyRate >= 100) {
        alert('Please provide an interest rate that is less than 100%.');
        return;
    }

    calcAmorMoPmt(loanAmt, yearlyRate, numMonths);

    $('Calc2').style.display = "block";

    if (gHaveRunAmortization) {
        amChartInited('flashBalChart');
        amChartInited('prinAndInterest');
    }
    else {
        gHaveRunAmortization = true;
    }
}
function calcAmorMoPmt(loanAmt, yearlyRate, numMonths) {
    var origLoanAmtCurrency = formatCurrency(loanAmt);

    var monthlyRate = yearlyRate / 1200;

    // First, find the payment
    // Payment(P) = Loan Amount(LA) * (InterestRate/(1200)) / 1-(1+(InterestRate/1200)^ -n
	// Where n= months
    var payment = calculateMinimumPayment(loanAmt, yearlyRate, numMonths, true);
    var paymentCurrency = formatCurrency(Math.round(payment));

    var i = 1;
    var monthlyInterestAmt = 0;
    var principalPaid = 0;

    var tr;
    var newTable = new Element("tbody");
    //newTable.addClassName('loanCalcTable');
    //newTable.addClassName('variations');

    var curDate = new Date();

    gDataAmortization = "";
    gDataIntrPrin = "";
    gDataIntrPrinMaxPmt = Math.round(payment);

    var cumulativeInterest = 0;
    var cumulativePrincipal = 0;
    var year = 0;

    for (i = 1; i <= numMonths; i++) {
        // First, increment the date
        curDate.setMonth(curDate.getMonth() + 1);

        //step1: calculate current monthly interest
        //  = LA * InterestRate/1200
        monthlyInterestAmt = loanAmt * monthlyRate;

        //step2: calculate monthly payment minus monthly interest, ie principal paid
        // = P-MonthlyInterest (step1)
        principalPaid = payment - monthlyInterestAmt;

        //step3: calculate new loan balance
        // = LA- principal paid(step2)
        //step4: set loan amount to be equal to new loan balance(step3) and go back to step1
        loanAmt = loanAmt - principalPaid;

        tr = new Element("tr");
        addElementWithText(tr, i + " - " + translateMonth(curDate.getMonth()) + " " + curDate.getFullYear(), new Element("td", { width: "150", style: "text-align:left;padding-left:5px;font-weight:700" }));
        addElementWithText(tr, paymentCurrency, new Element("td", { width: "180" }));
        addElementWithText(tr, formatCurrency(Math.round(monthlyInterestAmt)), new Element("td", { width: "140" }));
        addElementWithText(tr, formatCurrency(Math.round(principalPaid)), new Element("td", { width: "160" }));
        addElementWithText(tr, '', new Element("td", { width: "7", style: "border-top:none;border-bottom:none;background-color:#fff;" }));
        addElementWithText(tr, formatCurrency(Math.round(loanAmt)), new Element("td", { width: "170" }));
        newTable.appendChild(tr);

        cumulativeInterest += monthlyInterestAmt;
        cumulativePrincipal += principalPaid;

        if (i % 12 == 0) {
            year = i / 12;
            gDataAmortization += year + ";" + Math.round(cumulativeInterest) + ";" + Math.round(cumulativePrincipal) + ";" + Math.round(loanAmt) + "\n";
            gDataIntrPrin += year + ";" + Math.round(monthlyInterestAmt) + "\n";
        }

              /*<td width="150" style="text-align: left; padding-left: 5px; font-weight: 700">1 - 2009</td>
                <td width="180" id="">$200</td>
                <td width="140" id="">6.5%</td>
                <td width="160" id="">30</td>
				<td width="7" id="" style="border-top: none; border-bottom: none; background-color: #fff;">&nbsp;</td>
				<td width="170" id="">$2,686</td>*/
    }

    $('colAmountBox').update(paymentCurrency); // Update 'Monthly Principal & Interest'
    $('colInterestBox').update(numMonths); // Update 'Number of Payments'
    $('colYearsBox').update(formatCurrency(Math.round(numMonths * payment))); // Update 'Total Payments'
    var origLoanAmtBox = $('payVal');
    origLoanAmtBox.update(origLoanAmtCurrency); // Update 'Original Loan Amount'
    origLoanAmtBox.style.fontSize = "20px";
    origLoanAmtBox.style.fontWeight = "bold";

    var fullTable = $('fullTableBody');
    if (fullTable) {
        fullTable.parentNode.removeChild(fullTable);
    }
    $('fullTable').appendChild(newTable);
    newTable.id = "fullTableBody";
}

function amReturnData(chart_id, data) {
    alert("chart id: " + chart_id + ", data: " + data);
}

function amChartInited(chart_id) {
    var flashMovie = $(chart_id);

    if (flashMovie && flashMovie.setData) {
        if (chart_id == 'flashBalChart' && gDataAmortization && gDataAmortization.length) {
            flashMovie.setData(gDataAmortization);
        }

        else if (chart_id == 'prinAndInterest' && gDataIntrPrin && gDataIntrPrin.length) {
            flashMovie.setData(gDataIntrPrin);
            flashMovie.setParam("guides.guide[0].end_value", gDataIntrPrinMaxPmt);
            flashMovie.setParam("values.y_left.max", gDataIntrPrinMaxPmt);
            flashMovie.setParam("values.y_left.strict_min_max", true);
        }

        else if (chart_id == 'debtrepayment' && gDataDebtRepayment && gDataDebtRepayment.length) {
            flashMovie.setData(gDataDebtRepayment);
        }
    }
}