// Questa variabile globale sarà utilizzata dal numero per eseguire il controllo lato client per
// i numeri decimali. Rappresenta il simbolo dei decimali e verrà cambiato dal controllo numero,
// in base alle impostazioni della cultura della macchina, ad ogni caricamento della pagina.
var IGCal_SepDec;

var IGCal_DateSep;
var IGCal_DateFormat;
var IGCal_DatePos_dd;
var IGCal_DatePos_MM;
var IGCal_DatePos_yyyy;

function IGCal_Redirect(url)
{
  window.location = url;
}

function IGCal_ShowDlg(url,x,y,height,width,padding,modal,scrollbars,resizable)
{ 
  var params = "";
  
  if (padding < 0)
    padding = screen.availWidth/4;
  
  
  if (height > 0)
    params += ",height=" + height;
  else
  {
    height = screen.availHeight - padding;
    params += ",height=" + height;   
  }

  if (width > 0)
    params += ",width=" + width;
  else
  { 
    width = screen.availWidth - padding;
    params += ",width=" + width;
  }
   
  width = Math.min(screen.availWidth, width);  
  height = Math.min(screen.availHeight, height);
    
  if (x<0)
    // Centrato X
    x = (screen.availWidth - width) / 2 ;
   
  if (y<0)
    // Centrato Y
    y = (screen.availHeight - height) / 2;
 
  params += ",left=" + x; 
  params += ",top=" + y;
        
  if (scrollbars)  
    params += ",scrollbars=yes";
  else
    params += ",scrollbars=no";  
  
  if (resizable)  
    params += ",resizable=yes";
  else
    params += ",resizable=no";
  
  if (params != "")
    params = params.substr(1);
  
	var newwnd = '';
	newwnd = window.open(url, "_blank", params+",location=no,menubar=no,toolbar=no,status=yes");	
//	if (window.focus) {newwnd.focus()}
//	return false;
}

function IGCal_ShowDlgDynURL(url,x,y,height,width,padding,modal,scrollbars,resizable,Elementi)
{ 
  var params = "";
  
  if (padding < 0)
    padding = screen.availWidth/4;
  
  
  if (height > 0)
    params += ",height=" + height;
  else
  {
    height = screen.availHeight - padding;
    params += ",height=" + height;   
  }

  if (width > 0)
    params += ",width=" + width;
  else
  { 
    width = screen.availWidth - padding;
    params += ",width=" + width;
  }
   
  width = Math.min(screen.availWidth, width);  
  height = Math.min(screen.availHeight, height);
    
  if (x<0)
    // Centrato X
    x = (screen.availWidth - width) / 2 ;
   
  if (y<0)
    // Centrato Y
    y = (screen.availHeight - height) / 2;
 
  params += ",left=" + x; 
  params += ",top=" + y;
        
  if (scrollbars)  
    params += ",scrollbars=yes";
  else
    params += ",scrollbars=no";  
  
  if (resizable)  
    params += ",resizable=yes";
  else
    params += ",resizable=no";
  
  if (params != "")
    params = params.substr(1);

  i = 0;
  while (i<Elementi.length) {
    var objElem = document.getElementById(Elementi[i+1]);
    if (objElem == null)
        objElem = document.forms[0][Elementi[i+1]];

    url += "&" + Elementi[i] + "=" + objElem.value;
    i = i + 2;
  }
    window.open(url, "_blank", params+",location=no,menubar=no,toolbar=no,status=yes");	
}

function IGCal_DelMsg()
{
  return confirm("Sicuri di voler procedere?");
}

function IGCal_Pnl_Refresh(invert,objPnlDivName,objPnlTableName,srcCollapsed,srcExpanded)
{
  var objPnl = document.getElementById(objPnlDivName);
  if (objPnl == null)
    return;
    
  var origH  = objPnl.attributes["originalHeight"].value;
  var objTbl = document.getElementById(objPnlTableName + "_pnlTbl");
  var objRow = document.getElementById(objPnlTableName + "_pnlRow");
  var objImg = document.getElementById(objPnlTableName + "_PnlImgCollapse");
  
  var objHid = document.getElementById(objPnlDivName + "_pnlState");
  
  if (objHid == null)
    objHid = document.forms[0][objPnlTableName + "_pnlState"];
    
  var isCollapsed;
  if (objHid == null)
  {
   return;
   }  

  isCollapsed = (objHid.value == srcExpanded)
  
  if (invert)
    isCollapsed = !isCollapsed;
   
  if(isCollapsed)
  {
    objRow.style.display = "none";
    objTbl.style.height = 1;
    objHid.value = srcExpanded;
  }
  else
  {
    objRow.style.display = "inline";
    objTbl.style.height = origH;
    objHid.value = srcCollapsed;
  }  
  
  objImg.src = objHid.value;  
}

