﻿//
// Common API for widgets
//

// Gloabls
//var sessionId = '';
var ip = '<!--#echo var="REMOTE_ADDR"-->';
var scriptCount = 0;
// API Utilities
var API = function() {

    // validate/// <reference path="../Mortgage/Standard/" />
    // data: json data {AffiliateId: '8730529D-E0D1-4fa2-A856-C573269EE9F7', Application: 'calculators', Service: 'mortgage', Type: 'standardloan', Branding: 'N/A'}
    function validate(data) {
        jQuery.ajax({
            type: 'GET',
            contentType: "application/json; charset=utf-8",
            dataType: 'jsonp',
            data: Json2.stringify(data, null),
            url: "http://api.hudclips.org/services/affiliate/",
            cache: false
        });
    }
    // initialize
    // service: jason data {ReturnCode: 'OK', Disclaimer: 'NA', Application: 'calulators', Service: 'mortgage', Type: 'StandardLoan', 
    //
    function init(response) {

        // Set up Containers
        var html = "";
        html += '<div id="widgetContent">';
        html += '<div id="widgetHeader">Loading...</div>';
        html += '<div id="widgetContainer"></div>';
        html += '<div id="widgetStep"></div>';
        html += '<div id="widgetCallToAction"></div>';
        html += '<div id="widgetFootNote"></div>';
        html += '</div>';
        jQuery("#widget").prepend(html);
        if (typeof (hideSignUp) === 'undefined') {
            // Handle the legacy calculator
            if (ServiceType === 'standardloan') {
                ServiceType = 'standard-loan';
            }
            jQuery("#branding").prepend('<a id="addThisWidget" href="http://api.hudclips.org/register/' + Service + '-calculator/' + ServiceType + '/" target="_blank" title="Mortgage Calculator">Get this calculator for your site</a>');
        }
        jQuery("#widgetContent").append('<div id="disclaimer"></div>');
        if (response.ReturnCode === 'OK') {
            jQuery("#disclaimer").html(response.Disclaimer);
            // Load the Application Service
            loadscriptfile("http://api.hudclips.org/services/calculators/" + response.Service + "/" + response.Type + "/stdform.js", "js");
            //sessionId = generateGuid();
        }
        else {

            jQuery("#widgetHeader").html('Access Denied');
            jQuery("#widgetContainer").html('Access Denied:' + response.ReturnCode);
        }
    }

    // Used to paint custom widget
    function paint() {

        // Check for Custom Colors and adjust style sheet rules
        if (typeof (customColor) !== 'undefined') {

            // Set foreground
            jQuery('.btn-24 a').css('color', customColor.secondary);
            jQuery('.tab-24 a').css('color', customColor.secondary);
            jQuery('#disclaimer').css('color', customColor.secondary);
            jQuery('#widgetHeader').css('color', customColor.secondary);

            // set background
            jQuery('.btn-24').css('background-color', customColor.primary);
            jQuery('.tab-24').css('background-color', customColor.primary);
            jQuery('#disclaimer').css('background-color', customColor.primary);
            jQuery('#widgetHeader').css('background-color', customColor.primary);
            jQuery('#widgetContent').css('border-color', customColor.primary);
            jQuery('.tabs-container').css('border-color', customColor.primary);
            // Adjust Branding  - MAKE AUTOMATIC
            var bgColor = jQuery('body').css('background-color');
            if (/chrome/.test(navigator.userAgent.toLowerCase())) {
                bgColor = RGB2Hex(bgColor)
            }
            var fgColor = adjustColour(bgColor);
            // Clear Backgound Color for custom color schema
            jQuery('#branding').css('background-color', 'transparent');
            // Determin Color
            jQuery('#branding').css('color', fgColor);
            jQuery('#branding a').css('color', fgColor);

           
        }
        jQuery("#widget").css('display', 'inline');
    }
    function RGB2Hex(str) {
        var rgb = str.match(/\d+/g);

        return "#" + hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
    }
    //generates the hex-digits for a colour.
    function hex(d) {
        hexDigits = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F");
        return (d = isNaN) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
    }


    function adjustColour(hexString) {

        if (hexString === 'transparent') {
            hexString = '#FFFFFF';
        }
        var triplet = [];
        triplet[0] = parseInt(HexToR(hexString));
        triplet[1] = parseInt(HexToG(hexString));
        triplet[2] = parseInt(HexToB(hexString));


        var newtriplet = [];    //black or white:   
        var total = 0;
        for (var i = 0; i < triplet.length; i++) {
            total += triplet[i];
        }
        if (total > (3 * 256 / 2)) {
            newtriplet = [0, 0, 0];
        }
        else {
            newtriplet = [255, 255, 255];
        }
        var newstring = "rgb(" + newtriplet.join(",") + ")";

        return newstring;
    }
    function HexToR(h) { return parseInt((cutHex(h)).substring(0, 2), 16) }
    function HexToG(h) { return parseInt((cutHex(h)).substring(2, 4), 16) }
    function HexToB(h) { return parseInt((cutHex(h)).substring(4, 6), 16) }
    function cutHex(h) { return (h.charAt(0) == "#") ? h.substring(1, 7) : h }


    // MOVE TO UTILITY
    // Dynamiclly Load CSS, Scripts, and Html
    function loadscriptfile(uri, uriType, id) {
        if (uriType == "js") { //if filename is a external JavaScript file
            var fileref = document.createElement('script')
            fileref.setAttribute("type", "text/javascript")
            fileref.setAttribute("src", uri)
            scriptCount = scriptCount + 1;
            if (fileref.readyState) {  //IE
                fileref.onreadystatechange = function() {
                    if (fileref.readyState == "loaded" || fileref.readyState == "complete") {
                        fileref.onreadystatechange = null;
                        scriptCount = scriptCount - 1;
                    }
                };
            }
            else {  // Firefox, Safari, Chrome, and Opera
                fileref.onload = function() {
                    scriptCount = scriptCount - 1;
                };
            }

        }
        else if (uriType == "css") { //if filename is an external CSS file
            var fileref = document.createElement("link")
            fileref.setAttribute("rel", "stylesheet")
            fileref.setAttribute("type", "text/css")
            fileref.setAttribute("href", uri)
        }

        if (typeof fileref != "undefined") {
            document.getElementsByTagName("head")[0].appendChild(fileref)
        }
    }
    //
    // Set Loan Data Cookie TODO: Add a hook to call a custom function to save data to client (DONE)
    //
    function set_cookie(name, value, exp_y, exp_m, exp_d, path, domain, secure) {
        var cookie_string = name + "=" + escape(value);

        if (exp_y) {
            var expires = new Date(exp_y, exp_m, exp_d);
            cookie_string += "; expires=" + expires.toGMTString();
        }

        if (path) {
            cookie_string += "; path=" + escape(path);
        }
        if (domain) {
            cookie_string += "; domain=" + escape(domain);
        }
        if (secure) {
            cookie_string += "; secure";
        }
        document.cookie = cookie_string;

        if (typeof (dataSaveFunction) === 'function') {
            dataSaveFunction(value);
        }

    }

    //
    // Get Loan Data Cookie
    //
    function get_cookie(cookie_name) {
        var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');

        if (results) {
            if (typeof (dataFetchFunction) === 'function') {
                return dataFetchFunction();
            }

            return (unescape(results[2]));
        }
        else {
            return null;
        }
    }

    //    function generateGuid() {
    //        var result, i, j;
    //        result = '';
    //        for (j = 0; j < 32; j++) {
    //            if (j == 8 || j == 12 || j == 16 || j == 20)
    //                result = result + '-';
    //            i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
    //            result = result + i;
    //        }
    //        return result
    //    } 

    //
    // Single-Loan Data Entry Form
    //
    function renderLoanForm() {
        var html = '<div id="calcForm">';
        html += '<span id="formError"></span>';
        html += '<table id="widgetForm">';
        html += '<tbody>';
        html += '<tr>';
        html += '<td width="100%">Purchase Price</td>';
        html += '<td class="input">$<input id="form_purchasePrice" value="169000" size="8" name="purchasePrice"></td></tr>';
        html += '<tr>';
        html += '<td>Down Payment</td>';
        html += '<td class="input">$<input id="form_downPayment" value="20000" size="8" name="downPayment"></td></tr>';
        html += '<tr>';
        html += '<td>Mortgage Term: (years)</td>';
        html += '<td class="input">(1-40) <input id="form_termyears" value="30" size=8 name="termyears"></td></tr>';
        html += '<tr>';
        html += '<td>Interest Rate</td>';
        html += '<td class="input">%<input id="form_interestrate" value="5.000" size=8 name="interestrate"></td></tr>';
        html += '<tr>';
        html += '<td>Property Tax: (per year)</td>';
        html += '<td class="input">$<input id="form_propertyTax" value="1600" size=8 name="propertyTax"></td></tr>';
        html += '<tr>';
        html += '<td>Property Insurance: (per year)</td>';
        html += '<td class="input">$<input id="form_propertyInsurance" value="400" size=8 name="propertyInsurance"></td></tr>';
        //        html += '<tr>';
        //        html += '<td>PMI: (per month)</td>';
        //        html += '<td class="input">$<input id="form_PMI" value=0 size=8 name="PMI"></td></tr>';
        //        html += '<tr class=end>';
        //        html += '<td>desired table display <br><em>system always assumes monthly compounding.</em></td>';
        //        html += '<td><select id=form_amortization name=amortization><option value=1>monthly</option><option selected value=2>yearly</option></select></td></tr>';
        html += '</tbody></table>';
        html += '</div>';
        return (html);
    }

    //
    // Multi-Loan Data Entry Form
    //
    //    function renderForm() {
    //        var html = "<div id='form-1'>";
    //        //html += "<span id=\"formError\"></span>";
    //        html += "<table id=\"widgetForm\">";
    //        html += "<thead>";
    //        html += "<tr>";
    //        html += "<th>";
    //        html += "Loan Name";
    //        html += "</th>";
    //        html += "<th>";
    //        html += "Principal";
    //        html += "</th>";
    //        html += "<th>";
    //        html += "Interest Rate";
    //        html += "</th>";
    //        html += "<th>";
    //        html += "Term (Months)";
    //        html += "</th>";
    //        html += "<th>";
    //        html += "&nbsp;";
    //        html += "</th>";
    //        html += "</tr>";
    //        html += "</thead>";
    //        html += "<tbody>";
    //        html += "<tr>";
    //        html += "<td>";
    //        html += "<input type=\"text\" class=\"field[LoanName]\" style=\"width: 250px;\" />";
    //        html += "</td>";
    //        html += "<td>";
    //        html += "<input type=\"text\" class=\"field[LoanAmount]\" style=\"width: 120px;\" />";
    //        html += "</td>";
    //        html += "<td>";
    //        html += "<input type=\"text\" class=\"field[InterestRate]\" style=\"width: 90px;\" />";
    //        html += "</td>";
    //        html += "<td>";
    //        html += "<input type=\"text\" class=\"field[LoanTerm]\" style=\"width: 90px;\" />";
    //        html += "</td>";
    //        html += "<td>";
    //        html += "<span class=\"field[delete] cmdDelete\">&nbsp;</span>";
    //        html += "</td>";
    //        html += "</tr>";
    //        html += "</tbody>";
    //        html += "<tfoot id=\"formFooter\">";
    //        html += "</tfoot>";
    //        html += "</table>";
    //        html += "<div class=\"buttonwrapper\"><a href=\"#\" class=\"ovalbutton\"><span id=\"add\">Add Loan</span></a></div>";
    //        html += "</div>";

    //        return (html);
    //    }

    // Amortization Schedule - Displays Every 12 Months Periods
    // ----------------------------------------------------------------------------------------------------------------------------
    function paymentSchedule(context, results, title) {

        // Details
        var table = '<div><table id="amortization"><thead><tr><th>Year</th><th>Monthly Payment</th><th>Balance</th><th>Interest Paid</th><th>Principal Paid</th></thead><tbody>';
        var yearPrinciple = 0;
        var yearInterest = 0;
        var monthlyPayment = 0;
        var payments = results.PaymentSchedule;

        if (payments.lenght < 1) {
            return
        }

        if (title === undefined) {
            var title = "Payment Schedule";
        }
        var html = "";
        html += title + ' - ' + results.LoanName;
        html += "";
        for (var i = 0; i < results.PaymentSchedule.length; i++) {
            // Accumulate Principal and Interest
            if (payments[i].Period !== undefined) {
                yearPrinciple = yearPrinciple + payments[i].PrincipalPaid;
                yearInterest = yearInterest + payments[i].InterestPaid;
                if ((payments[i].Period % 12) === 0) {
                    var _year = Math.abs(payments[i].Period / 12);
                    var _row = '<tr>';
                    if ((_year % 2) === 0) {
                        _row = '<tr class="altRow">'
                    }
                    monthlyPayment = payments[i].Payment + (results.PropertyInsurance / 12) + (results.PropertyTax / 12) + (results.PMI)
                    _row += '<td>' + _year + '</td>';
                    _row += '<td>' + monthlyPayment.toFixed(2) + '</td>';
                    _row += '<td>' + payments[i].Balance.toFixed(2) + '</td>';
                    _row += '<td>' + yearInterest.toFixed(3) + '</td>';
                    _row += '<td>' + yearPrinciple.toFixed(2) + '</td></tr>';
                    table += _row;
                }
            }
        }
        table += '</tbody></table></div>';
        html += table;
        jQuery(context).html(html);

    }

    // Create XML for Chart
    function parseAmortization(results) {

        var totalPrincipal = 0;
        var totalInterest = 0;
        // Graph
        var xmlData = '<graph caption="Mortgage - ' + results.LoanName + '" subcaption="Amortization" xAxisName="Year" divlinecolor="F47E00" decimalPrecision="0" yAxisMinValue="0" yAxisMaxValue="200000" numDivLines="10" showAreaBorder="1" areaBorderColor="000000" numberPrefix="$" showNames="1" numVDivLines="5" vDivLineAlpha="30" formatNumberScale="1" rotateNames="1">';

        // Create Categories
        var xmlCategoriesData = '<categories>';
        var xmlPaymentData = '<dataset seriesname="Balance" color="00B0D8" showValues="0" areaAlpha="50" showAreaBorder="1" areaBorderThickness="2" areaBorderColor="FF0000">';
        var xmlInterestData = '<dataset seriesname="Interest" color="FF3333" showValues="0" areaAlpha="50" showAreaBorder="1" areaBorderThickness="2" areaBorderColor="FF0000">';
        var xmlPrincipalData = '<dataset seriesname="Principal" color="FFEB33" showValues="0" areaAlpha="50" showAreaBorder="1" areaBorderThickness="2" areaBorderColor="FF0000">';
        //var xmlTaxData = '<dataset seriesname="Property Tax" color="99FF33" showValues="0" areaAlpha="50" showAreaBorder="1" areaBorderThickness="2" areaBorderColor="FF0000">';
        //var xmlInsuranceData = '<dataset seriesname="Property Insurance" color="FF5904" showValues="0" areaAlpha="50" showAreaBorder="1" areaBorderThickness="2" areaBorderColor="FF0000">';

        for (var i = 0; i < results.PaymentSchedule.length; i++) {
            totalPrincipal += results.PaymentSchedule[i].PrincipalPaid;
            totalInterest += results.PaymentSchedule[i].InterestPaid;

            // 2 years
            if ((results.PaymentSchedule[i].Period % 24) === 0) {

                xmlCategoriesData += '<category name="' + (results.PaymentSchedule[i].Period / 12) + '" />';
                xmlPaymentData += '<set value="' + (results.LoanAmount - totalPrincipal) + '" />';
                xmlInterestData += '<set value="' + totalInterest + '" />';
                xmlPrincipalData += '<set value="' + totalPrincipal + '" />';
                //xmlTaxData += '<set value="' + (results.PropertyTax) + '" />';
                //xmlInsuranceData += '<set value="' + (results.PropertyInsurance) + '" />';
            }

        }
        xmlCategoriesData += '</categories>'
        xmlPaymentData += '</dataset>';
        xmlInterestData += '</dataset>';
        xmlPrincipalData += '</dataset>';
        //xmlTaxData += '</dataset>';
        //xmlInsuranceData += '</dataset>';
        return xmlData + xmlCategoriesData + xmlPaymentData + xmlInterestData + xmlPrincipalData + '</graph>';

        //return(xmlData);
    }

    function parsePayment(results) {
        // Pie
        var xmlData = '<graph caption="Monthly Payment Break Out - ' + results.LoanName + '" decimalPrecision="2" showPercentageValues="1" showNames="1" numberPrefix="$" showValues="1" showPercentageInLabel="1" pieRadius="80" pieBorderAlpha="90" animation="1" shadowXShift="4" shadowYShift="4" shadowAlpha="40" pieFillAlpha="75" pieBorderColor="CCCCCC">';
        // Data Set
        xmlData += '<set value="' + results.PaymentAmount + '" name="Mortgage" color="F3C846"/>';
        xmlData += '<set value="' + results.PropertyTax / 12 + '" name="Tax" color="7BB0C7"/>';
        xmlData += '<set value="' + results.PropertyInsurance / 12 + '" name="Insurance" color="E38D68"/>';
        //xmlData += '<set value="65" name="PMI" color="A66EDD"/>';
        xmlData += '</graph>';
        return xmlData;
    }

    function parseMortgage(results) {
        // Pie 
        var xmlData = '<graph caption="Mortgage Break Out - ' + results.LoanName + '" decimalPrecision="2" showPercentageValues="1" showNames="1" numberPrefix="$" showValues="1" showPercentageInLabel="1" pieRadius="80" pieBorderAlpha="90" animation="1" shadowXShift="4" shadowYShift="4" shadowAlpha="40" pieFillAlpha="75" pieBorderColor="CCCCCC">';
        // Data Set
        xmlData += '<set value="' + results.LoanAmount + '" name="Principal" color="F3C846"/>';
        xmlData += '<set value="' + results.TotalInterestPaid + '" name="Interest" color="47BF80"/>';
        xmlData += '<set value="' + results.PropertyInsurance * (results.LoanTerm / 12) + '" name="Insurance" color="E38D68"/>';
        xmlData += '<set value="' + results.PropertyTax * (results.LoanTerm / 12) + '" name="Tax" color="7BB0C7"/>';
        //xmlData += '<set value="65" name="results.PMI" color="A66EDD"/>';
        xmlData += '</graph>';
        return xmlData;
    }



    function currency(v, decimals, symbol) {
        if (decimals == null)
            decimals = 2;
        if (symbol == null)
            symbol = '$'
        var r = fixed(v, decimals, false);
        if (v >= 0)
            return symbol + r;
        return '-' + symbol + r.slice(1);
    }

    function fixed(v, decimals, noCommas) {
        if (decimals == null) decimals = 2;
        var x = Math.pow(10, decimals);
        var s = String(Math.round(N(v) * x) / x);
        var p = s.indexOf('.');
        if (p < 0) {
            p = s.length;
            s += '.';
        }
        for (var i = s.length - p - 1; i < decimals; i++)
            s += '0';
        if (noCommas == true) // Treats null as false.
            return s;
        var arr = s.replace('-', '').split('.');
        var result = [];
        var first = true;
        while (arr[0].length > 0) { // LHS of decimal point.
            if (!first)
                result.unshift(',');
            result.unshift(arr[0].slice(-3));
            arr[0] = arr[0].slice(0, -3);
            first = false;
        }
        if (decimals > 0) {
            result.push('.');
            var first = true;
            while (arr[1].length > 0) { // RHS of decimal point.
                if (!first)
                    result.push(',');
                result.push(arr[1].slice(0, 3));
                arr[1] = arr[1].slice(3);
                first = false;
            }
        }
        if (v < 0)
            return '-' + result.join('');
        return result.join('');
    }
    function N(v) {
        var RE_N = /[\$,\s]/g;
        if (v == null) return 0;
        if (v instanceof Date) return v.getTime();
        if (typeof (v) == 'object') v = v.toString();
        if (typeof (v) == 'string') v = parseFloat(v.replace(RE_N, ''));
        if (isNaN(v)) return 0;
        if (typeof (v) == 'number') return v;
        if (v == true) return 1;
        return 0;
    }


    return {
        Initilize: init,
        Validate: validate,
        Paint: paint,
        LoadScript: loadscriptfile,
        GetCookie: get_cookie,
        SetCookie: set_cookie,
        //GenerateId: generateGuid,
        RenderLoanForm: renderLoanForm,
        //RenderForm: renderForm,
        PaymentSchedule: paymentSchedule,
        Currency: currency,
        Fixed: fixed,
        ParseAmortization: parseAmortization,
        ParsePayment: parsePayment,
        ParseMortgage: parseMortgage

    }

} ();

