var MyCurrencyFormatter = Class.create();


MyCurrencyFormatter.prototype = {

  initialize: function(fld, milSep, decSep) {


	  this.curPosiz =0;
      this.fld = $(fld);
      
      if(milSep != null)
        this.milSep = milSep;
      else
        this.milSep = '.';
        
      if(decSep != null)
        this.decSep = decSep;
      else
        this.decSep = ',';

      if (this.fld.onblur)
        this.oldOnblur = this.fld.onblur.bindAsEventListener(this);
      
      if (this.fld.onkeypress)
        this.oldOnkeypress = this.fld.onkeypress.bindAsEventListener(this);
      
      
      
      this.fld.onkeypress = this.CURRENCYEDT_onkeypress.bindAsEventListener(this);
      this.fld.onblur = this.CURRENCYEDT_onblur.bindAsEventListener(this);
    		
   },
  CURRENCYEDT_onkeypress:function (event)
  {
      var tasto = '';
      var strCheck = '0123456789';
      var whichCode;
      var value = this.fld.value;
      var len = value.length;
      var idx = value.indexOf(this.decSep);
      
    
      
      if(event.which==undefined && event.keyCode!=undefined)
        whichCode = event.keyCode;
      else
        whichCode = (window.Event) ? event.which : event.keyCode;  
      
      //by-pass del backspace(8) e del canc(0)
      if (whichCode != 8 && whichCode != 0){
    	  
    	  if(this.fld.maxLength != undefined && this.fld.maxLength >0 && this.fld.maxLength <= this.numLenght(value)) return false;//lunghezza max superata
    	  
	      if (whichCode == 13) return true;  // Enter
	      if (whichCode == 44) return false;  // Enter
		  if ( (whichCode > 36)  &&  ( whichCode < 41))  return true;
		  
	      tasto = String.fromCharCode(whichCode);  // Get key value from key code
	      
	      if (strCheck.indexOf(tasto) == -1) {
	        if(tasto == this.decSep) {
	        	idx = value.indexOf(this.decSep);
	        	if(idx == -1) {
	        	  //alert("premuto , e non c'era");    
	        	  if(value=='')
	        	    value='0';
	        	  value = value + tasto;// + '00';
	        	}
	        	else {
	        	  //alert("premuto , e già c'era");
	        	  return false;
	        	}
	        }
	        else    
	          return false;  // Not a valid key
	      }
	      else {  	
	        if(idx != -1) 
	          value = this.fillDecimal(value, tasto, idx, this.decSep);    
	        else 
	          value = this.fillMilSep(value, tasto, this.milSep);          
	      }
	
	     this.fld.value = value;  
		setPointerPos( this.curPosiz+1,$(this.fld));
	      return false;		
	  }
  },

  CURRENCYEDT_onblur: function (event)
  {  	  	
	var tmp='';
	var value = this.fld.value;
	var cont =0;  	
	
	value = value.replace(/\./g,"");
	
	len = value.length;
	
	for(i = 0; i <len; i++) {
		var c = value.charAt(len -1 -i );
		cont = cont+1;
		if(cont==4){
			tmp = '.' + tmp;
			cont = 1;
		}                 
		tmp = c+tmp;
	}	
	
	var okei = true;
//	debugJsBox('testing di onblur');


	while(okei){
		if(tmp.length != eraseFirstZero(tmp).length){
		tmp = eraseFirstZero(tmp);
//		debugJsBox(tmp);
		}else{
		okei = false;
		}
	}
	this.fld.value = tmp;    
	
  },
  
  
  isValidChar: function (value, milSep, decSep)
  {
      if (value.length == 0)
        return false;
      if(value==milSep || value==decSep) 
        return true;
      return (value.search(/[^0-9]+/) == -1);
  },


  fillMilSep: function (value, tasto, milSep) { 

  
	// sele = oggetto con le info sulla parte di testo selezionato
	var sele = getMySelectionStartLength(this.fld);

	// se il testo e' tutto selezionato ed e' piu' lungo di 1 carattere viene sostituito con la variabile 'tasto' 
	if (value.length > 1 && sele.length == value.length) return tasto;   	

	var cont=0;
	var inisel =0;
	inisel = sele.start;
	var oldValue= value;
	
	
	// controllo che la stringa contenga un numero diverso da zero
	for(i=0; i<value.length; i++) 
		if(value.charAt(i)=='0' || value.charAt(i)==milSep)
			cont++;
    	if(cont==value.length)
		value='0';


		
	cont=0;
	var tmp='';
	if(value=='0')
		value='';

		

	// sostituzione dellla parte selezionata del testo con la variablie 'tasto'
//	debugJsBox( 'lunghezza della selezione:' + sele.length);
	if (sele.start != 0){
		value =  value.substr(0 , sele.start ) + tasto + value.substring(sele.start  + sele.length, value.length);
	
	} else{
		value =  value.substr(0 , sele.start ) + tasto + value.substring(sele.start , value.length);
	}
	

	//eliminazione dei punti
	value = value.replace(/\./g,"");

	// eliminazione di un eventuale zero iniziale
	value = eraseFirstZero(value);	


	//reinserimento dei punti in modo corretto
	var len = value.length;
	for(i = 0; i <len; i++) {
		var c = value.charAt(len -1 -i );
		if( i % 3 == 0  &&  i != 0 ){ 
			tmp = milSep+tmp;
			}
		tmp = c+tmp;
	}	

	this.curPosiz = sele.start;

	//valutazione della posizione reale del cursore sulla stringa modificata ( funzione da sistemare)
	var realPosition = realPos(oldValue,value,inisel);

	// assegnazione della posizione reale al cursore
	this.curPosiz = tmp.length;

	return tmp;   	    
  },


  
  
  fillDecimal: function (value, tasto, idx, decSep) {
      var intPart = value.substr(0, idx);
      var f = value.substr(idx+1, 1);
      var s = value.substr(idx+2, 1); 
            
      if(f=='0' && s=='0')
        if(tasto!='0')
          value = intPart + decSep + tasto + s;
        else
          value = intPart + decSep + tasto;
  
      if(f!='0' && f!='') 
        if(s!='0' && s!='') 
          ;
        else
          value = intPart + decSep + f + tasto;
    
      if(f=='0' && s=='')
        value = intPart + decSep + f + tasto;
  
      if(f=='' && s=='')
        value = intPart + decSep + tasto;
        
      return value;
  },
  
  
  numLenght:function (num){
		 
	var realNum;
	realNum = num.split(this.decSep).join("");
	realNum = realNum.split(this.milSep).join("");
	realNum = eraseFirstZero(realNum);	
	return realNum.length;
 }
  
   
};