//[stefano] questa funzione non é + necessaria nel 2.0
//function IGCal_fkLstSel(objLst,objtxt,objHidden,objDiv,objImgCloseId)
//{
//  if (document.forms[0][objtxt.id].value != objLst.options[objLst.selectedIndex].text)
//  {
//    document.forms[0][objtxt.id].value = objLst.options[objLst.selectedIndex].text;
//    document.forms[0][objtxt.id].title = "";
//    document.forms[0][objHidden.id].value = objLst.options[objLst.selectedIndex].value;  
//  //eval("document.all."+objDecodifica).click();
//  }
////  var objPnl = document.getElementById(objDiv.id);
////  objPnl.style.visibility = "hidden";
//  var objLista = document.getElementById(objLst.id);
//  objLista.style.visibility = "hidden";
//  var objImg = document.getElementById(objImgCloseId);
//  objImg.style.visibility = "hidden";
//}

function IGCal_fkHideMoreResults(objLstId,objImgCloseId)
{
  var objLista = document.getElementById(objLstId);
  objLista.style.visibility = "hidden";
  objLista.style.top = "-1000";
  objLista.style.position = "absolute";
  objLista.style.zIndex = "1000";

  var objImg = document.getElementById(objImgCloseId);
  objImg.style.visibility = "hidden";
  objImg.style.top = "-1000";
  objImg.style.position = "absolute";
  objImg.style.zIndex = "1000";
}


function IGCal_OpenCalendar(objData, calendarPageUrl)
{
 /* if (!IGCalDat_onBlur(null, objData))
    return;*/
      
  var xpos = screen.availWidth/2 -110;
  var ypos = screen.availHeight/2-100;
  
  var height = "200";
  var width = "220";     
  calendarPageUrl = calendarPageUrl + "?val="+escape(objData.value)+"&IDCaller="+objData.id+"&DF="+escape(IGCal_DateFormat);  
	var objW = window.open(calendarPageUrl, "_blank", "left="+xpos+",top="+ypos+",height="+height+",width="+width+",location=no,scrollbars=no,menubar=no,resizable=no,toolbar=no,status=no");
}

function IGCal_OpenAutorizzazione(objnumAut, AutPageUrl, CSER)
{
  var xpos = screen.availWidth/2 -110;
  var ypos = screen.availHeight/2-100;
  
  var height = "180";
  var width = "340";     
  AutPageUrl = AutPageUrl + "?val="+escape(objnumAut.value)+"&IDCaller="+objnumAut.id+"&ValAutoriz="+objnumAut.value+"&CSER=" + CSER;  
  var objW = window.open(AutPageUrl, "_blank", "left="+xpos+",top="+ypos+",height="+height+",width="+width+",location=no,scrollbars=no,menubar=no,resizable=no,toolbar=no,status=no");
}

// Recupera i valori degli attributi dall'html
function IGCal_Num_Params(e, obj)
{
  var dec;  
	if(document.all) 
	{	
		// Explorer
    dec = parseInt(obj.attributes["DN"].value);		
    int_digit = parseInt(obj.attributes["IN"].value);	
		this.Formato = obj.attributes["FT"].value;
		this.Range = obj.attributes["RG"].value;		
	}	
	else
	{ 	
		// Gli altri		
    dec = parseInt(e.target.attributes["DN"].value);
    int_digit = parseInt(e.target.attributes["IN"].value);
		this.Formato = e.target.attributes["FT"].value;
		this.Range = e.target.attributes["RG"].value;				
	}
	
  this.Decimali = isNaN(dec)? 0 : dec;	
  this.Interi = isNaN(int_digit)? 0 : int_digit;
}
  
// Nella pressione del tasto viene consentito l'inserimento delle sole cifre che possono
// comporre un numero in base alle impostazioni degli attributi che decorano il controllo
// Formato (FT), Range (RG), Numero dei decimali (DN), Numero degli interi (IN).
// E' possibile recuperare da ST la versione precedente.
function IGCalNum_onKeyPress(e, obj)
{
	var keyCode;
	var isCtrl = false;
	var keychar;
	var reg;
	
	// se non è impostato un separatore (mai!) ne imposto uno di default (italiano)
	if (IGCal_SepDec == "")
	  IGCal_SepDec = ",";
	
	// recupero i parametri
	var params = new IGCal_Num_Params(e, obj);
		
	// Tasto premuto in base al browser		
	if(document.all) 
	{
	  // Explorer
		keyCode = event.keyCode;
		isCtrl = window.event.ctrlKey;
	}
	else if(e.which) 
	{
		keyCode = e.which;
		isCtrl = e.ctrlKey;
		// Caratteri speciali non gestiti che in Netscape valgono 0
		if (keyCode == 0)
			return true;
	}
	
	// in caso di keyCode non numerico
	if (isNaN(keyCode)) 
    return true;
		
	// recupero il valore dal code
	keychar = String.fromCharCode(keyCode);	
	
	// controllo BackSpace e Ctrl (ammessi)
	if (keyCode == 8 || keyCode == 13 || isCtrl)
		return true;

  // imposto una regular expression su cifre
	reg = /\d/;
	// controllo il meno per range illimitato
	var isFirstN = (params.Range == '1') ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
	// controllo il separatore per formati decimali con numero cifre decimali > 0
	var isFirstD = (params.Formato == "2" && params.Decimali > 0) ? keychar == IGCal_SepDec && obj.value.indexOf(IGCal_SepDec) == -1 && obj.value != "" && obj.value != "-": false;

	if (isFirstN || isFirstD || reg.test(keychar))
	  return true;
	else
	{
	  // non è un tasto ammesso
	  if(document.all)	
  	  event.keyCode = 0; 
  	  
  	return false;
	}
}

