﻿/*******************************************************************************
TITLE: 			Character Count Plugin
	
AUTHORS:		Shaun Crittenden (original code) & Nathan Koch (plugin-ization)
	
VERSION:		1.0
	
REQUIRES:		jQuery v1.3.2
	
EXPECTS:		
	
OPTIONS:		
					
CALLBACKS: 		
					
DESCRIPTION:	
	
*******************************************************************************/

(function($) {
    $.fn.extend({
        characterCount: function(options) {
            // DEFAULTS
            var defaults = {
				charLimit: 500,
				charLimitClass: "word-count",
				charLimitText: "(%LIMIT% characters remaining)",
				charExceededText: ("(character limit exceeded by %OVER% )"),
				errorClass: "exceeded-limit"
            };
            var options = $.extend(defaults, options);
            return this.each(function() {

                // VARIABLES
				var current = 0;
				var remaining;
				var over;
				
				$this = $(this);
				$counter = $('<p class="%CLASS%" />'.replace("%CLASS%", options.charLimitClass))
								.insertAfter($this)
								.text(options.charLimitText.replace("%LIMIT%", options.charLimit));
								
				// FUNCTIONS
				updateCharacterLimit = function(remainingNum) {
					$counter.removeClass(options.errorClass);
					$counter.text(options.charLimitText.replace("%LIMIT%", remainingNum));	
				};
				
				updateLimitExceeded = function(overNum) {
					$counter.addClass(options.errorClass);
					$counter.text(options.charExceededText.replace("%OVER%", overNum));
				};
				
                // EVENT LISTENERS
				$this.keypress( function(event) {
			        current = $(this).val().length;
					remaining = options.charLimit - current;
			        if (remaining >= 0) {
			            updateCharacterLimit(remaining);
			        } else {
			            over = current - options.charLimit;
						updateLimitExceeded(over);
			        }
			    });
            });
        }
    });
})(jQuery);