(function ($) {
	jQuery.fn.faTextLimit = function (element, limit) {
		$.fn.checkCharacters = function (evt) {
			var ctrl = evt.ctrlKey;
			//var alt = evt.altKey;
			//var shift = evt.shiftKey;
			var chr = evt.which;
			var key = evt.keyCode;
			var forbiddenChr=false;			
			var possibleChr=false;
 			var chrChar = String.fromCharCode(chr);	var keyChar = String.fromCharCode(key);
			var match = /^[A-ZА-ЯЁ0-9-.,:;!?"'\s]+$/i.exec(chrChar);	// /^[A-ZА-ЯЁ0-9.,\s]+$/i
			if (match == null) forbiddenChr = true;
			if	(ctrl && (chr==99 || chr==118)) forbiddenChr=true;	//CTR+C CTR+V
			//$("#test").html('chr '+chr+', keyChar ' +chrChar+';<br/>key '+key+', keyChar ' +keyChar+'<br/>'+'forbiden '+forbiddenChr+'; possible ' +possibleChr);
			if	((key>=33 && key<=40) || key==8 || key==46) possibleChr=true;	//handle navigation arrows, home, end, pageup, pagedown, del, backspace
			if	((forbiddenChr==true  && possibleChr==false) || (possibleChr==false && typedChr==limit)) evt.preventDefault(); //don't type wrong and when limit reach and not navigating
		};
		$.fn.typedCount = function () {
			typedChr = $(this).val().length;
			element.text(limit - typedChr);
		};
		var typedChr = 0;//initialize count var
		$(this).typedCount(); //first run initialize output value 
		$(this).bind("contextmenu",function(){  return false;  }); //disable right mouse button
		$(this).bind('keypress', function (evt) {
			$(this).typedCount();
			$(this).checkCharacters(evt);
		})
		$(this).bind('keyup', function (evt) {
			$(this).typedCount();//fix last character bug
			//return false;
		})
		$(this).bind('keydown', function (evt) {
			$(this).typedCount();//fix last character bug
			//return false;
		})
	}
})(jQuery);