// Impostata su OnBlur del controllo numero per sistemare le cifre decimali
// aggiungendo gli zeri dove occorre
function IGCalNum_onBlur(e, obj)
{
  IGCalNumero_FinalFormatting(e, obj);
}

// gestisce la formattazione finale del testo nel controllo Numero
function IGCalNumero_FinalFormatting(e, obj)
{
  // recupero il valore
  var valore = obj.value;
  
  // se c'è q.sa formatto a modo
  if (valore != null && valore != "")
  {
    // se non è impostato un separatore (mai!) ne imposto uno di default (italiano)
    if (IGCal_SepDec == "")
	    IGCal_SepDec = ",";
	  
	  // imposto il separatore  
	  var SepDecCode = IGCal_SepDec.charCodeAt(0);
	
	  // recupero i parametri dall'html
	  var params = new IGCal_Num_Params(e, obj);
	
	  // nel caso di decimali con Decimali settato
	  if (params.Formato == "2" && params.Decimali > 0)
	  {
	    // se c'è il separatore lo converto in punto
	    if (valore.indexOf(IGCal_SepDec) != -1)
	    {
	      valore = valore.replace(IGCal_SepDec, ".");
	      // effettuo la conversione solo se necessaria decimali effettivi < decimali dichiarati
	      if (valore.substring(valore.indexOf(".")+ 1, valore.length).length < params.Decimali)  
	        valore = parseFloat(valore).toFixed(params.Decimali);
	    }
	    // se non c'è il separatore converto direttamente
	    else
	      valore = parseFloat(valore).toFixed(params.Decimali);
	  }   
	    // se formato decimale e decimali = 0 o
	    // in caso di formato intero non devo formattare
	}
	// rimetto il separatore giusto
	valore = valore.replace(".", IGCal_SepDec);
	
	// in caso di inizio con la virgola, inserita tramite click del mouse, aggiungo uno zero iniziale
	if(valore.indexOf(IGCal_SepDec)==0)
	  valore = "0" + valore;
	
	obj.value = valore;
	return true;
}

// Impostata su OnKeyUp del controllo numero
// Nella pressione del tasto viene consentito l'inserimento delle sole cifre che possono
// comporre un numero in base alle impostazioni degli attributi che decorano il controllo
// Formato (FT), Range (RG), Numero dei decimali (DN), Numero degli interi (IN).
function IGCalNum_onKeyUp(e, obj)
{
  // recupero il valore compreso il tasto appena premuto
	var temp = obj.value;
	
	// se non è impostato un separatore (mai!) ne imposto uno di default (italiano)
	if (IGCal_SepDec == "")
	  IGCal_SepDec = ",";
	
	// recupero i parametri
	var params = new IGCal_Num_Params(e, obj);
	
	// non cambiamo la stringa se corrisponde correttamente alla seguente regular expression
	var reg0Str;
	
	if (params.Interi > 0)
	  reg0Str = '[0-9]{0,' + params.Interi + '}';
	else
	  // se Interi=0 numero di cifre illimitato
	  reg0Str = '[0-9]*';

  // in caso di formato decimale con più di una cifra decimale dichiarata aggiungo il separatore e le cifre
	if (params.Formato == "2" && params.Decimali > 0) 
	{
		reg0Str += '\\' + IGCal_SepDec + '?[0-9]{0,' + params.Decimali + '}';
	} 
	// qui si potrebbe aggiungere che in caso di Decimali=0 formattiamo a due cifre decimali

  // in caso di range illimitato è possibile anche avere il meno
	reg0Str = params.Range == '1' ? '^-?' + reg0Str : '^' + reg0Str;
	// fine stringa
	reg0Str = reg0Str + '$';
	var reg0 = new RegExp(reg0Str);

  // se corretta non devo fare niente
	if (reg0.test(temp)) 
	   return true;

	// modifico tutti i non numeri, separatore e - con blank
	var reg1Str = '[^0-9' + (params.Formato == "2" && params.Decimali > 0 ? "\\" + IGCal_SepDec : '') + (params.Range == '1' ? '-' : '') + ']';
	// g = Global search for all occurrences of a pattern
	var reg1 = new RegExp(reg1Str, 'g');
	temp = temp.replace(reg1, '');
	
   // se range illimitato elimino eventuali altri segni meno
	if (params.Range == '1') 
	{		
		var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
		// l'sitruzione seguente è equivalente a new regexp
		var reg2 = /-/g;
		temp = temp.replace(reg2, '');
		if (hasNegative) 
		  temp = '-' + temp;
	}

  // se formato decimale con numero di decimali dichiarati >0
	if (params.Formato == "2" && params.Decimali > 0) 
	{
		var reg3 = new RegExp("\\" + IGCal_SepDec,'g');

		var reg3Array = reg3.exec(temp);
		if (reg3Array != null) {
			// keep only first occurrence of Sep
			//  and the number of places specified by decimals
			// index (the zero-based index of the match in the string) 
      // [0] (the portion of the string that was matched last) 
			var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
			reg3Right = reg3Right.replace(reg3, '');
			// recupero la parte decimale e ricompongo la stringa corretta
			reg3Right = reg3Right.substring(0, params.Decimali);
			temp = temp.substring(0,reg3Array.index) + IGCal_SepDec + reg3Right;
		}
	}

  // numero di interi dichiarati>0
	if (params.Interi > 0) 
	{		
		// controllo il meno e memorizzo che si tratta di un numero negativo in un flag
		var isNegative = false;
		if (temp.charAt(0) == '-')
		{
		  isNegative = true;
		  temp = temp.substring(1);
		}
		var reg4 = new RegExp("\\" + IGCal_SepDec,'g');
    var reg4Array = reg4.exec(temp);
    
		if (reg4Array != null) 
		{		  
			// keep only first occurrence of Sep
			//  and the number of places specified by integer
			var reg4Left = temp.substring(0, reg4Array.index);
			reg4Left = reg4Left.replace(reg4, '');
			// elimino cifre in eccesso dalla coda della parte intera e ricompongo la stringa
			reg4Left = reg4Left.substring(0, params.Interi);
			temp =reg4Left + IGCal_SepDec + temp.substring(reg4Array.index + reg4Array[0].length,temp.length);
		}
    else
    {
      temp = temp.substring(0, params.Interi);
    }
    
    // rimetto il meno se c'era
    if (isNegative)
     temp = "-" + temp;
	}
	
	obj.value = temp;
}

