/**
 * jQuery Maxlength plugin
 * @version		$Id: jquery.maxlength.js 18 2009-05-16 15:37:08Z emil@anon-design.se $
 * @package		jQuery maxlength 1.0.5
 * @copyright	Copyright (C) 2009 Emil Stjerneman / http://www.anon-design.se
 * @license		GNU/GPL, see LICENSE.txt
 */

(function($) {

	$.fn.maxlength = function(options) {
		var settings = jQuery.extend({
			events:				      [], // Array of events to be triggerd
			maxCharacters:		  10, // Characters limit
			status:				      true, // True to show status indicator
			statusElement:      "", // Status element
			statusClass:		    "", // The class on the status element
			statusText:			    "characters left", // The status text
			notificationClass:	"red", // Will be added to the emement when maxlength is reached
			cutDown:            false // True to cut down the string when maxCharacters reached
		}, options );
		
		// Add default event
		$.merge(settings.events, ['keyup']);

		return this.each(function() {
		  
		  // Get count
			var item = $(this);
			var charactersLength = $(this).val().length;
			
      // Update the status text
			function updateStatus() {
				var charactersLeft = settings.maxCharacters - charactersLength;
				$(settings.statusElement).html(charactersLeft + " " + settings.statusText);
			}

			// Check characters
			function checkChars() {
				var valid = true;
				// Too many chars?
				if(charactersLength >= settings.maxCharacters) {
					// Too may chars, set the valid boolean to false
					valid = false;
					// Add the notification class when we have too many chars
				  $(settings.statusElement).addClass(settings.notificationClass);
					// Cut down the string if specified
					if(settings.cutDown) item.val(item.val().substr(0,settings.maxCharacters));
				} else {
					// Remove the notification class
					$(settings.statusElement).removeClass(settings.notificationClass);
				}
				// Update ?
				if(settings.status) updateStatus();
			}
						
			// Check if the element is valid.
			function validateElement() {
				var ret = false;
				if(item.is('textarea')) ret = true;
				else if(item.filter("input[type=text]")) ret = true;
				else if(item.filter("input[type=password]")) ret = true;
				return ret;
			}

			// Validate
			if(!validateElement()) return false;
			
			// Loop through the events and bind them to the element
			$.each(settings.events, function (i, n) {
				item.bind(n, function(e) {
					charactersLength = item.val().length;
					checkChars();
				});
			});

			// Update status div
			if(settings.status) updateStatus();
			else $(settings.statusElement).remove();

		});
	};
})(jQuery);
