/// <reference path="jquery-1.2.6.min.js"/>

(function($) {
    $.fn.extend({

        amounts: function(options) {

            var dec = '.';

            var defaults = {
                allowDecimal: true,
                allowNegative: false,
                allowPercentage: false
            };

            var options = $.extend(defaults, options);

            return this.each(function() {

                var obj = $(this);

                obj.bind('keypress', function(evt) {
                    var val = obj.val();
                    var key = evt.which;
                    var allow = true;

                    if (key < 48 || key > 57) {
                        /* '-' only at beginning */
                        if (key == 45 && options.allowNegative == false)
                            return false;
                        else if (key == 45) {
                            if (val.startsWith('-')) {
                                obj.val(val.substring(1));
                                return false;
                            }
                            else {
                                obj.val('-' + val);
                                return false;
                            }
                        }
                        /* check for decimal and if allowed */
                        if (key == dec.charCodeAt(0) && options.allowDecimal == false)
                            allow = false;
                            
                        /* only one decimal separator allowed */
                        if (key == dec.charCodeAt(0) && val.indexOf(dec) != -1) {
                            allow = false;
                        }
                        if (key == 37 && (options.allowPercentage == false || val.indexOf('%') >= 0))
                            allow = false;
                        // check for other keys that have special purposes
                        if (
					        key != 8 /* backspace */ &&
					        key != 9 /* tab */ &&
					        key != 13 /* enter */ &&
					        key != 35 /* end */ &&
					        key != 36 /* home */ &&
					        key != 37 /* left */ &&
					        key != 39 /* right */ &&
					        key != 46 /* del */ &&
					        evt.keyCode != 9
				        ) {
                            allow = false;
                        }
                    }

                    if (allow == false) {
                        evt.preventDefault();
                    }
                });
            });
        }
    });
})(jQuery);
