﻿// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function() {
    return this.each(function() {
        $(this).keydown(function(e) {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return (
                key == 8 || 
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};

jQuery.fn.limitMaxlength = function(options) {

    var settings = jQuery.extend({
        attribute: "maxlength",
        onLimit: function() { },
        onEdit: function() { }
    }, options);

    // Event handler to limit the textarea
    var onEdit = function(event) {
        var textarea = jQuery(this);
        var maxlength = parseInt(textarea.attr(settings.attribute));

        // prevent user from typing any more characters (inc return (13) and space (32)
        if (textarea.val().length >= maxlength) {
            if (event.which >= 48 || event.which == 13 || event.which == 32) {
                event.preventDefault();

                // Call the onlimit handler within the scope of the textarea
                jQuery.proxy(settings.onLimit, this)();
            }
            if (textarea.val().length > maxlength) {
                textarea.val(textarea.val().substr(0, maxlength)); 
            }
        }

        // Call the onEdit handler within the scope of the textarea
        jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
    }

    this.each(onEdit);

    return this.keyup(onEdit)
				.keydown(onEdit)
				.focus(onEdit);
}
