﻿(function($) {
    $.fn.textareaLimit = function(options) {
        var defaultOps = { limit: 1000, remainContainer: null, textPrefix: '', textPostfix: '' };
        var combineOps = $.extend({}, defaultOps, options);
        return $(this).each(function() {
            var $this = $(this);
            var fn = function() {

                if ($this.val().length > combineOps.limit)
                    $this.val($this.val().substring(0, combineOps.limit));

                if (combineOps.remainContainer != null) {
                    var textLeft = parseInt(combineOps.limit) - $this.val().length;
                    $(combineOps.remainContainer).text(combineOps.textPrefix + textLeft.toString() + combineOps.textPostfix);
                }
            };

            $this.unbind('keyup').keyup(function() {
                fn();
            }).unbind('keydown').keydown(function() {
                fn();
            });

            fn();
        });
    };
})(jQuery);
