﻿(function($) {

    $.fn.numericinput = function(settings) {
        var config = { integersonly: false, decimalplaces: 2, thousandsdelimiter: ',', decimaldelimiter: '.', oninvalidkey: null };
        var controlKeys = [8, 9, 13, 27, 35, 36, 37, 39];

        if (settings) $.extend(config, settings);
        this.each(function() {
            $(this).keypress(function(event) {
                // We don't support the del key in Opera because del == . == 46.
                // IE doesn't support indexOf
                var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
                // Some browsers just don't raise events for control keys. Easy.
                // e.g. Safari backspace.
                if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
                          (49 <= event.which && event.which <= 57) || // Always 1 through 9
                          (!config.integersonly && event.which == 46) ||
                          (48 == event.which && $(this).attr("value")) || // No 0 first digit
                          isControlKey) { // Opera assigns values for control keys.
                    return;
                } else {
                    if (config.oninvalidkey != null) {
                        config.oninvalidkey();
                    }
                    event.preventDefault();
                }
            });

            $(this).bind((($.browser.msie) ? 'focusout' : 'blur'), function() {
                var test = parseFloat($(this).val());
                if (isNaN(test)) {
                    if (config.oninvalidkey != null) {
                        config.oninvalidkey();
                    } else {
                        $(this).val('')
                    }
                } else {
                    if (test.toFixed) {
                        $(this).val(test.toFixed(config.decimalplaces));
                    }
                }
            });
        });
        return this;
    };
})(jQuery);
