/*
 *
 * Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Version 1.0
 * Demo: http://www.texotela.co.uk/code/jquery/numeric/
 *
 * $LastChangedDate: 2007-05-29 11:31:36 +0100 (Tue, 29 May 2007) $
 * $Rev: 2005 $
 */
 
/*
 * Allows only valid characters to be entered into input boxes.
 * Note: does not validate that the final text is a valid number
 * (that could be done by another script, or server-side)
 *
 * @name     numeric
 * @param    decimal      Decimal separator (e.g. '.' or ',' - default is '.')
 * @param    callback     A function that runs if the number is not valid (fires onblur)
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @example  $(".numeric").numeric();
 * @example  $(".numeric").numeric(",");
 * @example  $(".numeric").numeric(null, callback);
 *
 */
jQuery.fn.numeric=function(pdecimal,callback){
	decimal=pdecimal||".";
	callback=typeof callback=="function"?callback:function(){};
	this.keydown(function(e)
	{
		var key=e.keyCode?e.keyCode:0;
		if(key==13&&this.nodeName.toLowerCase()=="input"){return true;}
		else if(key==13){return false;}

		var allow=false;
		if((e.ctrlKey&&key==97)||(e.ctrlKey&&key==65))return true; //ctrl+1(num) || ctrl+a
		if((e.ctrlKey&&key==120)||(e.ctrlKey&&key==88))return true; //ctrl+f9 || ctrl+x
		if((e.ctrlKey&&key==99)||(e.ctrlKey&&key==67))return true; //ctrl+3(num) || ctrl+c
		if((e.ctrlKey&&key==122)||(e.ctrlKey&&key==90))return true; //ctrl+f11 || ctrl+z
		if((e.ctrlKey&&key==118)||(e.ctrlKey&&key==86)||(e.shiftKey&&key==45))return true; //ctrl+f7 || ctrl+v || shift+insert
		if(pdecimal==undefined&&(key==190||key==194))return false; //.> || .(num)
		if((key<48||key>57)&&(key<96||key>105))
		{
			if(key==45&&this.value.length==0)return true;
			if(key==decimal.charCodeAt(0)&&this.value.indexOf(decimal)!=-1){allow=false;}
			if(key!=8&&key!=9&&key!=13&&key!=35&&key!=36&&key!=37&&key!=39&&key!=46){allow=false;}
			else{
				if(typeof e.charCode!="undefined"){
					if(e.keyCode==e.which&&e.which!=0){allow=true;}
					else if(e.keyCode!=0&&e.charCode==0&&e.which==0){allow=true;}
				}
			}
			if(key==decimal.charCodeAt(0)&&this.value.indexOf(decimal)==-1){allow=true;}
		}
		else{allow=true;}
		return allow;
	})
	
	.blur(function(){
		var val=jQuery(this).val();
		if(val!=""){
			var re=new RegExp("^\\d+$|\\d*"+decimal+"\\d+");
			if(!re.exec(val)){callback.apply(this);}
		}
	});
	
	return this;
}