﻿/*
* CharLimit - jQuery plugin for counting and limiting characters for input and textarea fields
*
* $Version: 18.11.2008
* michal.podhradsky@gmail.com
*/
(function($) {
    $.fn.charLimit = function(options) {
        var defaults = {
            limit: 30,
            speed: "normal",
            descending: true,
            targetelement: "",
            textholder: ""
        }
        var o = $.extend(defaults, options);
        return this.each(function(i) {
            var obj = $(this);
            o.textholder = $("#" + o.targetelement).text();
            if (!obj.next().hasClass("char-count"))
                $("#" + o.targetelement).html($("#" + o.targetelement).text() + " <span class='char-count box" + i + "'></span>")
            function countChars() {
                var value = (o.descending) ? o.limit - obj.val().length : obj.val().length;
                $(".box" + i).text(value + " Characters remaining");
            }
            //countChars();
            obj
				.keydown(function(e) {
				    if (obj.val().length >= o.limit && e.keyCode != "8" && e.keyCode != "9" && e.keyCode != "46")
				        e.preventDefault(); // cancel event
				    countChars();
				})
				.keyup(function(e) {
				    if (obj.val().length >= o.limit) {
				        obj.val(obj.val().substr(0, o.limit))
				    }
				    countChars();
				})
				.focus(function() {
				    $(".box" + i).fadeIn(o.speed);
				    countChars();
				})
				.blur(function() {
				    $(".box" + i).fadeOut(o.speed);
				});
        });
    }
    $(function() {
        $("textarea").charLimit({
            limit: 500, // number
            speed: "slow", // nummber or string
            descending: true, // boolean
            targetelement: "review-comments"
        });
    });
})(jQuery);