//valutazione della posizione reale del cursore sulla stringa modificata ( funzione da sistemare)
function realPos(oldValue,value,inisel){

	oldValue = oldValue.replace(/\./g,"");
	value = value.replace(/\./g,"");

	if (oldValue.length %3 != 0 && value.length%3 != 0)
		return inisel;
	else if(oldValue.length < value.length ){	

		if(oldValue.length %3 == 0){ 
			inisel++;	
		}
		return inisel;
	
	}else
		return inisel;
	
}



function getSelectionStart(obj)
{
    if (obj.setSelectionRange) {
      var selectionStart = obj.selectionStart;
      return selectionStart;
  } else {
  	var oRng = document.selection.createRange();
  	if (oRng) {
  		var sBmk = oRng.getBookmark();
  		var nMov = oRng.move("character", -99);
  		oRng.moveToBookmark(sBmk);
  		return -nMov; }
  	else
  		return 0
  }
}



//funzione per il monitoraggio della selezione di un testo
function getMySelectionStartLength(obj)
{
	oSel = new Object;
	oSel.start = 0;
	oSel.length = 0;
	oSel.bSelected = true;
  
	
	if (obj.setSelectionRange) {
		var selectionStart = obj.selectionStart;
		var selectionEnd = obj.selectionEnd;
	if (selectionStart>=0) {
		oSel.length = selectionEnd-selectionStart;
		if (oSel.length==0) {
  			oSel.bSelected = false;
			//		oSel.length++;
      }

    	oSel.start = selectionStart;
  	} 
  	return oSel;
      
     
  } else {
  	var oRng = document.selection.createRange();
  	if (oRng) {
  		oSel.length = oRng.text.length;
  		if(!oSel.length) {
  			oSel.bSelected = false;
 // 			oSel.length++;
  		}	
  		var sBmk = oRng.getBookmark();
  		var nMov = oRng.move("character", -99);
  		oRng.moveToBookmark(sBmk);
  		oSel.start = -nMov;
  	} 
  	return oSel;
  }  		
}



// posizionamento del cursore nell'oggetto del dom 'obj' nel posto 'inVal'
function setPointerPos(inVal,obj)
{
  if (obj.setSelectionRange) {
	obj.setSelectionRange(inVal,inVal);
  } 
  else {
   var oRng = document.selection.createRange();
	oRng.collapse(false);
	oRng.move("character",inVal - $F(obj).length);
	oRng.select();
  }
}

// cancellazione di un eventuale zero o punto come primo carattere della stringa 'strin'
function eraseFirstZero(strin){

	if (strin.charAt(0) =="0" && strin.length > 1 )
		strin = strin.substring(1 , strin.length);
	if  (strin.charAt(0) ==".")
		strin = strin.substring(1 , strin.length);
	
return strin;
}
var quantita= 0;


function debugJsBox( testo){
	quantita++;
	var win;
	var alreadyOpened;
	if ($('debugJsBox')){
		win = Windows.getWindow('debugJsBox');
		alreadyOpened = true;
	} else{
		win = new Window('debugJsBox',{top: 130, resizable: true, draggable:true, wiredDrag: true });
		alreadyOpened = false;
		win.setSize(  200   , 200);
		win.setTitle('debugJsBox')
		win.showCenter(false, 200,200); 
	}
	win.getContent().innerHTML += testo ;
	win.getContent().innerHTML += "<br>" ;	
}