// Previene un paste di un valore non congruente con le impostazioni del numero
// Se le impostazioni non coincidono sbianca il campo
// su Firefox non esiste onPaste!
function IGCalNum_onPaste(e, obj) 
{	
	var clipData = window.clipboardData.getData("Text");	
	var Negativo = false;
	
  // Devo avere q.cosa da incollare
	if(clipData.length == 0)
	  return;
	  
	// recupero i parametri
	var params = new IGCal_Num_Params(e, obj);
	  
  obj.value = trim(clipData);  
	var Valore = obj.value;
	
	// in caso di formato intero, decimali varrà sempre 0
  if(params.Formato == "1")
     params.Decimali = 0;      
	
	// Ricavo il numero
  var valNum = NaN;
  if (params.Formato == "1")
    valNum = parseInt(Valore);
  else if (params.Formato == "2")
    // Se dovesse contenere un separatore decimale lo trasformiamo in . per far funzionare il float
    valNum = parseFloat(replace(Valore,IGCal_SepDec,"."));
  
  obj.value = "";
  if (!isNaN(valNum))
  {
    if (params.Range == "2" && valNum < 0)
    {
      // Abbiamo richiesto un numero positivo ma ne stiamo incollando uno negativo
      alert("Questo campo non accetta numeri negativi.");
    }
    else
    {     
      var divisore = Math.pow(10,params.Decimali);
      valNum = Math.round(valNum * divisore)/divisore;      

      var string_num = valNum.toString(); 
      
      // memorizzo se si tratta di un numero negativo
      if(string_num.charAt(0) == '-')
      {
        Negativo = true;
        string_num = string_num.substring(1);
      }        
      
      var arr_num;
      
      // se incollo un numero con separatore, separo la parte intera e controllo la lunghezza
      if (string_num.indexOf(".") != (-1))
      {
        arr_num = string_num.split(".");
        
        // se incollo un numero con interi superiori al previsto non lo faccio
        if (params.Interi > 0 && arr_num[0].length > params.Interi)
        {
          alert("Il numero di cifre intere supera la dimensione massima consentita.");
          return false;
        }
      }
      // se incollo un numero senza separatore, controllo la lunghezza della stringa
      else
        if (params.Interi > 0 && string_num.length > params.Interi)
        {
          alert("Il numero di cifre intere supera la dimensione massima consentita.");
          return false;
        }
        
      
      // in caso di formato decimale se il numero di decimali è inferiore aggiungiamo zeri
      if(params.Formato == "2")
      {
        if (string_num.indexOf(".") != (-1))
        {
          // se il numero di decimali è minore del previsto
          if (arr_num[1].length < params.Decimali)
          {
            for (var i=0; i < params.Decimali - arr_num[1].length; i++)
              string_num += "0";
          }
        }
        // altrimenti aggiungiamo il separatore e il numero di zeri esatto
        else
        {        
          string_num += ".";
          for (var i=0; i < params.Decimali; i++)
              string_num += "0";
        }     
      }
      
      // elimino il punto se appare come ultimo carattere
      if (string_num.charAt(string_num.length-1) == '.')
        string_num = string_num.substring(0, string_num.length - 1);
        
      // rimetto il meno se l'avevo tolto  
      if (Negativo)
        string_num = "-" + string_num;

      // In tutti gli altri casi il numero è ammesso (rimetto il simbolo dei dec. originale)
	    obj.value += replace(string_num,".",IGCal_SepDec);
	    obj.select();	    
    }
  }
    
	return false;
}

