/*
* Based on jQuery MaxLength 1.0.0 by Jose Plaza
* Description: Implements simple maxlength parameter for input text, password and textarea.
* Parameters:
	- Integer max: maximum text length
	- String class_container: name of the class that implements the character counter 
* Configuration:
	- Boolean use_container: define if the input comes with information DOM to show characters remaining or not
	- String type_container: the container DOM type (div or span recommended)
	- String prev_message: previous text on the container (prev to the remainig chars)
	- String post_message: the text before remaning chars
*/
jQuery.fn.maxLength = function(max,class_container){
	var use_container = true;
	var type_container = 'div';
	var prev_message = '';
	var post_message = '';
	
	if (max < 1) return;
	
	this.each(function(){
		//Get the type of the matched element
		var type = this.tagName.toLowerCase();
		var container = $(this).parent().parent().find(type_container+'.'+class_container) ;

		//If the type property exists, save it in lower case
		var inputType = this.type ? this.type.toLowerCase() : null;
		
		if (use_container){
			$(container).html(prev_message + (max - $(this).val().length) + post_message);
		}
		
		// Preset the max value if some text is set by default
		$(this).val($(this).val().substring(0,max));
		
		var keyFunction = function() {
			var myText = $(this).val();
			if (myText.length > max){
				$(this).val(myText.substring(0,max));
				return false;
			}
			if (use_container){
				var charsLeft = max - myText.length;
				if ((charsLeft / max) <= 0.2 ) {
					$(container).addClass('maxLengthInfo_warn');
				} else {
					$(container).removeClass('maxLengthInfo_warn');
				}
				$(container).html(prev_message + (max - myText.length) + post_message);
			}
			return true;
		};
		
		var keyFunction2 = function() {		
			if (use_container){
				$(container).html(prev_message + (max - myText.length)+post_message);
			}
			return true;
		};
		
		// For Input text or password just set maxlength attr And count container
		if($(this).is('input') && ($(this).attr('type') == 'text' 
													 || $(this).attr('type') == 'password')){
			$(this).attr('maxlength',max);
			$(this).bind('keypress keydown keyup', keyFunction);
		}
		else if ($(this).is('textarea')){
			$(this).bind('keypress keydown keyup', keyFunction);
		}
	});
};