/**
* @author Daniel Kis
* CRM Numericfield plugin 0.0
*
* usage:
* $("input.numeric").Numericfield();
*/
(function($){

	$.fn.Numericfield = function(options) {
		
		
		$(this).blur(function () {
			$(this).val(__number_format(__remove_spaces($(this).val()),',',' '));
		});
		$(this).focus(function () {				
			$(this).val(__remove_spaces($(this).val()));
		});
		
		$(this).keypress(function (event) {
			return __keypress_checker(event);
		});
		
		function __remove_spaces(str)
		{
			var s = '';
			str = str.toString();
			
			for(i=0;i<str.length;i++)
			{
				if(str.charAt(i)!=' ') s+= str.charAt(i);
			}
			return s;
		}
		function __number_format(num, decpoint, sep) {
				  num = num.toString().replace(",",".");
				  num = parseFloat(num);
				  if(isNaN(num))
				  {
				  		return "";
				  }

				  // check for missing parameters and use defaults if so
				  if (arguments.length == 2) {
					sep = ",";
				  }
				  if (arguments.length == 1) {
					sep = ",";
					decpoint = ".";
				  }
				  // need a string for operations
				  num = num.toString();
				  // separate the whole number and the fraction if possible
				  a = num.split(decpoint);
				  x = a[0]; // decimal
				  y = a[1]; // fraction
				  z = "";
				
				
				  if (typeof(x) != "undefined") {
					// reverse the digits. regexp works from left to right.
					for (i=x.length-1;i>=0;i--)
					  z += x.charAt(i);
					// add seperators. but undo the trailing one, if there
					z = z.replace(/(\d{3})/g, "$1" + sep);
					if (z.slice(-sep.length) == sep)
					  z = z.slice(0, -sep.length);
					x = "";
					// reverse again to get back the number
					for (i=z.length-1;i>=0;i--)
					  x += z.charAt(i);
					// add the fraction back in, if it was there
					if (typeof(y) != "undefined" && y.length > 0)
					  x += decpoint + y;
				  }
				  return x;
		}
		
		function __keypress_checker(e)
		{
			var key = e.keyCode ? e.keyCode : e.charCode;
			if((key>47 && key<58) || key==9 || key==32 || key==45 || key==47 || key==8 || key==37 || key==39 || key==46 || key==44 || key==36 || key==35)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		
		
	}
})(jQuery);