// evento onKeyPress del controllo data
function IGCalDat_onKeyPress(e, obj) 
{	
   var keyCode;
  
   // Estraggo gli attributi del controllo numero, recupero parametri in base al browser	
   if(document.all) 
      // Explorer
      keyCode = e.keyCode;
   else
   { 
     // Gli altri
     keyCode = e.which;				
        
     // Caratteri speciali non gestiti che in Netscape valgono 0
     if (keyCode == 0)
        return true;
   }	
  
  // tasto invio
  if (keyCode == 13)
  {
   return IGCalDat_FinalFormatting(e, obj);
  }
  
  // recupero il valore dal code
   var keychar = String.fromCharCode(keyCode);	
      
   var result = ((keyCode >= 48 && keyCode <= 57) || keyCode == 8 || keychar == IGCal_DateSep);	
      
    // in explorer quando è definito un DefaultButton, il javascript sul tag form va 
  	// a prevalere su quello definito sul controllo, quindi bisogna annullare
  	// il keyCode
  	if (!result && document.all)
  	  event.keyCode = 0;
  	  
   return result;
}

// evento onPaste del controllo Data
// su Firefox non esiste onPaste!
function IGCalDat_onPaste(e, obj) 
{	
	var clipData = window.clipboardData.getData("Text");	

  // Devo avere q.cosa da incollare
	if(clipData.length == 0)
	  return;
	  
  obj.value = trim(clipData);  
	var Valore = obj.value;
  
  // Ricavo il numero
  var valNum = parseInt(Valore);  
  
  if (!isNaN(valNum))
  {
	  obj.value = valNum;
	  obj.select();	    
  }
  else
    obj.value = "";
        
	return false;
}

// evento onFocus sul controllo Data
function IGCalDat_onFocus(e, obj) 
{
  // Non sono state inizializzate quindi lo faccio ora
	if (IGCal_DateFormat == "")
  {
	  IGCal_DateFormat = "dd/MM/yyyy";
	  IGCal_DateSep = "/";
    IGCal_DatePos_dd = 0;
    IGCal_DatePos_MM = 2;
    IGCal_DatePos_yyyy = 4;
  }

	var nuovaData = replace(trim(obj.value),IGCal_DateSep,"");
	obj.value = nuovaData;	
	obj.select();
	
	return true;
}


// effettua la fomattazione finale del testo inserito nel controllo data
// Se la stringa inserita non rappresenta una data, blocca l'uscita dal controllo
function IGCalDat_FinalFormatting(e, obj)
{
  var dd = "";
  var MM = "";
  var yyyy = "";
  var today = new Date();	
  var year = "" + today.getFullYear();
  
  
  // Elimino la formattazione con il separatore.
	//var valore = replace(trim(obj.value),IGCal_DateSep,"");
	var valore = trim(obj.value);
	if(valore == "")
		return true;

  var dateArray = valore.split(IGCal_DateSep);
  if (dateArray.length != 1 && dateArray.length != 3)
  {
  	FocusAndSelectTimeout(obj);
		return false;
  }

  if (dateArray.length > 1)
  {
    // sono nel caso in cui il testo contiene già il separatore  
    if (dateArray[0] == "" || dateArray[1] == "" || dateArray[2] == "")
    {
  	  FocusAndSelectTimeout(obj);
		  return false;
    }
    // WARNING il codice seguente supporta solo 2 tipi di formati: dd/MM/yyyy e MM/dd/yyyy
    if (IGCal_DatePos_dd == 0)
    {
      dd = dateArray[0];
      MM = dateArray[1];
    }
    else
    {
      dd = dateArray[1];
      MM = dateArray[0];
    }
    
    yyyy = dateArray[2];
  }
  else
  {
    // sono nel caso in cui il testo non contiene separatori
	  dd = valore.substr(IGCal_DatePos_dd,2);
	  MM = valore.substr(IGCal_DatePos_MM,2);
	  yyyy = valore.substr(IGCal_DatePos_yyyy,4);
  		
	  if(dd == "")
  	  dd = eval(today.getDate());
    		
	  if(MM == "")
		  MM = eval(today.getMonth())+1;
		  
		if(yyyy == "")
	    yyyy = year;
	}

  if(yyyy.length==1)
	  yyyy = year.substring(0,3) + yyyy;
		
  else if	(yyyy.length==2)	
	  yyyy = year.substring(0,2)+ yyyy;
		
  else if	(yyyy.length==3)		
	  yyyy = year.substring(0,1) + yyyy;
		  
	var dataCorretta;
	try
	{
	  dataCorretta = IGCal_dateCheck(eval(yyyy),eval(MM),eval(dd));
	}
	catch(e) {
	  FocusAndSelectTimeout(obj);
	  return false;
	}
	
	//controllo la correttezza della data	
	if (dataCorretta && yyyy < 3000 )
	{		
		if (dd < 10)
		  dd = "0" + eval(dd);
		  
		if (MM < 10)
		  MM ="0" + eval(MM);

		var valoreData = replace(IGCal_DateFormat,"dd",dd);
		valoreData = replace(valoreData,"MM",MM);
		valoreData = replace(valoreData,"yyyy",yyyy);
		
		var oldValue = obj.value;
		obj.value = valoreData;
		
		
		// questo è necessario per ovviare ad un bug di firefox: nel caso
		// obj.value sia modificato durante la onblur, onchange non viene
		// rilanciato, quindi lo devo rilanciare io manualmente.
		if (e && e.type == 'blur' && obj.value != oldValue)
		  fireOnChangeEvent(obj);
	}
	else	
	{
		FocusAndSelectTimeout(obj);
        return false;
	}

  return true;
}

