/*
 *	Nummernformat
 *	'''''''''''''
 *	
 *				 V 0.1
 *	
 */

(function($) {
	
	//Das Objekt
	jQuery.fn.number_format = function(options) {
		
		//Optionen
		var defaults = {			
			decimals: 0,
			dec_point: ",",
			thousands_sep: ".",
			allowed_chars: [110, 190],		//KeyCodes!
			error: function(field) {
				alert("Bitte geben Sie nur ganze Zahlen ein.");
				$(field).val(0);
			}
		};
		
		//Mit den Standardeinstellungen vergleichen
		var opts = jQuery.extend(defaults, options);
		
		//Und los gehts!
		return this.each(function() {
			//Eventhandler binden
			$(this).keyup(function(event) {
				
				//console.log(event.which);
				//console.log($.inArray(event.which, opts.allowed_chars));
				
				
				if($.inArray(event.which, opts.allowed_chars) < 0) {
					value = number_format($(this).val().replace(/\./g, "").replace(/,/, ".") , opts.decimals, opts.dec_point, opts.thousands_sep);
					//console.log("new value: "+value);
					if(value != "NaN")
					 $(this).val(value);
					else 
						opts.error(this);
				}
				
			})
		});
		
		//Das übernimmt die eigentliche Formatierung
		function number_format(numeral, decimals, dec_point, thousands_sep) {
			var neu = "";
			
			// Runden
			var f = Math.pow(10, decimals);
			numeral = "" + parseInt(numeral * f + (.5 * (numeral > 0 ? 1: -1))) / f;
			
			// Komma ermittlen
			var idx = numeral.indexOf('.');
			
			// fehlende Nullen einfügen
			if(idx != -1) {
			numeral += (idx == -1 ? '.': '') + f.toString().substring(1);
			}
			
			// Nachkommastellen ermittlen
			idx = numeral.indexOf('.');
			if(idx == -1) idx = numeral.length;
			else neu = dec_point + numeral.substr(idx + 1, decimals);
			
			// Tausendertrennzeichen
			while(idx > 0) {
			if(idx - 3 > 0)
			neu = thousands_sep + numeral.substring(idx - 3, idx) + neu;
			else
			neu = numeral.substring(0, idx) + neu;
			idx -= 3;
			}
			
			return neu;
		} 
	}
})(jQuery);