/*
 * jquery.limitinput. The jQuery limit input plugin
 *
 * Copyright (c) 2009 Djalma Araújo de Andrade
 * http://www.djalmaaraujo.com.br
 * contato [at] djalmaaraujo.com.br
 *
 * Licensed under MIT License
 *
 * Launch  : Nov, 2009
 * Version : 0.2.1 edge
 * Released: 09.11.09, 09:33
 *
 * History:
 *
 * Version 0.2.1 edge
 * - Fixed bug. The keyCode SPACE was not count.
 * - Fixed Bug. When the limit was over, keyCode was disable. Add allowed key codes
 * Version 0.2.1
 * - Add checkVal() function to block typing with no escape caracter.
 * - thnks to Ruan Carlos - www.ruancarlos.com.br for the tip
 * - thnks to Wilker Lúcio for support
 * Version 0.2 
 *	- Add keydown, keypress, focus, mouseover, mouseout events
 *	- Remove keypress delay
 *
 * ###########################################################################################
 * ######################################### HOW TO ##########################################
 * ###########################################################################################
 *
 * Options:
 *	- (int)     		limit           *** Limit of caracters.
 *  - (string)  		charName		*** The word "Caracters" in your language.
 *	- (boolean) 		blockTyping     *** Block the typing when limit is over.
 *	- (string) 			sufixDisplay    *** Name will apear on the sufix of the div element.
 *	- (string) 			excededString   *** Name will apear on the sufix of the display message.
 *	- (string) 			leftString   	*** Name will apear on the sufix of the display message.
 *
 */
 
(function(jQuery) {
	
	jQuery.fn.limitInput = function(options) {
		
		//Default parameters
		var sets = {
			limit: 300,
			sufixDisplay: 'limitInput',
			charName: "Characters",
			excededString: "Exceeded",
			leftString: "Left",
			blockTyping: true
		};
		
		jQuery.extend(sets, options || {});
		
		//keyDownPress
		function keyDownPressAllowed(e) {
			
			if ((e.keyCode >= 8) && (e.keyCode <= 46)) {
				return true;
			} else {
				return false;
			}
		};
		
		//Check val
		function checkVal(element, options, e) {
		
			jQuery.extend(sets, options || {});
				
			var inputValue = element.val();
			var inputLength = inputValue.length;
		    if (inputLength >= sets.limit) {
		    	if (!keyDownPressAllowed(e)) {
		    		if (sets.blockTyping) {
		    			return false;
		    		} else {
		    			return true;
		    		}
		    	} else {
		    		return true;
		    	}
		    } else {
		    	return true;
		    }
		};

      var elementDisplay;

		//DoLimit
		jQuery.fn.limitInput.bindElements = function (element, options)
		{
		
			jQuery.extend(sets, options || {});
				
			var inputValue = element.val();
			var inputLength = inputValue.length;
		   elementDisplay = element.attr('id') + sets.sufixDisplay;
			
			if (jQuery('div[id="' + elementDisplay + '"]').length == 0) {
				
				//Add relative position
				element.parent().addClass('jquery-limitinput-element');
				
				//Create display
			 	element.after('<div id="' + elementDisplay + '" class="jquery-limitinput-container"></div>');
			 	
			};
			
			//Message display
			if (inputLength > sets.limit) {
			    if (sets.blockTyping) element.val(inputValue.substr(0,sets.limit));
			    var inputValue = element.val();
				var inputLength = inputValue.length;
				if ((sets.limit - inputLength) < 0) {
					var displayMsg = (inputLength-sets.limit) + ' ' + sets.charName + ' ' + sets.excededString;
				} else {
					var displayMsg = sets.limit - inputLength + ' ' + sets.charName + ' ' + sets.leftString;
				}
			} else {
				var displayMsg = sets.limit - inputLength + ' ' + sets.charName + ' ' + sets.leftString;
			}
			//var displayDiv = jQuery('#' + elementDisplay);
			jQuery('#' + elementDisplay).text(displayMsg);

/*			
			//Element positions
			var elementWidth = element.width();
			var elementHeight = element.height();
			var elementOffsetTop = element.offset().top;
			var elementOffsetLeft = element.offset().left;
			
			//Element display positions
			var displayWidth = jQuery('#' + elementDisplay).width();
			var displayHeight = jQuery('#' + elementDisplay).height();
			var elementDisplayPosTop = elementOffsetTop - (displayHeight-10);
			var elementDisplayLeft = elementWidth + (displayWidth-30);
			
			//Apply display positions
			jQuery('#' + elementDisplay).css({
			    top: elementDisplayPosTop + 'px',
			    left: elementDisplayLeft + 'px'
			});
*/
		};
		
		//Run
		return this.each(function(){
		
			//Check if its a textarea or a input valid
			var arrAllowed = [ "text", "password" ];
			if (jQuery(this).is('textarea')) {
				initCheck = true;
			} else if (jQuery(this).is('input')) {
			
				if (jQuery(this).is('input') && (jQuery.inArray(jQuery(this).attr('type'), arrAllowed) != -1)) {
					initCheck = true;
				} else {
					initCheck = false;
				};
			};
			
			//If the element is valid, apply the plugin
			if (initCheck) {
			
				//INIT
				jQuery.fn.limitInput.bindElements(jQuery(this), options);
				//BIND
				jQuery(this)

				.bind('keyup', function() { jQuery.fn.limitInput.bindElements(jQuery(this), options); })
				.bind('keydown', function(e) { if (!checkVal(jQuery(this), options, e)) { return false; }; })
				.bind('keypress', function(e) { if (!checkVal(jQuery(this), options, e)) { return false; }; })
				.bind('focus', function() {
               jQuery.fn.limitInput.bindElements(jQuery(this), options); 
               //Shows display
               //jQuery('#' + elementDisplay).fadeIn('fast');
      			jQuery('#' + elementDisplay).addClass('jquery-limitinput-container-active');
            })
				.bind('blur', function() {
				   jQuery('.jquery-limitinput-container').removeClass('jquery-limitinput-container-active');
      			//jQuery('#' + elementDisplay).removeClass('jquery-limitinput-container-active');
            })
				.bind('mouseover', function() { jQuery.fn.limitInput.bindElements(jQuery(this), options); })
				.bind('mouseout', function() { jQuery.fn.limitInput.bindElements(jQuery(this), options); })
				.bind('paste', function() {
					setTimeout(function () { jQuery.fn.limitInput.bindElements(jQuery(this), options); }, 10); 
				});
			};
		});
	};
})(jQuery);