// funzione interna per il check della data
function IGCal_dateCheck(y, m, d) 
{ 

	if(m != 0 && m <= 12 && m>0 && d>0 && y>0 && d!=0 && d<=31 )
	{ 
		//Controllo i mesi di 30 giorni
		if(m == 4 || m == 6 || m == 9 || m == 11)
		{ 
			if(d == 31)
				return false; 
		} 
		
		if(m == 2)
		{   // controllo per gli anni bisestili
			//Se è divisibile per 100 allora deve essere divisibile per 400
			if(parseInt(y)%100 == 0)
			{
				if(parseInt(y)%400 != 0 && d == 29)
					return false; 	
			}
			// se non è divisibile per 100 deve essre divisibile per 4
			if(parseInt(y)%4 != 0 && d == 29)
				return false; 
			// comunque non può avere né 30 né 31 giorni
			if(d > 29)
				return false; 
		} 		
		return true; 
	} 
	else 
		return false;
} 

// Recupera i valori degli attributi dall'html del controllo ora
function IGCal_Ora_Params(e, obj)
{
  var dec;  
	if(document.all) 
	{	
		// Explorer
		this.Formato = obj.attributes["FT"].value;
		this.Range = obj.attributes["RG"].value;		
	}	
	else
	{ 	
		// Gli altri		
		this.Formato = e.target.attributes["FT"].value;
		this.Range = e.target.attributes["RG"].value;				
	}
	
  this.Decimali = 2;
  this.Interi = 0;
}

// funzione necessaria a firefox per far funzionare il select
function FocusAndSelectTimeout(obj)
{
  setTimeout(function()
  {
    if(obj.focus)
      obj.focus();
    if(obj.select)
      obj.select();
  },15);
}

/*Funzioni per il webcontrol Ora */
/* per onKeyPress sicuramente formato orologio*/
function IGCalOra_onKeyPress(e, obj) 
{	
  var Valore = obj.value;
	var keyCode;
	
	var params = new IGCal_Ora_Params(e, obj);
	var Allow24HOnly = obj.getAttribute("Allow24HOnly").toLowerCase() == "true" ? true : false;
  
  // Estraggo gli attributi del controllo numero, recupero parametri in base al browser	
	if(document.all) 
		// Explorer
		keyCode = event.keyCode;
	else if (e.which)
	{ 
		// Gli altri
		keyCode = e.which;				
		
		// Caratteri speciali non gestiti che in Netscape valgono 0
		if (keyCode == 0)
			return true;
	}	
  
  // tasto invio
  if (keyCode == 13)
  {
   IGCalDat_onBlur(e, obj);
   return;
  }
  
  if (keyCode == 8 || isNaN(keyCode))
    return true;   
  
    
  // caso decimale ok per tutte le cifre
  if (keyCode >= 48 && keyCode <= 57 && params.Formato == '2')
    return true;
    
  // accetto i numeri se il controllo si trova in stato di errore (testo evidenziato)
  if (keyCode >= 48 && keyCode <= 57 && params.Formato == '1')
    if (document.selection) 
    {
      // for IE
      if (document.selection.createRange().text.length > 0)
        return true;
    }
    else 
      if (typeof obj.selectionEnd != 'undefined') 
        // for FF, Opera etc...
        if((obj.selectionEnd - obj.selectionStart) > 0)
          return true;

    
  var keychar = String.fromCharCode(keyCode); 
  
  var reg5d = /[0-9]{4}/;
   
	// controllo il meno per range illimitato e formato decimale
	var isMenoCorretto = (params.Range == '1' && params.Formato == '2') ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
	// controllo il separatore decimale per formato decimale
	var isSeparatoreCorretto = (params.Formato == '2') ? keychar == IGCal_SepDec && obj.value.indexOf(IGCal_SepDec) == -1 && obj.value != "" && obj.value != "-" : false;
	// controllo il separatore di tempo per formato orologio
	var isDuePuntiCorretto = (params.Formato == '1') ? keychar == IGCal_OraSep && obj.value.indexOf(IGCal_OraSep) == -1 && obj.value != "" : false;
	
	// cifra ok
	var checkDigit = (keyCode >= 48 && keyCode <= 57);
	
	// se cifra verifico che non sia il 5 numero inserito senza separatore di tempo (espressione in reg5d)
	if (checkDigit && params.Formato == '1' && Allow24HOnly && reg5d.test(obj.value))
	  checkDigit = false;
	  
	if (isMenoCorretto || isSeparatoreCorretto || isDuePuntiCorretto || checkDigit)
	  return true;
	else
	{
	  if (document.all)
	    event.keyCode = 0;
	  
	  return false;
	}
}

