/**
 *
 * 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);
	 */
	
	$.fn.charCounter = function (min, max, settings) {
		max = max || 6000;
        min = min || 2500;

		settings = $.extend({
			container: "<div></div>",
			classname: "charcounter",
			format: "%1 символов (принимаются истории от 2500 до 6000)",
			pulse: true,
			delay: 0
		}, settings);
		var p;
		
		function count(el, container) {

            el = $(el);
            var len = el.val().length;
            container.html(settings.format.replace(/%1/, len));

            if(len > max)
                container.addClass('greater').removeClass('less');
            else if(len < min)
                container.removeClass('greater').addClass('less');
            else
                container.removeClass('greater').removeClass('less');
		};
		
		return this.each(function () {
			var container = $(settings.container);
                //                (!settings.container.match(/^<.+>$/)) 
                //				? $(settings.container) 
                //				: $(settings.container)
                //					.insertAfter(this)
                //					.addClass(settings.classname);

            $(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);
