/*
 * jQuery charRemain plugin
 * Version 0.0.1  (01/22/2009)
 * @requires jQuery v1.1.1+
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * No limitation for www.politics.com
 *
 */
 
/*
 * @name charRemain
 * @type jQuery
 * @cat Plugins/Forms
 * @return jQuery
 * @author Vincent Perlerin
 *
 * @credit Inspired by Brad Landis's jCounter (http://www.bradlis7.com/main/jquery-chars-remaining)
 */
 
 
/**
 * 
 * Displays a customizable counter to communicate how many characters are left for a text element with a maxLength attribute.
 * 
 * @example $("textarea[@maxlength]").charRemain();
 * @desc This displays a counter after each textarea with a maxLenght attribute. The counter has the following form: <span class="helpF'>[# of char]/[maxLength]</span>
 * The class 'max' is added to the counter when the maxLength is reached.
 *
 * @example $("textarea[@maxlength]").charRemain({
 *		tagCounter:'div', 
 *		classMax:'maximum', 
 *		defaultClass:'counter'
 *  });
 * @desc This displays a counter with the following format: <div class="counter">[# of char]/[maxLength]</div> - The class 'max' is added to the counter 
 * when the maxLength is reached. 
 *
 */
$.fn.charRemain = function(options) {

	var opts = $.extend({}, $.fn.charRemain.defaults, options);

	return this.each(function() {
		var maxL  = this.getAttribute('maxlength');
		var currentLength = $(this).val().length;
				 
		var counterElement = "<"+opts.tagCounter+" class='" + opts.defaultClass + "'>" + currentLength.toString() + "/" + maxL + " characters </"+opts.tagCounter+">";
		$(this).after(counterElement);
				 
		$(this).keyup(function() {
			currentLength = $(this).val().length;		
			if(currentLength >= maxL) {
				$(this).next("."+opts.defaultClass).addClass(opts.classMax).text(currentLength.toString() + "/" + maxL + " characters");
				$(this).val($(this).val().substring(0, maxL))
			} else {
				$(this).next(".helpF").text(currentLength.toString() + "/" + maxL + " characters");
				$(this).next("."+opts.defaultClass).removeClass(opts.classMax);
			}
		})
	})
};


$.fn.charRemain.defaults = { // Default Options
	tagCounter:'span', 
	classMax:'max', 
	defaultClass:'helpF'
};