﻿/// <reference path="./jquery.min.js" />

; (function() {
    $.fn.FormatCurrency = function() {
        return this.each(function() {
            var $this = $(this);

            var html = $.fn.FormatCurrency.GetNumber($this.val());
            var number = $.fn.FormatCurrency.GetCurrency(html, true, false, '');
            $this.val(number);
        });
    };

    $.fn.FormatCurrency.GetNumber = function(html) {
        var number = html.replace(/\D/g, '');
        return number.replace(/$/g, '');
    };

    $.fn.FormatCurrency.GetCurrency = function(num, digitalGroup, displayCents, prefix) {
        // format number
        var isPositive = (num == (num = Math.abs(num)));
        // removed to always round down 
        // num = Math.floor(num * 100 + 0.50000000001)
        num = Math.floor(num * 100);
        var cents = num % 100;
        num = Math.floor(num / 100).toString();

        if (cents < 10) cents = '0' + cents;

        if (digitalGroup == true) {
            for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
                num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
            }
        }

        if (displayCents == true) {
            num = num + '.' + cents;
        }

        // format symbol/negative
        var format = '%s%n';
        var money = format.replace(/%s/g, prefix)
        money = money.replace(/%n/g, num);

        return money;
    };
})(jQuery)
