// Achtung!
// 
// getValue liefert nicht 123.5 sondern 123,5
// daher getValueForDb() benutzern

Ext.namespace('Ext.ux.plugins');

Ext.ux.plugins.numberFormater = function(config){
	Ext.apply(this,config);
};


Ext.extend(Ext.ux.plugins.numberFormater, Ext.util.Observable, {
	init:function(input){
		Ext.apply(input,{
			enableKeyEvents:true,
			setFormat:function(){


				var value = this.getValue();
				if(value == 0){
					return;
				}
				
				var rawValue = this.number_format(value, 0, this.decimalSeparator, '.');
				
				this.setRawValue(rawValue);
				
				
			},

		
			beforeBlur:function()
		    {
				var A = String(this.getRawValue());
				
				if(A.indexOf('.')!=-1){
					while(A.indexOf('.')!=-1){
						A = A.replace('.','');
					}
				}
				
				
				A = parseFloat(A.replace(this.decimalSeparator,'.'));
				
				A = this.fixPrecision(A);
			
		        
		       this.setValue(A)
		    },
		
		    setValue : function(v){
		    	v = typeof v == 'number' ? v : parseFloat(String(v).replace(this.decimalSeparator, "."));
		        v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator);
		        Ext.form.NumberField.superclass.setValue.call(this, v);
				this.setFormat();
		    },
		    
		
		    parseValue : function(value){

				if(value.indexOf('.')!=-1){
					while(value.indexOf('.')!=-1){
						value = value.replace('.','');
					}
				}
				
				
		        value = parseFloat(String(value).replace(this.decimalSeparator, "."));
		        return isNaN(value) ? '' : value;
		    },
		

			number_format:function ( number, decimals, dec_point, thousands_sep ) {
			    // Format a number with grouped thousands


			    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
			    var d = dec_point == undefined ? "." : dec_point;
			    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
			    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;

			    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
			}
		});
		
		
		input.on('blur',function(){

			this.setFormat();
		});
		
		input.on('render',function(){

		});
		
		input.on('focus',function(){
			if(this.getValue()!=0){

				this.setRawValue(String(this.getValue()).replace('.', this.initialConfig.decimalSeparator));				
			
			}

		});
		
	}
}); 
