/**
 *
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */

(function(jQuery) {
	/**
	 * attaches a character counter to each textarea element in the jQuery object
	 * usage: jQuery("#myTextArea").charCounter(max, settings);
	 */

	jQuery.fn.charCounter = function (max, settings) {
        max = max || 140;
        settings = jQuery.extend({
        container: "#usercornercounter",
            format: "%1", // (%2/%max characters used)
            pulse: true,
            delay: 0
        }, settings);
        var p, timeout;

		function update_container(el, container){
		  if(el.val() == el.attr("defaultValue")) return;
		  var cc = el.val().length //character count
		  replaced = settings.format.replace(/%1/, (max - cc)).replace(/%2/, cc).replace(/%0/, max);
		  container.html(replaced);
		};

		function count(el, container) {
			el = jQuery(el);
			if (el.val().length > max) {
			    el.val(el.val().substring(0, max));
			    if (settings.pulse && !p) {
			    	pulse(container, true);
			    };
			};
			if (settings.delay > 0) {
				if (timeout) {
					window.clearTimeout(timeout);
				}
				timeout = window.setTimeout(function () {
					update_container(el, container)
				}, settings.delay);
			} else {
					update_container(el, container)
			}
		};

		function pulse(el, again) {
			if (p) {
				window.clearTimeout(p);
				p = null;
			};
			el.animate({ opacity: 0.1 }, 100, function () {
				jQuery(this).animate({ opacity: 1.0 }, 100);
			});
			if (again) {
				p = window.setTimeout(function () { pulse(el) }, 200);
			};
		};

		return this.each(function () {
			var container = (!settings.container.match(/^<.+>$/))
				? jQuery(settings.container)
				: jQuery(settings.container)
					.insertAfter(this)
					.addClass(settings.classname);
			jQuery(this)
				.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);


