/**
 * Count Characters Plugin
 * Count the number of characters used and display
 * number of characters left
 * 
 * Version 1.0
 * Updated 05/06/2009
 *
 * Copyright (c) 2009 Ryan Brill (solutionset.com)
 *
 * Usage: $(object).countChars([number]);
 * 
 * Example: $(".countdown").countChars(100); Countdown from 100 characters
 * 
 */

(function($){
	$.fn.countChars = function(oConfig){
		var config = {
			limit: 1000,
			descending: true,
			preventOver: false,
			countUpMessage: "You have used {{chars}} characters",
			underLimitMessage: "You have {{chars}} characters remaining",
			overLimitMessage: "You are {{chars}} characters over the number of allowed characters"
		}
		var config = $.extend(config,oConfig);
		
		return this.each(function(i) {
			var obj = $(this);
			var message = (config.descending) ? config.underLimitMessage.replace("{{chars}}", '<span></span>') : config.countUpMessage.replace("{{chars}}", '<span></span>');
			obj.after('<p class="countChars counter'+ i +'">' + message + '</p>');
			
			function countChars(){
				var value = (config.descending) ? config.limit - obj.val().length : obj.val().length;
				if (obj.val().length > config.limit) {
					value *= -1;
					var message = config.overLimitMessage.replace("{{chars}}", '<span></span>');
					$(".counter"+i).addClass("overLimit").html(message);
				} else {
					var message = (config.descending) ? config.underLimitMessage.replace("{{chars}}", '<span></span>') : config.countUpMessage.replace("{{chars}}", '<span></span>');
					$(".counter"+i).removeClass("overLimit").html(message);
				}
				$(".counter"+i+" span").text(value);
			}
			countChars();
			
			obj
				.keydown(function(e){
					if(config.preventOver && obj.val().length >= config.limit && e.keyCode != "8" && e.keyCode != "9" && e.keyCode != "46") {
						e.preventDefault(); // cancel event
					}
					countChars();
				})
				.keyup(function(e){
					if(config.preventOver && obj.val().length >= config.limit){
						obj.val(obj.val().substr(0,config.limit))
					}
					countChars();
				})
				.change(function(e){
					if(config.preventOver && obj.val().length >= config.limit){
						obj.val(obj.val().substr(0,config.limit))
					}
					countChars();
				});
		});
	}
})(jQuery);