﻿(function ($) {
    $.fn.maxChar = function (limit, options) {

        var target = this;
        if (target.length == 0)
            return;

        options = jQuery.extend(
        {
            indicator: null,
            indicatorType: 'remaining'
        }, options);

        initialize();
        updateIndicator();

        function initialize() {

            if ($(target).attr('tagName').toUpperCase() != 'TEXTAREA')
                return;

            $(target).keyup(function (e) {
                updateIndicator();
            });

            $(target).keypress(function (e) {
                if ($(target).val().length >= limit) {
                    if (e.which != 0 && e.which != 8)
                        return false;
                }

                return true;
            });
        }

        function updateIndicator() {
            if (options.indicator != null) {
                if (options.indicatorType == 'current') {
                    $(options.indicator).text(
                        $(target).val().length);
                } else {
                    $(options.indicator).text(
                        limit - $(target).val().length);
                }
            }
        }
    };
})(jQuery);
