////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//  File name   : amortization.js                                             //
//  Last edited : May 20, 2005  (Updated 01/02/06 by Ian Williamson)                                              //
//  Author      : Ralph Mayer                                                 //
//  Contact     : Ralph Mayer ( ralmayo20_at_dokie_dot_ca )                   //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//                              dollar_amount()                               //
// Ensures a correct dollar amount (0.00) is returned for any input argument. //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

function dollar_amount( num ) {
   
    /* Ensure input is a string. */
    var val = num + '';

    /* Add decimal pont and two zeros if none exist ... */
    if ( -1 == val.indexOf( '.' ) ) {
        val += '.00';

    /* ... or add a single zero in the case of only 
       a single decimal place. */
    } else if ( val.indexOf( '.' ) == val.length-2 ) {
         val += '0'
    }

    /* Return the converted value */
    return val;
}


////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//                                schedule()                                  //
//     Produces the amortization schedule for the amorization HTML page.      //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

function schedule( principal, interest_rate, num_years ) {
/*                              i    1/6
                           ( 1 + --- )       -  1
                                 200
    monthly payment = p x ------------------------
                                       i    1/6   -12 x n
                          1 - [ ( 1 + --- )     ] 
                                      200 
    Where:
    p = principal outstanding
    i = annual interest rate percentage
    n = number of years
    
    Thanks to http://www.hughchou.org/calc/formula.html
*/
    
    var p = principal.value;     /* Principal (initial loan amount) */
    var i = interest_rate.value; /* Annual interest rate percentage */
    var n = num_years.value;     /* Number of years */
    var j = 1;                   /* Simple counter */
    var y = 0;                   /* Total principal paid */
    var z = 0;                   /* Total cash paid */
    var row = 'odd';             /* HTML table row */
    var message = '';            /* Error message */
    var a = 0;                   /* Term */

    var pattern_p = /^\d+\.?\d{0,2}$/; /* RegEx pattern for principal */
    var pattern_i = /^\d{1,3}\.?\d*$/; /* RegEx pattern for interest */
    var pattern_n = /^\d+\.?\d{0,3}$/; /* RegEx pattern for term */
    var stripper  = /[^\d.]/g;         /* RegEx pattern to strip anything
                                          that isn't a number or a decimal */

    /* Strip everything that isn't a digit or a decimal point.
       This will allow people to enter dollar signs, percent signs, commas,
       and so forth, and the script will still run. The only requirement that
       the data needs to meet is that a digit needs to appear to the left of
       a decimal point (so .5 is not acceptable, 0.5 is acceptable).*/
    p = p.replace( stripper, '' );
    i = i.replace( stripper, '' );
    n = n.replace( stripper, '' );

    /* Validate user input */
    if ( p.search( pattern_p ) < 0 ) {
        message = 'The amount you entered for Principal is not valid.\n\n' +
                  'Be sure you have only a single decimal point (if any), ' +
                  'and make sure that you have at least one digit to the ' +
                  'left of the decimal point if there is one. ' +
                  '(for example: 12345.67 or 1234567)\n\n';
    }

    if ( i.search( pattern_i ) < 0 ) {
        message += ( null == message ) ? '' : '\n\n' ;
        message += 'The amount you entered for Interest is not valid.\n\n' +
                   'Be sure you have only a single decimal point (if any), ' +
                   'and make sure that you have at least one digit to the ' +
                   'left of the decimal point if there is one. ' +
                   '(for example: 4.5 or 0.5 or 2.75)\n\n';
    }

    if ( n.search( pattern_n ) < 0 ) {
        message += ( null == message ) ? '' : '\n\n' ;
        message += 'The amount you entered for Amortization is not valid.\n\n' +
                   'Be sure you have only a single decimal point (if any), ' +
                   'and make sure that you have at least one digit to the ' +
                   'left of the decimal point if there is one. ' +
                   '(for example: 25 or 0.5)\n\n';
    }

    if ( 0 == p ) {
        message += ( null == message ) ? '' : '\n' ;
        message += 'Principal can\'t be zero.\n';
    }

    if ( 0 == i ) {
        message += ( null == message ) ? '' : '\n' ;
        message += 'Interest can\'t be zero.\n';
    }

    if ( 0 == n ) {
        message += ( null == message ) ? '' : '\n' ;
        message += 'Amortization can\'t be zero.\n';
    }
    
    /* Display an alert box with all (any) error messages, 
       and halt form submission */
    if ( message != '' ) {
        alert( message );
        return false;
    }

    /* Total number of months */
    var m = n * 12;              
    
    /* Monthly interest in decimal format */
    var x = Math.pow( ( 1 + i / 200 ), ( 1 / 6 ) );
    
    /* Monthly payment */
    var pmt = p * ( ( x - 1 ) / ( 1 - Math.pow( x, -m ) ) );
    
    /* Two decimal places */
    pmt = Math.floor( pmt * 100 ) / 100;

    /* Amortization table (caption and column titles) */
    var html = '<table id="amortization_table">' +
               '<caption>Mortage Amount: $' + dollar_amount( p ) + '<br />' +
               'Monthly Payment: $' + dollar_amount( pmt ) + '<br />' +
               'Interest Rate: ' + i + '%</caption>' +
               '<tr>' +
               '<th>Payment<br />No.</th>' +
               '<th>Monthly<br />Interest</th>' +
               '<th>Monthly<br />Principal Paid</th>' +
               '<th>Total<br />Principal Paid</th>' +
               '<th>Balance</th>' +
               '</tr>';
    
    while ( p > 0.01 ) {
        /* Monthly interest, two decimal places */
        var mi = Math.floor ( p * ( x - 1 ) * 100 ) / 100; 
        
        /* Principal you pay for the month, two decimal places */
        var c = Math.floor ( ( pmt - mi ) * 100 ) / 100; 
        
        /* New principal, two decimal places */
        p = Math.floor( ( p - c ) * 100 ) / 100;

        /* Total principal paid, two decimal places */
        y = Math.floor( ( y + c ) * 100 ) / 100;
        
        /* Total cash paid out, two decimal places */
        z = Math.floor( ( z + pmt ) * 100 ) / 100;
        
        /* If principal is less than zero, make it zero */
        if ( p <= 0.01 )  p = 0;
        
        /* Decide class for row (is it shaded or not) */
        'odd' == row ? row = 'even' : row = 'odd';

        /* Amortization table (table contents) */
        html += '<tr class = "' + row + '">' +
                '<td>' + j + '</td>' +
                '<td>' + dollar_amount( mi ) + '</td>' +
                '<td>' + dollar_amount( c ) + '</td>' +
                '<td>' + dollar_amount( y )+ '</td>' +
                '<td>' + dollar_amount( p ) + '</td>' +
                '</tr>';
        if ( 0 == j%12 ) {
            a++;
            html += '<tr class = "annum"><td class = "annum" colspan = "4">' +
            'Balance remaining after Year&#160;' + a +'</td>' +
            '<td>' + dollar_amount( p ) + '</td></tr>';
        }
        j++;
    }
    html += '</table>';
    amortization_table( html );
}


