(function($)
{
	jQuery.maxlength =
	{
		defaults: {
			maxlength: 255,
			show_counter_box: true,
			counter_box_class: "maxlength_counter",
			warning_length: 10,
			warning_class: "maxlength_counter_warning",
			full_class: "maxlength_counter_full"
		}
	};

	$.fn.maxlength = function(userOptions)
	{
		var options = $.extend({}, $.maxlength.defaults, userOptions);

		$(this).each(function()
		{
			var name = $(this).attr('name');
		
			if (options.show_counter_box)
			{
				$(this).before('<input type="text" readonly="readonly" ' +
					'name="counter_' + name + '" ' +
					'value="' + options.maxlength + '" ' +
					'class="' + options.counter_box_class + '"/>');
			}

			$(this).bind("change keyup", function()
			{
				var oldVal = $(this).val();
				var newVals = oldVal.split("\n");

				var i = 0;
				var newVal = "";
				var currentLength = 0;
				while (i < newVals.length && currentLength + newVals[i].length + 1 < options.maxlength)
				{
					if (newVal != "")
					{
						newVal += "\n";
						currentLength++;
					}
					newVal += newVals[i];
					currentLength += newVals[i].length;
					i++;
				}

				if (i < newVals.length)
				{
					if (newVal != "")
					{
						newVal += "\n";
						currentLength++;
					}

					newVal += newVals[i].substr(0, options.maxlength - currentLength);
					currentLength = options.maxlength;
				}

				if (newVal != oldVal) {
					$(this).val(newVal);
				}

				var charLeft = options.maxlength - currentLength;
				if (options.show_counter_box)
				{
					var counter_box = $('input[name="counter_'+name+'"]', $(this).parent());
					counter_box.val(charLeft);

					if (charLeft == 0)
						$(counter_box).removeClass(options.warning_class).addClass(options.full_class);
					else if (charLeft <= options.warning_length)
						$(counter_box).removeClass(options.full_class).addClass(options.warning_class);
					else
						$(counter_box).removeClass(options.full_class).removeClass(options.warning_class);
				}
			});

			$(this).change();
		});
	}

})(jQuery);
