/**
 * Adds a character counter to each textarea element in the jQuery object.
 * 
 * The character counter output will be formatted as followed:
 * currentCount/limit
 * 
 * If the passed limit should be null, 0 or an empty string, there won't be any limitation.
 * The character counter output then only display the currentCount.
 * 
 * Usage: $("#myTextarea").charCounter(100, "#myTextareaCounter");
 * 
 * You can also unbinds the used events by calling charCounterUnbind,
 * but be CAREFULLY, it deletes ALL binded functions from those events!
 * 
 * @author D. Pacassi Torrico
 * @version 20100114
 */
(function($) {
	$.fn.charCounter = function (limit, counterElement) {
		counterElement = $(counterElement);
		
		function count(elem) {
			elem = $(elem);
			
			if (limit === null || limit == 0 || limit == "") {
				counterElement.html(elem.val().length);
			} else {
				if (elem.val().length > limit) {
					elem.val(elem.val().substring(0, limit));
				}
				
				counterElement.html(elem.val().length + "/" + limit);
			}
		}
		
		$(this).bind("charCounterUnbind", function () {
			$(this)
				.unbind("keydown")
				.unbind("keypress")
				.unbind("keyup")
				.unbind("focus")
				.unbind("mouseover")
				.unbind("mouseout")
				.unbind("paste");
			counterElement.html("");
		});
		
		return this.each(function () {
			$(this)
				.bind("keydown", function () { count(this); } )
				.bind("keypress", function () { count(this); } )
				.bind("keyup", function () { count(this); } )
				.bind("focus", function () { count(this); } )
				.bind("mouseover", function () { count(this); } )
				.bind("mouseout", function () { count(this); } )
				.bind("paste", function () {
					var me = this;
					setTimeout(function() { count(me); }, 10);
				});
			count(this);
		});
	};
	
	$.fn.charCounterUnbind = function () {
		return this.trigger("charCounterUnbind");
	};
})(jQuery);

