/**
 *
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */

(function($) {
	/**
	 * attaches a character counter to each textarea element in the jQuery object
	 * usage: $("#myTextArea").charCounter(max, settings, defaultText);
	 */

	$.fn.charCounter = function (max, settings, defaultText) {
		max = max || 100;
                defaultText = defaultText || '';
		settings = $.extend({
			container: "<span></span>",
			classname: "charcounter",
			format: "(%1 characters remaining)",
			delay: 0
		}, settings);
		var p;
		var timeout = null;

		function count(el, container) {
			try {
				val = el.value;
	            if (val == defaultText) {
	                container.html(settings.format.replace(/%1/, max));
	                return;
	            }
				if (val.length > max) {
					val = val.substring(0, max);
				    el.value = val;
				}
				if (settings.delay > 0) {
					if (timeout) {
						window.clearTimeout(timeout);
					}
					timeout = window.setTimeout(function () {
						container.html(settings.format.replace(/%1/, (max - val.length)));
						timeout = null;
					}, settings.delay);
				} else {
					container.html(settings.format.replace(/%1/, (max - val.length)));
				}
			} catch(e) {
			}
		}

		return this.each(function () {
			var container = $(settings.container)
					.insertAfter(this)
					.addClass(settings.classname);
			$(this)
				.bind("change", function () { count(this, container); })
				.bind("keyup", function () { count(this, container); })
				.bind("paste", function () { count(this, container); });
				/*.bind("keydown", function () { count(this, container); })
				.bind("keypress", function () { count(this, container); })
				.bind("keyup", function () { count(this, container); })
				.bind("focus", function () { count(this, container); })
				.bind("mouseover", function () { count(this, container); })
				.bind("mouseout", function () { count(this, container); })
				.bind("paste", function () {
					var me = this;
					setTimeout(function () { count(me, container); }, 10);
				});*/
			/*if (this.addEventListener) {
				this.addEventListener('input', function () { count(this, container); }, false);
			}*/
			count(this, container);
		});
	};

})(jQuery);