if (typeof jQuery == 'undefined') {
    API.LoadScript("http://api.hudclips.org/services/scripts/jquery-1.3.1.js", "js");

    var waitForLoad = setInterval(function() {
        if (scriptCount < 1) {
            clearInterval(waitForLoad);
            API.LoadScript("http://api.hudclips.org/services/calculators/styles/master.css", "css");
            API.LoadScript("http://api.hudclips.org/services/scripts/json2.js", "js");
            API.LoadScript("http://api.hudclips.org/services/scripts/jQuery.tabs.js", "js");
            API.LoadScript("http://api.hudclips.org/services/scripts/fusioncharts.js", "js");
        }
    }, 50);
}
else {
    API.LoadScript("http://api.hudclips.org/services/calculators/styles/master.css", "css");
    API.LoadScript("http://api.hudclips.org/services/scripts/json2.js", "js");
    API.LoadScript("http://api.hudclips.org/services/scripts/jQuery.tabs.js", "js");
    API.LoadScript("http://api.hudclips.org/services/scripts/fusioncharts.js", "js");
}
// wait for scripts to load
var timerId = setInterval(function(){

	if ( scriptCount < 1 ) {
		clearInterval( timerId );
        var brandingStr = jQuery('#branding').html();
		API.Validate({AffiliateId: affiliateId, Application: 'calculator', Service: Service, Type: ServiceType, Branding: brandingStr});
	}
}, 50);