// onPaste del controllo ora
// su Firefox non esiste onPaste!
function IGCalOra_onPaste(e, obj) 
{	
	var clipData = window.clipboardData.getData("Text");	

  // Devo avere q.cosa da incollare
	if(clipData.length == 0)
	  return;
	  
	var Allow24HOnly = obj.getAttribute("Allow24HOnly").toLowerCase() == "true" ? true : false;
	  
  obj.value = trim(clipData);  
	var valoreTrim = obj.value;
	
	var params = new IGCal_Ora_Params(e, obj);
	
		// caso orologio
	if (params.Formato == '1')
	  return IGCalOra_Orologio_onPaste(obj, valoreTrim, Allow24HOnly);
	else
	  return IGCalOra_Decimale_onPaste(obj, valoreTrim, Allow24HOnly, params.Decimali, params.Range);
}

// funzione richiamata su onPaste del controllo ora in formato orologio
function IGCalOra_Orologio_onPaste(obj, valoreTrim, allow24HOnly)
{  
  var arr_ora;
  var newValue = valoreTrim;
  var esito = true;
  // controllo la posizione del separatore del tempo
  if (newValue.indexOf(IGCal_OraSep) >= 0)
  {
    arr_ora = newValue.split(IGCal_OraSep);
    if ((allow24HOnly && arr_ora[0].length > 2) || (allow24HOnly && parseInt(arr_ora[0]) > 23) || arr_ora[1].length > 2) 
      esito = false;

   
    newValue = newValue.replace(IGCal_OraSep, '')
  }
  
  // stringhe senza separatore maggiori di 24 ore
  if (allow24HOnly && newValue.length > 4)
    esito = false;
    
  obj.value = "";
  
  if (!esito)  
  {
    alert('Formato non corretto.');
    return false;
  }
    
  // Ricavo il numero
  var valNum = parseInt(newValue);   
  
  if (!isNaN(valNum))
  {
	  obj.value = valoreTrim;
	  obj.select();	    
  }    
        
	return false;
}

// Previene un paste di un valore non congruente con le impostazioni dell'ora decimale
// Se le impostazioni non coincidono sbianca il campo
function IGCalOra_Decimale_onPaste(obj, valoreTrim, Allow24HOnly, decimali, range) 
{	
  // Ricavo il numero
  var valNum = NaN;
  var Negativo = false;

  // Se dovesse contenere un separatore decimale lo trasformiamo in . per far funzionare il float
  valNum = parseFloat(replace(valoreTrim,IGCal_SepDec,"."));
  
  obj.value = "";
  if (!isNaN(valNum))
  {
    if (range == "2" && valNum < 0)
    {
      // Abbiamo richiesto un numero positivo ma ne stiamo incollando uno negativo
      alert('Questo campo non accetta numeri negativi.');
    }
    else
    {
      var divisore = Math.pow(10, decimali);
      valNum = Math.round (valNum*divisore)/divisore;
      
      var string_num = valNum.toString();
      
      //memorizzo se si tratta di un numero negativo
      if(string_num.charAt(0) == '-')
      {
        Negativo = true;
        string_num = string_num.substring(1);
      }	    
      
      var arr_num;
      // caso numero decimali inferiore al previsto
      if (string_num.indexOf('.') != -1)
      {
        if (arr_num[1].length < decimali)
        {
          for(var i=0; i < decimali - arr_num[1].length; i++)
           string_num += "0";
        }
      }
      else
      {
        string_num += ".";
        for (var i=0; i < decimali; i++)
         string_num += "0";
      }
    }
    // elimino il punto se appare come ultimo carattere
    if (string_num.charAt(string_num.length - 1) == '.')
      string_num = string_num.substring(0, string_num.length - 1);
      
    // rimetto il meno se l'avevo tolto
    if (Negativo)
      string_num = "-" + string_num;
    
    //in tutti gli altri casi il numero è ammesso
    obj.value += replace(string_num,".", IGCal_SepDec);
    obj.select();  
  }
    
	return false;
}


/*function IGCalOra_onFocus(e, obj) 
{
	var nuovaOra = replace(trim(obj.value),IGCal_OraSep,"");
	obj.value = nuovaOra;	
	obj.select();

	return true;
}*/
	
function IGCalOra_onBlur(e, obj) 
{
  IGCalOra_FinalFormatting(e, obj);
}

// gestisce la formattazione finale del testo inserito nel controllo Ora
function IGCalOra_FinalFormatting(e, obj)
{
	var Allow24HOnly = obj.getAttribute("Allow24HOnly").toLowerCase() == "true" ? true : false;
	// recupero i parametri
	var params = new IGCal_Ora_Params(e, obj);
	var valoreTrim = trim(obj.value);
	
	// caso orologio
	if (params.Formato == '1')
	  return IGCalOra_Orologio_FinalFormatting(obj, valoreTrim, Allow24HOnly);
	else
	  return IGCalOra_Decimale_FinalFormatting(obj, valoreTrim, Allow24HOnly, params.Decimali);
}

// funzione richiamata su onblur del controllo ora in formato orologio
function IGCalOra_Orologio_onBlur(obj, valoreTrim, allow24HOnly)
{
  IGCalOra_Orologio_FinalFormatting(obj, valoreTrim, allow24HOnly);
}

