﻿// SCOTT.CSC.Tools.SavingsCalculator.Application
/// <reference path="../jquery-1.2.6-vsdoc.js"/>

Type.registerNamespace('SCOTT.CSC.Tools.SavingsCalculator');

SCOTT.CSC.Tools.SavingsCalculator.Application = function(panelId) 
{   
    var __app = this;
    this.ClientID = panelId;
    this.Selector = '#' + panelId;
    this.MonthlyPayment = 0;
    
    // inheritance (of sorts)
    SCOTT.CSC.Extend(SCOTT.CSC.Tools.SavingsCalculator.Application, SCOTT.CSC.Core);
    
    this.Initialize();
    this.Start();
};

SCOTT.CSC.Tools.SavingsCalculator.Application.prototype =
{
    __type : 'SCOTT.CSC.Tools.SavingsCalculator.Application',
    Start : function()
    {
        var __app = this;
        var context = $(this.Selector);
        
        // Reset the result field for the default value
        $('#SavingsCalculator-Deposit').text('$0.00');
        
        // Preset all input fields with base values
        $('#SavingsCalculator-Goal').val(0);
        $('#SavingsCalculator-Base').val(0);
        $('#SavingsCalculator-Rate').val('0.0');
        $('#SavingsCalculator-Months').val(0);
        $('#SavingsCalculator-Years').val(0);
        
        // Setup all fields to default values on blur if the user clears the field. Note
        // that the default for the rate is a float to help the user with input.
        $('.FormItem input[type=text]').blur(function() {
            if (this.value.length == 0) {
                if (this.id.indexOf("Rate") != -1) {
                    this.value = "0.0";
                } else {
                    this.value = "0";
                }
            }
        });
    },
    AttachEvents : function()
    {
        var __app = this;
        var context = $(this.Selector);
        
        $('#SavingsCalculator-Calculate').click(function()
        {
            __app.Calculate();
            __app.DisplayResults();
        });
        
        // Setup basic input character restrictions to help the user
        $('input.Percentage', __app.Selector).restrict("percentage", { tooltip: "Please enter a decimal value." });
        $('input.Currency',   __app.Selector).restrict("float", { tooltip: "Please enter a decimal value." });
        $('input.Months, input.Years',  __app.Selector).restrict("integer", { tooltip: "Please enter an integer value." });
    },
    Calculate : function()
    {
        var __app = this;
        var context = $(this.Selector);
	
	    var deposit = 0;
	    var goal    = parseFloat($('#SavingsCalculator-Goal').val());
	    var base    = parseFloat($('#SavingsCalculator-Base').val());
	    var months  = Math.round(parseInt($('#SavingsCalculator-Years').val())) * 12 + Math.round(parseInt($('#SavingsCalculator-Months').val()));
	    var rate    = parseFloat($('#SavingsCalculator-Rate').val()) * 0.01;
	    
	    if (months > 0)
	    {
	        if (rate == 0) 
	        {
		        deposit = (goal - base) / months;
	        } 
	        else 
	        {
		        var mrate = rate / 12;
		        var lrate = 1 + mrate;
		        var p1    = Math.pow(lrate, months);
		        var av    = base * p1;
		        var avad  = (p1 - 1) / (mrate * (1 / lrate));
		        deposit   = (goal - av) / avad;
	        }
	    }
	    
	    __app.MonthlyPayment = deposit;
    },
    DisplayResults : function()
    {
        var __app = this;
        var context = $(this.Selector);
        
        var pmt  = __app.MonthlyPayment;
        var nums = pmt.toString().split('.');
        var real = nums[0];
        var frac = nums[1];
        
        // We need to format the real portion of the result using commas to
        // separate the thousands. We will step across the length and drop
        // commas in after every group of three numbers using an incrementing
        // offset that starts at the first appropriate group from the left
        var offset = real.length % 3;
        var format = real.substr(0, offset);
        while (offset < real.length)
        {
            // If we have a string length divisble by three then we
            // should skip appending the first comma
            if (offset > 0) {
                format += ',';
            }
            
            // Add the next grouping of three numbers and increment the
            // offset to the next thousands grouping
            format += real.substr(offset, 3);
            offset += 3;
        }
        
        if (frac == undefined) {
            frac = "00";
        } else {
            while (frac.length < 2) {
                frac = "0" + frac;
            }
            frac = frac.substr(0, 2);
        }
        format += "." + frac;
        
        $('#SavingsCalculator-Deposit').fadeOut(1, function() {
            $(this).text('$' + format).fadeIn(1000);
        });
    }
};
