/*
 * jQuery onlyChars
 *
 * Plug-in ktery kontroluje zda jsou ve formularovem policku jen povolene znaky a nepovolene odstrani.
 *
 * Copyright (c) 2008 Michal Kandr www.kandr.name
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2008-10-06 14:31:17 $
 * $Rev: 1 $
 */

(function($){
	$.fn.onlyChars = function(p) {
		return this.each(function(){
			$(this).keyup(function(e){
				if(e.keyCode != 37 && e.keyCode != 39 && e.keyCode != 16){
					//puvodni hodnota
					var oldVal = $(this).val();
					//zjisteni pozice kurzoru
					var oldCurPos;
					var field = this.jquery ? this[0] : this;
					if('selectionStart' in field){
						//Gecko
						oldCurPos = field.selectionStart;
					} else {
						//IE
						field.focus();
						var r = document.selection.createRange();
						if (r == null) {
							oldCurPos = 0
						} else {
							var re = field.createTextRange();
							var rc = re.duplicate();
							re.moveToBookmark(r.getBookmark());
							rc.setEndPoint('EndToStart', re);
							oldCurPos = rc.text.length;
						}
					}
					//vyhozeni nevyhovujicich znaku
					$(this).val($(this).val().replace(new RegExp('[^'+p+']','g'),''));
					var newVal = $(this).val();
					//nastaveni pozice kurzoru na puvodni
					if(oldCurPos > newVal.length){
						oldCurPos = newVal.length+1;
					}
					if(newVal != oldVal){
						--oldCurPos;
					}
					if(!$.browser.msie){
						//Gecko
						field.focus();
						field.setSelectionRange(oldCurPos, oldCurPos); 
					} else {
						//IE
						var range = field.createTextRange();
						range.move("character", oldCurPos);
						range.select();
					}
				}
			});
		});
	};
	
	$.fn.onlyInt = function() {
		return this.each(function(){
			$(this).onlyChars('\\d');
		});
	};
	
	$.fn.onlyIntS = function() {
		return this.each(function(){
			$(this).onlyChars('\\d+-');
		});
	};
	
	$.fn.onlyFloat = function() {
		return this.each(function(){
			$(this).onlyChars('\\d,\.');
		});
	};
	$.fn.onlyFloatS = function() {
		return this.each(function(){
			$(this).onlyChars('\\d,\.+-');
		});
	};
})(jQuery);