function IGCalOra_Orologio_FinalFormatting(obj, valoreTrim, allow24HOnly)
{
  var hh;
  var mm;
  
  if(valoreTrim == null || valoreTrim == "")
	  return true;
  
  // controllo della posizione del separatore ora
  // non ammesso 123:2 per solo 24 ore o 1:223
  if (valoreTrim.indexOf(IGCal_OraSep) >= 0)
  {
   var arr_ora = valoreTrim.split(IGCal_OraSep);
   if ((allow24HOnly && arr_ora[0].length > 2) || arr_ora[1].length >2)
   {
     FocusAndSelectTimeout(obj);
		 return false;
   }
   else
   { 
     if (arr_ora[0].length == 1)
      hh = "0" + arr_ora[0];
     else
      hh = arr_ora[0];
     if (arr_ora[1].length == 1)
      mm = "0" + arr_ora[1];
    else
      mm = arr_ora[1];  
   }
  }
  // non c'è il separatore
  else
  {  	
	  if (valoreTrim.length == 3)
    {
	    hh = "0" + valoreTrim.substr(0,1);
	    mm = valoreTrim.substr(1,2);
    }
    else if(valoreTrim.length == 2)
    {
	    hh = valoreTrim.substr(0,2);
	    mm = "";
    }
    else if(valoreTrim.length == 1)
    {
	    hh = "0" + valoreTrim.substr(0,1);
	    mm = "";
    }
    else
    {
	    hh = valoreTrim.substr(0, valoreTrim.length - 2);
	    mm = valoreTrim.substr(valoreTrim.length - 2, 2);
    }
	}
	
  if (mm == "")
	  mm = "00";
	
  if (allow24HOnly)
  {		
    if (parseInt(hh) < 24 && parseInt(hh) >= 00 && parseInt(mm) < 60 && parseInt(mm) >= 00 )
    {		
	    var valoreData = hh + IGCal_OraSep + mm;
	    obj.value = valoreData;
    }
    else	
    {
	    FocusAndSelectTimeout(obj);
	    return false;
	  }
  }
  else
  {
	  if (parseInt(mm) < 60 && parseInt(mm) >= 00)
	  {		
		  var valoreData = hh + IGCal_OraSep + mm;
		  obj.value = valoreData;
	  }
	  else	
	  {
		  FocusAndSelectTimeout(obj);
		  return false;
	  }
	
  }
  return true;  
}

// funzione richiamata su onblur del controllo ora in formato decimale
function IGCalOra_Decimale_onBlur(obj, valoreTrim, Allow24HOnly, decimali)
{
  IGCalOra_Decimale_FinalFormatting(obj, valoreTrim, Allow24HOnly, decimali);
}

function IGCalOra_Decimale_FinalFormatting(obj, valoreTrim, Allow24HOnly, decimali)
{
  // recupero il valore
  var valore = valoreTrim;
  
  // se c'è q.sa formatto a modo
  if (valore != null && valore != "")
  {
    // se non è impostato un separatore (mai!) ne imposto uno di default (italiano)
    if (IGCal_SepDec == "")
	    IGCal_SepDec = ",";
	  
	  // imposto il separatore  
	  var SepDecCode = IGCal_SepDec.charCodeAt(0);	
	  
	  // verrà eseguito sempre questo if perchè Decimali è fisso a 2
	  if (decimali > 0)
	  {
      // se c'è il separatore lo converto in punto
      if (valore.indexOf(IGCal_SepDec) != -1)
        valore = valore.replace(IGCal_SepDec, "."); 
        
      valore = parseFloat(valore).toFixed(decimali);  
	  }  
	  // se è stato settato l'attributo Allow24HOnly a true, permetto solo
	  // valori inferiori a 24
    if (Allow24HOnly)
    {
      if (parseFloat(valore) >= 24 || parseFloat(valore) <= -24)
      {
        FocusAndSelectTimeout(obj);
		    return false;
      }
    }
  }
	
	// rimetto il separatore giusto
	valore = valore.replace(".", IGCal_SepDec);
	
	// in caso di inizio con la virgola, inserita tramite click del mouse, aggiungo uno zero iniziale
	if(valore.indexOf(IGCal_SepDec) == 0)
	  valore = "0" + valore;
	
	obj.value = valore;
	return true; 
}

// Impostata su onKeyUp del controllo ora
// Formato decimale con 2 decimali
function IGCalOra_onKeyUp(e, obj)
{
  //recupero il valore compreso il tasto appena premuto
  var temp = trim(obj.value)  
  
	// recupero i parametri
	var params = new IGCal_Ora_Params(e, obj);
  
  // parte intera
  var reg0Str = '[0-9]*';
  
  // sempre questo if visto che decimali=2 per il controllo ora
  if (params.Decimali > 0)
    reg0Str += '\\' + IGCal_SepDec + '?[0-9]{0,' + params.Decimali + '}';
    
  reg0Str = params.Range == '1' ? '^-?' + reg0Str : '^' + reg0Str;
  //fine stringa
  reg0Str = reg0Str + '$';
  var reg0 = new RegExp(reg0Str);
  
  // se corretta non devo fare niente
  if (reg0.test(temp))
    return true;
  
  // se range illimitato elimino altri segni meno
  if (params.Range == '1')
  {
    var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
    //l'istruzione seguente è equivalente a new RegExp
    var reg2 = /-/g;
    temp = temp.replace(reg2, '');
    if (hasNegative)
      temp = '-' + temp;
    
    obj.value = temp;
    return true;
  }
  
}