////////////////////////////////////////////////////////////////////////////////
//                                                                            //
//                            amortization_table()                            //
//               Produces the amortization schedule HTML page.                //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

function amortization_table( table ) {
/* HTML-formatted output of the function:
   See amortization.html - only the amortization schedule 
   gets dropped into that code. */   
    var html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"' +
               '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' +
               '<html lang = "en" xml:lang = "en"' +
               'xmlns = "http://www.w3.org/1999/xhtml">' +
               '<head>' +
               '<style media = "screen" type = "text/css" >' +
               '@import "styles/main.css";' +
               '@import "styles/amortization.css";' +
               '</style>' +
               '<meta content = "text/html;charset=utf-8"' +
               'http-equiv = "content-type" />' +
               '<title>' +
               'The Mortgage Centre : Canada&#8217;s Lowest Mortgage Rates' +
               '</title>' +
               '</head>' +
               '<body id = "amortization">' +
               '<div id = "wrapper">' +
               '<div id = "header">' +
               '<h1 id = "logotype">' +
               'The Mortgage Centre&#8482; &#8211;' +
               '</h1>' +
               '<h2 id = "slogan">' +
               'We bring Canada&#8217;s leading lenders to you.' +
               '</h2>' +
               '<a href  = "apply_combined.html"' +
               ' title = "Go to online application page">' +
							 ' <img alt = "Authorized MCC transfer" id  = "transfer"' +
               ' src = "logos_graphics/authorized-tsf.gif" /></a>' +
							 ' <br />' +
							 '<a href = "apply_combined.html"' +
               'title = "Go to online application page">' +
               '<img alt = "Apply now!" id  = "apply_now"' +
               'src = "logos_graphics/apply.jpg" /></a>' +
               '<a href = "index.html" title = "Go to home page">' +
               '<img alt = "The Mortgage Centre home page" id  = "logo"' +
               'src = "logos_graphics/MC2005_logo_hor_2in.jpg" /></a>' +
							 '<p id="total_text">' +
							 'Total Mortgage &amp; Credit Services' +
  						 '</p>' +
							 '<p id="independent">' +
							 'An independent member of The Mortgage Centre Network' +
							 '</p>' +
               '</div>' +
               '<div id = "sidebar">' +
               '<dl id = "navigation">' +
               '<dt>' +
               '<a class = "info" href = "info.html"' +
               'title = "Go to mortgage information page">' +
               'Mortgage&#160;Information</a>' +
               '</dt>' +
               '<dd>Find information about mortgages.</dd>' +
               '<dt>' +
               '<a class = "financing" href = "financing.html"' +
               'title = "Go to financing options page">' +
               'Financing&#160;Options</a>' +
               '</dt>' +
               '<dd>Learn about financing options.</dd>' +
               '<dt>' +
               '<a class = "calculator" href = "calculator.html"' +
               'title = "Go to mortgage calculator page">' +
               'Mortgage&#160;Calculator</a>' +
               '</dt>' +
               '<dd>Run some numbers through our ' +
               'amortization calculator.</dd>' +
               '<dt>' +
               '<a class = "rates" href  = "rates.html"' +
               'title = "Go to current rates page">Current&#160;Rates</a>' +
               '</dt>' +
               '<dd>View all of the latest rates.</dd>' +
               '<dt>' +
               '<a class = "apply" href  = "apply.html"' +
               'title = "Go to online application page">Apply&#160;Now</a>' +
               '</dt>' +
               '<dd>Complete a mortgage application online. Apply now!</dd>' +
               '</dl>' +
               '<h1>Lowest rates for the past week:</h1>' + 
               '<dl id = "lowest_rates"><dt><a class = "five"' +
               'href = "rates.html" title = "Go to current rates page">' +
               'Lowest 5<br />year rate <span class = "low_rate">' + 
               five + '%</span></a></dt><dd>' +
               'Lowest rate we\'ve found for a typical five year mortgage.' +
               '</dd><dt><a class = "seven"' +
               'href = "rates.html" title = "Go to current rates page">' +
               'Lowest 7<br />year rate <span class = "low_rate">' + 
               seven + '%</span></a></dt><dd>' +
               'Lowest rate we\'ve found for a typical seven year ' +
               'mortgage.</dd><dt><a class = "ten"' +
               'href = "rates.html" title = "Go to current rates page">' +
               'Lowest 10<br />year rate <span class = "low_rate">' + 
               ten + '%</span></a></dt><dd>' +
               'Lowest rate we\'ve found for a typical ten year mortgage.' +
               '</dd></dl>' +
               '</div>' +
               '<div id = "content">' +
               '<h1>' +
               'Amortization Schedule' +
               '</h1>' +
               '<p>' +
               'Numbers in this table may not be exactly accurate because of ' +
               'rounding, so you may find that, in the end, slightly more ' +
               'balance is shown as paid than called for by the original ' +
               'mortgage.' +
               '</p>' +
               '<p>' +
               'The table shows you the balance remaining after each year. ' +
               'That&#8217;s useful if you are planning on a shorter term ' +
               'for your mortgage, and you want to know the balance ' +
               'you&#8217;ll be renegotiating.' +
               '</p>' +
               table +
               '<p class = "return_to_top">' +
               '<a href = "#amortization" ' +
               'title = "Return to top of this page">' +
               'Return to top</a>' +
               '</p>' +
               '</div>' +
               '<p id = "text_links">' +
               '<a  class = "info" href = "info.html#tmcs"' +
               'title = "Go to' +
               'mortgage information page">Mortgage&#160;Information</a> | ' +
               '<a class = "financing" href = "financing.html" ' +
               'title = "Go to ' +
               'financing options page">Financing&#160;Options</a> | ' +
               '<a class = "calculator" href = "calculator.html" ' +
               'title = "Go to ' +
               'mortgage calculator page">Mortgage&#160;Calculator</a> | ' +
               '<a class = "rates" href = "rates.html" ' +
               'title = "Go to current rates page">Current&#160;Rates</a> | ' +
               '<a class = "apply" href = "apply.html" ' +
               'title = "Go to online application page">Apply&#160;Now</a>' +
               '<br />' +
               '<a href = "info.html"' +
               'title = "Go to mortgage information page">' +
               'About Total Mortgage &#38; Credit Services</a> | ' +
               '<a href = "mailto:inquire@canadamortgageservices.com" ' +
               'title = "Send an email to Total Mortgage &#38; ' +
               'Credit Services">Contact us</a> | ' +
               '<a href = "glossary.html" title = "Go to glossary page">' +
               'Glossary</a> | ' +
               '<a href = "privacy.html" title = "Go to privacy policy page">' +
               'Privacy Policy</a>' +
               '</p>' +
               '<address>' +
               'The Mortgage Centre (Total Mortgage &#38; Credit Services):' +
               '3487 Pembina Highway, Winnipeg MB R3V 1A4, Canada' +
               '</address>' +
               '<table cellspacing = "0" id = "top_bar">' +
               '<caption>' +
               'General links relating to policy and terminology.' +
               '</caption>' +
               '<tbody>' +
               '<tr>' +
               '<th>' +
               '<a href = "info.html#tmcs"' +
               'title = "Go to mortgage information page"> ' +
               'About Total Mortgage &#38; Credit Services</a>' +
               '</th>' +
               '<td>' +
               '<a href = "mailto:inquire@canadamortgageservices.com" ' +
               'title = "Send an email to Total Mortgage &#38; ' +
               'Credit Services">Contact us</a>' +
               '</td>' +
               '<td>' +
               '<a href = "glossary.html" title = "Go to glossary page">' +
               'Glossary</a>' +
               '</td>' +
               '<td>' +
               '<a href = "privacy.html" title = "Go to privacy policy page">' +
               'Privacy Policy</a>' +
               '</td>' +
               '<!--' +
               '<td>' +
               '<a href = "faq.html" title = "Go to FAQ page">' +
               'Frequently Asked Questions (FAQ)</a>' +
               '</td>' +
							 '-->' +
							 '<tr style="color: #FFFFCC;">' +
							 '<td colspan="3">' +
							 '<!--<span style="font-size: 1.5em;">  Apply today: Effective Monday, October 29, rates will be increasing by 0.10%!</span>-->' +		 
						   '<a href  = "apply_combined.html" title = "Apply online NOW!"><span style="color: #FFFFCC; font-weight: bold; font-size: 1.50 em; text-align: center;">' +
							 ' Apply Online today &nbsp; OR &nbsp; Try our Handy Over-the-Phone Application Service:' +
							 '<span style="color: black;">&nbsp; &nbsp; 1-800-878-4431 </span></span></a>' +
							 '</td>' +
							 '</tr>' +
               '</tr>' +
               '</tbody>' +
               '</table>' +
               '</div>' +
               '</body>' +
               '</html>';
    var now = new Date();
    var n = 'amortization' + Date.parse( now );
    var w = window.open( '', n, '' );
    var d = w.document;
    d.write( html );
    d.close();
}
