(function($){
	// If the browser already supports maxlength, gto.
	if (('maxLength' in document.createElement('textarea'))) return;  

	$(function(){
		var areas = $('textarea[maxlength]'), 
		allowedKeys = [
			8,  //backspace
			9,  //tab
			16, //shift
			17, //ctrl
			27, //escape
			33, //page up
			34, //page down
			35, //end
			36, //home
			37, //left arrow
			38, //up arrow
			39, //right arrow
			40, //down arrow
			46  //delete
		];
  
		// Some keys a user should be able to press, even if they're maxed out.
		function keyIsAllowed(keyCode){
			var len = allowedKeys.length; 
			while(len--) if (allowedKeys[len]===keyCode){ return true; };
		};
  
		// If some text is selected, a user should be able to make an edit.
		// Default behavior is to replace selected text with keys pressed.
		function textIsSelected(){
		//IE detection then FF detection. None for webkit, since it has maxLength support <3 (Safari 5 & Chrome 8 at least)
		return (document.selection && document.selection.createRange().text.length>0) 
			|| (this.selectionStart !== this.selectionEnd);
		};
  
		function handle_key(e){
			var max = e.data.max, len = this.value.length, maxed = len>=max;    
			if (len>max) this.value = this.value.substr(0,max); // Maybe this should only be done keyup. I think it looks better on both, but def not *quite* as efficient.      
			return !maxed || keyIsAllowed(e.keyCode) || e.ctrlKey || textIsSelected.call(this); 
		};
  
		areas && areas.bind('keydown keyup', { max:parseInt($(this).attr('maxlength')) }, handle_key);
	});
})(jQuery);


