//
// *********************************************
//            checkForm - v. 05.20
// *********************************************
//
// Permette di controllare tutti i campi di ogni FORM presente in una pagina.
// Inserisce delle proprietà e dei metodi su ogni campo, di ogni form presente nella pagina.
// Inserisce nel onSubmit e nel onReset della Form il controllo dei campi.
// Lo stato di FORM modificata (nomform.changed) è un campo hidden, quindi è gestibile nel dopo ACTION.
// Definisce dei nuovi metodi per l'oggetto Array().
// Definisce dei nuovi metodi per l'oggetto Date().
// Definisce una FORM di nome JOLLY per poter evitare l'injecting, ved.: linkPost() e successive.
// Definisce delle function generiche.
// Inizializza la formattazione dei campi con KIND diverso da null.
//
// E' sufficiente chiamare il file /js/checkForm.js all'inizio della Vs pagina.
// Nel caso si volessero utilizzare i metodi e/o proprietà della form e/o dei campi è necessario chiamare
// la startCF() dopo la fine della form.
//
// AGGIORNAMENTI *********************
//
//   - Inserita l'opzione UNLOAD, per controllare l'uscita dalla pagina senza aver salvato i campi modificati.
//   - Corretto il controllo di campo modificato.
//   - Alleggerito il processo di caricamento.
//   - Inserito il metodo calcolaDifferenzaGiorniCommerciale.
//
// IMPORTANTE ************************
//
//   - Tutte le funzioni sono case sensitive, quindi fare attenzione a maiuscolo e minuscolo.
//   - Utilizzare la nomecampo.setValue() per assegnare un nuovo valore ad un campo e
//     non assegnare il valore direttamente, perchè si perde il controllo del campo.
//   - Inoltre utilizzare la nomecampo.getValue() per avere il valore del campo senza l'eventuale formattazione.
//   - Una volta eseguita la submit i campi vengo inviati senza formattazione.
//   - Se si deve eseguire il metodo .submit() è necessario utilizzare .submitForm() .
//
//
// PROPRIETÀ DELLE FORM **************
//
//   nomeform.changed			Input Hidden	TRUE se almeno un campo della FORM è stato modificato
//   							FALSE se nessun campo della FORM è stato modificato
//
//   nomeform.confirm			Boolean		TRUE richiede conferma al momento della submit
//   							FALSE non richiede conferma al momento della submit
//   					String		Richiede conferma utilizzando come messaggio il valore di confirm
//
//   nomeform.unload			Boolean		FALSE non controlla l'uscita dalla pagina con campi modificati
//   							TRUE controlla l'uscita dalla pagina con campi modificati
//
//   nomeform.waiting			Function	Viene eseguita la funzione durante la submit, ideale per un messaggio tipo "attendere operazione in corso..."
//
//   nomeform.onCancel			Function	Viene eseguita la funzione se viene annullata l'esecuzione della submit, ideale per ripristinare dei valori settati prima di un submit
//
//   nomeform.isCancel			Boolean		TRUE l'esecuzione della submit non è stata confermata
//   							FALSE l'esecuzione della submit è stata confermata
//
//   nomeform.onError			Function	Viene eseguita la funzione se va in errore l'esecuzione della submit, ideale per ripristinare dei valori settati prima di un submit
//
//   nomeform.isError			Boolean		TRUE l'esecuzione della submit è andata in errore
//   							FALSE l'esecuzione della submit è andata in errore
//
//   nomeform.fieldsMandatory		Boolean		TRUE i campi obbligatori sono da gestire
//   							FALSE i campi obbligatori non sono da gestire
//
//   nomeform.fieldsMandatoryColor	String 		Colore del testo dei campi obbligatori
//   nomeform.fieldsMandatoryBgColor	String 		Colore di sfondo dei campi obbligatori
//
//   nomeform.fieldsChanged		Boolean		TRUE i campi vengono evidenziati se modificati
//   							FALSE i campi non vengono evidenziati se modificati
//
//   nomeform.fieldsChangedColor	String 		Colore del testo dei campi modificati
//   nomeform.fieldsChangedBgColor	String 		Colore di sfondo dei campi modificati
//
//   nomeform.changedFields		Array 		Array con i nomi dei campi modificati
//
//   nomeform.wrongFields		Array 		Array con i nomi dei campi sbagliati
//
//   nomeform.fieldsMarker		Boolean		TRUE i campi vengono evidenziati all'onFocus
//   							FALSE i campi non vengono evidenziati all'onFocus
//
//   nomeform.fieldsMarkerColor		String 		Colore del testo dei campi evidenziati
//   nomeform.fieldsMarkerBgColor	String 		Colore di sfondo dei campi evidenziati
//
//   nomeform.fieldsBaseColor		String 		Colore base del testo dei campi
//   nomeform.fieldsBaseBgColor		String 		Colore base di sfondo dei campi
//
//
// METODI DELLE FORM *****************
//
//   nomeform.submitForm()		Void		Esegue il controllo onSubmit() e poi la submit()
//
//   nomeform.onSubmitForm()		Boolean		TRUE tutto ok prosegui con la submit()
//   							FALSE è stato rilevato un errore non eseguire la submit()
//
//   nomeform.isWrong()			Boolean		TRUE se ci sono dei campi sbagliati nella form
//   							FALSE se i campi nella form sotto tutti corretti
//
//   nomeform.wrongMsg()		Void		Se c'è almeno un campo sbagliato visualizza l'alert e si posiziona sul primo campo errato
//
//
// PROPRIETÀ DEI CAMPI ***************
//
//   nomefield.title			String		Contiene il nome descrittivo di un campo
//
//   nomefield.kind			String		Contiene il tipo di un campo
//							VALUTA
//							VALUTAINTERA
//							DATA
//							NUMERO -> vedere .decimali e .migliaia
//							EMAIL
//							ABI
//							CAB
//							CAP
//							CODICEFISCALE
//							PIVA
//							LETTERE
//							LETTERESPAZIO
//							ORA
//
//							di futura implementazione
//							TELEFONO
//
//   nomefield.baloonHelp		String		Visualizza il testo sottoforma di Baloon Help gestito con onMouseOver e onMouseOut
//
//   nomefield.changed			Boolean		TRUE se il campo è stato modificato
//   							FALSE se nessun campo della FORM è stato modificato
//
//   nomefield.mandatory		Boolean		TRUE se il campo è obbligatorio
//   							FALSE se il campo NON è obbligatorio
//
//   nomefield.oldValue			Field		Contiene il valore iniziale del campo
//
//   nomefield.transform		String		Varia il "case" del testo contenuto nel campo
//							Esempi:
//							NORMAL -> valore di default, il test non subisce variazioni
//							UPPER -> il testo viene trasformato in MAIUSCOLO
//							LOWER -> il testo viene trasformato in minuscolo
//							CAP -> il testo viene trasformato in Maiuscolo solo la prima lettera di ogni frase
//							CAPALL -> il testo viene trasformato in Maiuscolo solo la prima lettera di ogni parola
//
//   nomefield.maxlength		String		Quantità max di caratteri ammessi
//							N.B. Solo per type=TEXTAREA
//
//   nomefield.decimali			String		Quantità di cifre decimali ammesse
//							N.B. Solo per kind=NUMERO
//							Esempi:
//							999 -> Tre cifre decimali 'forzate', inserisce degli zeri nel caso sia meno di tre
//							NNN -> Tre cifre decimali 'libere'
//
//   nomefield.migliaia			Boolean		TRUE se il campo deve gestire il separatore delle migliaia
//   							FALSE se il campo deve gestire il separatore delle migliaia
//							N.B. Solo per kind=NUMERO/VALUTA/VALUTAINTERA
//
//   nomefield.exceptionok		String		Nome della funzione js che verifica delle eccezioni valide
//							N.B. Esempio exceptionok="test"
//
//   nomefield.exceptionko		String		Nome della funzione js che verifica delle eccezioni NON valide
//							N.B. Esempio exceptionko="test"
//
//   nomefield.testurl			String		Url da impiegare per il controllo del campo
//							Esempio : testurl="testSql.jsp?nome="
//							N.B. Vedere metodo testFunction()
//
//   nomefield.testframe		String		Frame da impiegare per il controllo del campo
//							Il frame di default "sql"
//							N.B. Vedere metodo testFunction()
//
//   nomefield.testResult		Boolean		E' l'attributo da settare per indicare il risultato eseguito da testFunction()
//							TRUE i
//							N.B. Vedere metodo testFunction()
//
//   nomefield.valuene			General		Deve contenere un valore diverso "!=" da
//   nomefield.valueeq			General		Deve contenere un valore uguale "==" a
//   nomefield.valuelt			General		Deve contenere un valore minore "<" di
//   nomefield.valuele			General		Deve contenere un valore minore o uguale "<=" di
//   nomefield.valuege			General		Deve contenere un valore maggiore o uguale ">=" di
//   nomefield.valuegt			General		Deve contenere un valore maggiore ">" di
//   nomefield.valuemod			General		Deve contenere un valore modulo "%" di
//			   				N.B. Nel caso di kind=DATA è possibile usare OGGI o TODAY
//                   
//   nomefield.calendar			Boolean		TRUE abilita la gestione del Calendario in caso di kind=DATA
//   							FALSE disabilita la gestione del Calendario in caso di kind=DATA
//
//   nomefield.baseColor		String		Contiene il valore iniziale del colore del testo del campo
//   nomefield.baseBgColor		String		Contiene il valore iniziale del colore dello sfondo del campo
//
//   nomefield.multicolor		String		Contiene il valore del colore dello 2° sfondo delle scelte
//							N.B. Solo per i campi di tipo SELECT
//
//
// METODI DEI CAMPI ******************
//
//   nomefield.testFunction()		Boolean		Verifica il contenuto del campo in base
//							Restituisce
//							FALSE, segnala valore non corretto
//							TRUE, prosegue con il normale controllo in base al kind
//							N.B. Vedi testurl e testframe
//
//   nomefield.isWrong()		String		Restituisce il tipo di errore sul campo
//							""		Il campo non ha errori
//							EMPTY		Il campo è vuoto
//							VALUE		Il campo non ha un valore corretto
//							RANGE		Il campo è fuori dal range impostato
//							FORMAT		Il campo non ha un formato corretto
//
//   nomefield.wrongMsg()		String		Se il campo è sbagliato restituisce la descrizione del relativo errore
//
//   nomefield.isChanged()		Boolean		TRUE se il campo è stato modificato
//   							FALSE se il campo non è stato modificato
//
//   nomefield.setMandatory(valore)	Void		Setta il campo in obbligatorio (true) o non obbligatorio (false)
//
//   nomefield.reset()			Field		Riporta al valore iniziale il campo, resetta l'eventuale errore e resituisce il valore oldValue
//
//   nomefield.setValue(valore [,forceCheck])
//					Void		Assegna un nuovo valore al campo e lo formatta in base all'eventuale kind
//							Se forceCheck è TRUE esegue il controllo del valore inserito
//
//   nomefield.getValue([perDB])	Field		Restituisce il valore di un campo -> Vedere anche la getValueText()
//							Se perDB FALSE lascia i numeri con separatore decimale ",": valore di default
//							Se perDB TRUE  lascia i numeri con separatore decimale "."
//
//   nomefield.getValueText()		String		Restituisce il valore "testuale" di un campo
//
//   nomefield.getValueNumber()		Float		Restituisce il valore "numerico" di un campo.
//							Solo per NUMERO, VALUTA, VALUTAINTERA
//
//
// FUNZIONI GENERICHE ****************
//
//   resetFieldsFormat(nomeform)	Void		Resetta il formato dei campi un istante prima della submit
//
//   setFieldsMandatory(nomeform)	Void		Dice alla form di gestire i campi obbligatori
//
//   setFieldsNotMandatory(nomeform)	Void		Dice alla form di non gestire i campi obbligatori
//
//   whoIsChecked(nomefield)		Integer		Ritorna il valore checked dei un campo di tipo radio, -1 se nessun opzione è checked
//
//   setOldValueField(nomefield)	Void		Setta l'attuale valore delcampo in oldValue
//
//   formatDoubleCF(valore,
//		ndecimali, tipo, )
//		noMigliaia)		String		Formatta un numero con i decimali
//
//   formatIntegerCF(valore, 
//		tipo, )
//		noMigliaia)		String		Formatta un numero intero
//
//   isDataRealeCF(dataValore)		Boolean		Verifica se la data passata è valida
//
//   isOraRealeCF(oraValore)		Boolean		Verifica se l'ora passata è valida
//
//   isEmailRealeCF(valore)		Boolean		Verifica se la email passata può considerarsi valida
//
//   isCodiceFiscaleRealeCF(valore)	Boolean		Verifica se il codice fiscale passato può considerarsi valido
//
//   isPartitaIvaRealeCF(valore)	Boolean		Verifica se la parita iva passata può considerarsi valida
//
//   addDayCF(data, delta)		String		Aggiunge (o Sotrae) delta giorni alla data, formato GG/MM/AAAA
//
//   addMonthCF(data, delta)		String		Aggiunge (o Sotrae) delta mesi alla data, formato GG/MM/AAAA
//
//   addYearCF(data, delta)		String		Aggiunge (o Sotrae) delta anni alla data, formato GG/MM/AAAA
//
//   replaceChrCF(stringa,
//		carattereDaTrovare,
//		carattereDaSostituire)	String		Sostituisce uno o più caratteri con uno o più altri caratteri in una stringa
//
//   replicateChrCF(carattere,
//			lunghezza)	String		Restituisce una stringa contenente un carattere ripetuto n volte
//
//   trimCF(stringa)			String		Elimina tutti i blank all'inizio e alla fine della stringa
//
//   enableOptionCF(nomefield,
//			strBy,
//			valore)		Boolean		Disabilita una voce da un campo combobox (o lista)
//
//   disableOptionCF(nomefield,
//			strBy,
//			valore)		Boolean		Riabilita una voce da un campo combobox (o lista)
//
//   removeOptionCF(nomefield,
//			strBy,
//			valore)		Boolean		Elimina definitivamente una voce da un campo combobox (o lista)
//
//   addOptionCF(nomefield,
//			valore,
//			descrizione)	Boolean		Aggiunge una voce ad un campo combobox (o lista)
//
//   showCF(nomeObj)			String		Rende visibile l'oggetto nomeObj
//
//   hideCF(nomeObj)			String		Rende non visibile l'oggetto nomeObj
//
//   expandCF(nomeObj)			String		Rende visibile l'oggetto nomeObj, espandendo l'area di visualizzazione
//
//   collapseCF(nomeObj)		String		Rende non visibile l'oggetto nomeObj, collassando l'area di visualizzazione
//
//   moveCF(nomeObj, x, y)		String		Riposiziona l'oggetto obj in base a xL e yL
//
//   dataConverterCF(			String		Convert il formato di una data
//			valore,
//			[separatore,
//			[formatoDa,
//			[formatoA]]])
//
//   calcolaEtaAttuarialeCF(		String		Calcola l'età attuariale data la data di nascita rispetto alla data di decorrenza, tutte le date sono nel formato GG/MM/AAAA
//                   dataNascita,
//                   dataDecorrenza)
//
//   linkPost(strLink, [targetFrame])	String		Esegue il link in modalità POST, protegge dall'injecting
//
//   addFieldCF(			String		Aggiunge un campo ad una FORM
//			form,
//			type,
//			field,
//			value)
//
//   removeFieldCF(form, field)		String		Rimuove un campo ad una FORM
//
//   getFieldCF(form, field)		String		Restituisce il campo di una FORM
//
//   toggleFieldCF(form, field)		String		Aggiunge/Rimuove un campo ad una FORM
//
//
// NUOVI METODI PER Oggetti "base" ***********
//
//
//  Date.addDay(giorni)			Void		Aggiunge/Sottrae dei giorni alla data
//
//
//  Date.addMonth(mesi [, solare])	Void		Aggiunge/Sottrae dei mesi alla data
//
//
//  Date.addYear(anni [, solare])	Void		Aggiunge/Sottrae degli anni alla data
//
//
//  Date.getGiorno()			String		Restituisce il giorno con l'eventuale 0 davanti
//
//
//  Date.getMese()			String		Restituisce il mese con l'eventuale 0 davanti
//
//
//  Date.getAnno()			String		Restituisce l'anno con l'eventuale 19 davanti
//
//
//  Date.setGiorno(giorno)		String		Setta il giorno nella data, anche con 0 davanti
//
//
//  Date.setMese(mese)			String		Setta il giorno nella data, anche con 0 davanti
//
//
//  Date.setAnno(anno)			String		Setta il giorno nella data, anche con 0 davanti
//
//
//  Date.getLastDay()			Numeric		Restiruisce l'ultimo giorno del mese
//
//
//  Date.isBisestile()			Boolean		TRUE l'anno è bisestile
//							FALSE l'anno non è bisestile
//
//
//  Date.getDataFormattata(		Void		Restituisce la data nel formato richiesto
//			[formato
//			[, separatore]])
//
//
//  Date.setDataFormattata(		Void		Setta la data leggendola nel formato passato
//			valore
//			[,formato])
//
//
//  Date.calcolaDifferenzaGiorni(	Numeric		Restituisce il numero di giorni tra le due date
//			valore
//			[,formato])
//
//
// Date.calcolaDifferenzaGiorniCommerciale(
//					Numeric		Restituisce il numero di giorni tra le due date
//							in Anno Commerciale (considera i mesi tutti di 30gg)
//							può restituire anche un valore negativo
//			valore
//			[,formato])
//
//
//  Date.calcolaDifferenzaMesi(		Numeric		Restituisce il numero di mesi tra le due date
//			valore
//			[,formato])
//
//
//  Date.calcolaDifferenzaAnni(		Numeric		Restituisce il numero di anni tra le due date
//			valore
//			[,formato])
//
//
//  Date.calcolaEta(			Numeric		Restituisce l'età
//			valore
//			[,tipoData
//			[,formato]])
//
//
//  Date.calcolaEtaAttuariale(		Numeric		Restituisce l'età attuariale
//			valore
//			[,tipoData
//			[,formato]])
//
//
//  Array.search(			Numeric		Restituisce l'indice in cui si trova il valore
//			valore)				Accetta anche il carattere jolly '%'
//
//
//
//  Array.add(				Void		Accoda in un Array la stringa passata
//			valore)
//
//
//  String.toCapitalize(		String		Trasforma in maiuscolo una stinga
//			sentece				se è FALSE lavora sulle parole [default]
//							se è TRUE lavora sulle frasi
//			[,forceLower])			se è FALSE lascia i caratteri maiuscoli inalterati [default]
//							se è TRUE forza i rimanenti caratteri in muniscolo
//
//
//  Math.roundTo(			Numeric		Restituisce un valore arrotondato sulla base di decimali
//			valore
//			,decimali)
//
//
// ******* NOTA BENE *******************************************
//
//  (*) FUNZIONI O VALORI NON ANCORA DIPSONIBILI
//



//
// INIZIALIZZAZIONE DELLA checkForm.js *********
//
var submitFlag = false;

var documentOnLoad = '';
var documentOnLoadFind = 0;
var initializedCF = false;

if (window.onload != null)
{
  documentOnLoad = window.onload;
  documentOnLoadFind = documentOnLoad.toString().indexOf('{');
  documentOnLoad = documentOnLoad.toString().substr(documentOnLoadFind+1, (documentOnLoad.toString().length - documentOnLoadFind - 3) );
}
window.onload = new Function('startCF();'+documentOnLoad);

var documentOnBeforeUnload = '';
var documentOnBeforeUnloadFind = 0;

if (window.onbeforeunload != null)
{
  documentOnBeforeUnload = window.onbeforeunload;
  documentOnBeforeUnloadFind = documentOnBeforeUnload.toString().indexOf('{');
  documentOnBeforeUnload = documentOnBeforeUnload.toString().substr(documentOnBeforeUnloadFind+1, (documentOnBeforeUnload.toString().length - documentOnBeforeUnloadFind - 3) );
}
window.onbeforeunload = new Function('var rExitCF = exitCF(); if ((submitFlag == false) && (rExitCF != \'\')) return \'Sono stati modificati dei campi!\'; '+documentOnBeforeUnload);
//window.onbeforeunload = new Function('var rExitCF = exitCF(); if ((submitFlag == false) && (rExitCF != \'\')) return \'Sono stati modificati dei campi!\\n\'+rExitCF; '+documentOnBeforeUnload);


//
// Esegue l'inizializzazione della checkForm
//
function startCF()
{
  if (initializedCF == false) // Per evitare di ripetere l'inizializzazione
  {
    var i = 0;
  
    maschere = document.forms;
    for (i=0; i<maschere.length; i++)
    {
      initForm(maschere[i]);
    }
    initializedCF = true;
  }
}


//
// Controlla all'uscita dalla pagina se ci sono campi modificati
//
function exitCF()
{
  var Ritorna = '';
  var aCampi = new Array();

  if (initializedCF == true) // Per evitare di controllare prima che finisca la pagina
  {
    var i = 0;
  
    maschere = document.forms;
    for (i=0; i<maschere.length; i++)
    {
      if ((maschere[i].changed == true) && (maschere[i].unload == true))
      {
        aCampi.push('document.'+maschere[i].name+'.'+maschere[i].changedFields.join(',\n')+'\n');
        Ritorna = Ritorna + ' - ' + aCampi.join(',\n');
      }
    }
  }

/*
  if (Ritorna == true)
    return aCampi.join('\n');
  else

  if (Ritorna == true)
    alert(aCampi.join('\n'));
*/
    return Ritorna;
}


//
// Inizializza la formattazione di tutti i campi in base al tipo di KIND prescelto,
// in modo tale da avere una visualizzazione corretta anche se viene caricato un valore con VALUE="".
//
function initFormat() {
	var maschere = document.forms;
	for (var i = 0; i < maschere.length; i++)
	{
		var campi = maschere[i].elements;
		for (var j = 0; j < campi.length; j++)
		{
			initFormatField(campi[j]);
		}
	}
}


//
// Inizializza la formattazione di un campi in base al tipo di KIND prescelto,
// in modo tale da avere una visualizzazione corretta anche se viene caricato un valore con VALUE="".
// Inoltre, carica il valore di oldValue, per avere una corretta gestione delle isChanged().
//
function initFormatField(thisField) {

	if(thisField.kind != null)
	{
		if(thisField.value != '')
		{
			thisField.setValue(thisField.getValue());
		}
	}
}


//
// Modifica l'Eventi Handler di ogni campo aggiungendo la chiamata a onChangeField,
// inoltre inizializza il valore di Changed e dell'Array changedFields della form
//
function initForm(thisForm)
{
  var i = 0, j = 0;

  changed = new Object("thisForm.Hidden");
  thisForm.changed = false;

  if (typeof thisForm.confirm == 'undefined')
  {
    thisForm.confirm = new Boolean();
    thisForm.confirm = true;
  }
  else
  {
    switch (thisForm.confirm.toLowerCase())
    {
      case 'true' :
      case 'vero' :
      case 'si' :
      case 's' :
      case 'yes' :
      case 'y' :
      case '1' :
        thisForm.confirm = true;
        break;
      case 'false' :
      case 'falso' :
      case 'no' :
      case 'n' :
      case '0' :
        thisForm.confirm = false;
        break;
      default :
    }
  }

  if (typeof thisForm.unload == 'undefined')
  {
    thisForm.unload = new Boolean();
    thisForm.unload = false;
  }
  else
  {
    switch (thisForm.unload.toLowerCase())
    {
      case 'true' :
      case 'vero' :
      case 'si' :
      case 's' :
      case 'yes' :
      case 'y' :
      case '1' :
        thisForm.unload = true;
        break;
      case 'false' :
      case 'falso' :
      case 'no' :
      case 'n' :
      case '0' :
        thisForm.unload = false;
        break;
      default :
    }
  }

  if (typeof thisForm.waiting != 'undefined')
  {
    thisForm.waiting = new Function(thisForm.waiting);
  }

  if (typeof thisForm.onCancel != 'undefined')
  {
    thisForm.onCancel = new Function(thisForm.onCancel);
  }

  thisForm.isCancel = new Boolean(false);

  if (typeof thisForm.onError != 'undefined')
  {
    thisForm.onError = new Function(thisForm.onError);
  }

  thisForm.isError = new Boolean(false);

  if (typeof thisForm.fieldsMandatory == 'undefined')
  {
    thisForm.fieldsMandatory = new Boolean();
    thisForm.fieldsMandatory = true;
  }
  else
  {
    switch (thisForm.fieldsMandatory.toLowerCase())
    {
      case 'true' :
      case 'vero' :
      case 'yes' :
      case 'y' :
      case 'si' :
      case 's' :
      case '1' :
        thisForm.fieldsMandatory = true;
        break;
      default :
        thisForm.fieldsMandatory = false;
    }
  }

  if (typeof thisForm.fieldsMandatoryColor == 'undefined')
  {
    thisForm.fieldsMandatoryColor = new String("white");
  }

  if (typeof thisForm.fieldsMandatoryBgColor == 'undefined')
  {
    thisForm.fieldsMandatoryBgColor = new String("red");
  }

  if (typeof thisForm.fieldsChanged == 'undefined')
  {
    thisForm.fieldsChanged = new Boolean();
    thisForm.fieldsChanged = false;
  }
  else
  {
    switch (thisForm.fieldsChanged.toLowerCase())
    {
      case 'true' :
      case 'vero' :
      case 'si' :
      case 'yes' :
      case 'y' :
      case 's' :
      case '1' :
        thisForm.fieldsChanged = true;
        break;
      default :
        thisForm.fieldsChanged = false;
    }
  }

  if (typeof thisForm.fieldsChangedColor == 'undefined')
  {
    thisForm.fieldsChangedColor = new String("black");
  }

  if (typeof thisForm.fieldsChangedBgColor == 'undefined')
  {
    thisForm.fieldsChangedBgColor = new String("beige");
  }

  if (typeof thisForm.fieldsBaseColor == 'undefined')
  {
    thisForm.fieldsBaseColor = new String("black");
  }

  if (typeof thisForm.fieldsBaseBgColor == 'undefined')
  {
    thisForm.fieldsBaseBgColor = new String("#E0E0E0");
  }

  if (typeof thisForm.fieldsMarker == 'undefined')
  {
    thisForm.fieldsMarker = new Boolean();
    thisForm.fieldsMarker = false;
  }
  else
  {
    switch (thisForm.fieldsMarker.toLowerCase())
    {
      case 'true' :
      case 'vero' :
      case 'yes' :
      case 'y' :
      case 'si' :
      case 's' :
      case '1' :
        thisForm.fieldsMarker = true;
        break;
      default :
        thisForm.fieldsMarker = false;
    }
  }

  if (typeof thisForm.fieldsMarkerColor == 'undefined')
  {
    thisForm.fieldsMarkerColor = new String("navy");
  }

  if (typeof thisForm.fieldsMarkerBgColor == 'undefined')
  {
    thisForm.fieldsMarkerBgColor = new String("lightyellow");
  }

  thisForm.wrongFields = new Array();
  thisForm.isWrong = new Function('return (this.wrongFields.length>0);');
  thisForm.wrongMsg = new Function('return strWrong(this);');

  thisForm.changedFields = new Array();

  campi=thisForm.elements;

//Aggiungo la submitForm per effettuare il controllo sulla onSumit()
  thisForm.submitForm = new Function('submitForm(this);');

//Aggiungo su onSubmit il testFields()
  actualOnChangeNext = '';
  if (thisForm.onsubmit != null)
  {
    actualOnChange = thisForm.onsubmit;
    actualOnChangeFind = actualOnChange.toString().indexOf('{');
    actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
    actualOnChangeNext = 'submitFlag = true; testFields(this); if (onSubmitForm(this) == false) return false; ' + actualOnChangeNext + '; if (typeof this.waiting != \'undefined\') this.waiting(); resetFieldsFormat(this); return true; ';
    thisForm.onsubmit = new Function(actualOnChangeNext);
  }
  else
  {
    thisForm.onsubmit = new Function('submitFlag = true; testFields(this); if (onSubmitForm(this) == false) return false;  if (typeof this.waiting != \'undefined\') this.waiting(); resetFieldsFormat(this); return true; ' );
  }

//Aggiungo su onReset il resetFields()
  actualOnChangeNext = '';
  if (thisForm.onreset != null)
  {
    actualOnChange = thisForm.onreset;
    actualOnChangeFind = actualOnChange.toString().indexOf('{');
    actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
  }
  thisForm.onreset = new Function('resetFields(this);'+actualOnChangeNext);

  for (i=0; i<campi.length; i++)
  {

    actualOnChangeNext = '';

/*
    Aggiungo su onKeyDown il controllo sui tasti BACKSPACE e RETURN
    e inoltre altri controlli in base al kind
*/
    actualOnChangeNext = '';
    if (campi[i].onkeydown != null)
    {
      actualOnChange = campi[i].onkeydown;
      actualOnChangeFind = actualOnChange.toString().indexOf('{');
      actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
    }
    campi[i].onkeydown = new Function('onKeyField(this, event); '+actualOnChangeNext);

    switch (campi[i].type.toUpperCase())
    {
      case 'HIDDEN' :
      case 'SUBMIT' :
      case 'IMAGE' :
      case 'RESET' :
      case 'BUTTON' :
	break;
      case 'RADIO' :
        actualOnChangeNext = '';
        if (campi[i].onclick != null)
        {
          actualOnChange = campi[i].onclick;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onclick = new Function('onChangeField(this);'+actualOnChangeNext);

        actualOnChangeNext = '';
        if (campi[i].onfocus != null)
        {
          actualOnChange = campi[i].onfocus;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onfocus = new Function('if (this.form.fieldsMarker==true) setColorField(this, this.form.fieldsMarkerColor, this.form.fieldsMarkerBgColor ); '+actualOnChangeNext);

        actualOnChangeNext = '';
        if (campi[i].onblur != null)
        {
          actualOnChange = campi[i].onblur;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onblur = new Function('setColorField(this);'+actualOnChangeNext);

        campo=document.getElementsByName(campi[i].name);

        actualOnChangeNext = '';
        if (campi[i].onmouseover != null)
        {
          actualOnChange = campi[i].onmouseover;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onmouseover = new Function('baloonHelpCF(this); '+actualOnChangeNext);
      
        actualOnChangeNext = '';
        if (campi[i].onmouseout != null)
        {
          actualOnChange = campi[i].onmouseout;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onmouseout = new Function('baloonHelpCF(false); '+actualOnChangeNext);

        initField(campi[i]);
        break;

      case 'SELECT-ONE' :
      case 'SELECT-MULTIPLE' :
        actualOnChangeNext = '';
        if (campi[i].onclick != null)
        {
          actualOnChange = campi[i].onclick;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onclick = new Function('onChangeField(this);'+actualOnChangeNext);

        actualOnChangeNext = '';
        if (campi[i].onfocus != null)
        {
          actualOnChange = campi[i].onfocus;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onfocus = new Function('if (this.form.fieldsMarker==true) setColorField(this, this.form.fieldsMarkerColor, this.form.fieldsMarkerBgColor ); '+actualOnChangeNext);

        actualOnChangeNext = '';
        if (campi[i].onblur != null)
        {
          actualOnChange = campi[i].onblur;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
//        campi[i].onblur = new Function('setColorField(this);'+actualOnChangeNext);
        campi[i].onblur = new Function('onBlurField(this, ((typeof(document.all.overDiv.style)!="undefined") && (document.all.overDiv.style.visibility=="visible"))); setColorField(this);'+actualOnChangeNext);

        actualOnChangeNext = '';
        campo=document.getElementsByName(campi[i].name);

        actualOnChangeNext = '';
        if (campi[i].onmouseover != null)
        {
          actualOnChange = campi[i].onmouseover;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onmouseover = new Function('baloonHelpCF(this); '+actualOnChangeNext);
      
        actualOnChangeNext = '';
        if (campi[i].onmouseout != null)
        {
          actualOnChange = campi[i].onmouseout;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onmouseout = new Function('baloonHelpCF(false); '+actualOnChangeNext);

        initField(campi[i]);
        break;

      default :
        actualOnChangeNext = '';
        if (campi[i].onchange != null)
        {
          actualOnChange = campi[i].onchange;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onchange = new Function('onChangeField(this);'+actualOnChangeNext);

        actualOnChangeNext = '';
        if (campi[i].onfocus != null)
        {
          actualOnChange = campi[i].onfocus;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onfocus = new Function('onFocusField(this); if (this.form.fieldsMarker==true) setColorField(this, this.form.fieldsMarkerColor, this.form.fieldsMarkerBgColor ); this.select(); '+actualOnChangeNext);

        actualOnChangeNext = '';
        if (campi[i].onblur != null)
        {
          actualOnChange = campi[i].onblur;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onblur = new Function('onBlurField(this, ((typeof(document.all.overDiv.style)!="undefined") && (document.all.overDiv.style.visibility=="visible"))); setColorField(this);'+actualOnChangeNext);

        actualOnChangeNext = '';
        if (campi[i].onmouseover != null)
        {
          actualOnChange = campi[i].onmouseover;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onmouseover = new Function('baloonHelpCF(this); '+actualOnChangeNext);
      
        actualOnChangeNext = '';
        if (campi[i].onmouseout != null)
        {
          actualOnChange = campi[i].onmouseout;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        campi[i].onmouseout = new Function('baloonHelpCF(false); '+actualOnChangeNext);

        initField(campi[i]);
    }
  }
}

//
// Crea tutti i metodi e le proprietà di un campo.
// Setta i valori iniziali delle proprietà da inizializzare.
//
function initField(thisField)
{

  var i =0;

  if (thisField.type.toUpperCase() == 'RADIO')
  {
    campo = document.getElementsByName(thisField.name);
    for (i=0; i<campo.length; i++)
    {
      campo[i].setValue = new Function('valore', 'forceCheck', 'setValue(this, valore, forceCheck)');
      campo[i].getValue = new Function('return getValue(this)');
      campo[i].getValueText = new Function('return getValueText(this)');
      campo[i].getValueNumber = new Function('return getValueNumber(this)');

      if (typeof campo[i].kind == 'undefined')
	      campo[i].kind = new String('');

      campo[i].isWrong = new Function('return isWrongField(this)');

      campo[i].wrongMsg = new Function('if (strWrongField(this) != "") alert(strWrongField(this));');

      oldValue = new Object("campo[i]");
      campo[i].oldValue = whoIsChecked(thisField);

      if (typeof campo[i].mandatory == 'undefined')
      {
        mandatory = new Boolean("campo[i]");
        campo[i].mandatory = false;
      }
      else
      {
        if (typeof(campo[i].mandatory) == 'string')
        {
          switch (campo[i].mandatory.toLowerCase())
          {
            case 'true' :
            case 'vero' :
            case 'yes' :
            case 'y' :
            case 'si' :
            case 's' :
            case '1' :
              campo[i].mandatory = true;
              break;
            default :
              campo[i].mandatory = false;
          }
        }
        else
        {
          switch (campo[i].mandatory)
          {
            case true :
            case 1 :
              campo[i].mandatory = true;
              break;
            default :
              campo[i].mandatory = false;
          }
        }
      }

      baseColor = new String("campo[i]");
      campo[i].baseColor = campo[i].style.color ;

      baseBgColor = new String("campo[i]");
      campo[i].baseBgColor = campo[i].style.background ;

      changed = new Boolean("campo[i]");
      campo[i].changed = false;
      campo[i].isChanged = new Function('return testField(this)');

      campo[i].setMandatory = new Function('valore', 'if (valore) {setMandatory(this);} else {setNotMandatory(this)};');

      campo[i].reset = new Function('return resetField(this)');

    }
    xmandatory = false;
    for (i=0; i<campo.length; i++)
    {
      xmandatory = (xmandatory || campo[i].mandatory);
    }
    for (i=0; i<campo.length; i++)
    {
      campo[i].mandatory = xmandatory;
    }
  }
  else
  {
    thisField.setValue = new Function('valore', 'forceCheck', 'setValue(this, valore, forceCheck)');
    thisField.getValue = new Function('perDb', 'return getValue(this, perDb)');
    thisField.getValueText = new Function('return getValueText(this)');
    thisField.getValueNumber = new Function('return getValueNumber(this)');

    if (typeof thisField.kind == 'undefined')
      thisField.kind = new String('');

    thisField.isWrong = new Function('return isWrongField(this)');

    thisField.wrongMsg = new Function('if (trimCF(strWrongField(this)) != "") alert(strWrongField(this));');

    if (typeof thisField.testurl == 'undefined')
    {
      thisField.testFunction = new Function('return true;');
    }
    else
    {
      if (typeof thisField.testframe == 'undefined')
      {
        thisField.testframe = new String('sql');
      }
      else
      {
        if (thisField.testframe.substr(0,1) == '_') thisField.testframe = 'sql';
      }
      thisField.testFunction = new Function('return testFunction(this)');
    }

    if (typeof thisField.exceptionok == 'undefined')
      thisField.exceptionokFunction = new Function('return false;');
    else
      thisField.exceptionokFunction = new Function('return ' + thisField.exceptionok  + '(this);');

    if (typeof thisField.exceptionko == 'undefined')
      thisField.exceptionkoFunction = new Function('return true;');
    else
      thisField.exceptionkoFunction = new Function('return ' + thisField.exceptionko  + '(this);');

    if (typeof thisField.mandatory == 'undefined')
    {
      mandatory = new Boolean("thisField");
      thisField.mandatory = false;
    }
    else
    {
      if (typeof(thisField.mandatory) == 'string')
      {
        switch (thisField.mandatory.toLowerCase())
        {
          case 'true' :
          case 'vero' :
          case 'yes' :
          case 'y' :
          case 'si' :
          case 's' :
          case '1' :
            thisField.mandatory = true;
            break;
          default :
            thisField.mandatory = false;
        }
      }
      else
      {
        switch (thisField.mandatory)
        {
          case true :
          case 1 :
            thisField.mandatory = true;
            break;
          default :
            thisField.mandatory = false;
        }
      }
    }

    baseColor = new String("thisField");
    if (typeof thisField.form.fieldsBaseColor == 'undefined')
    {
      thisField.baseColor = thisField.style.color ;
    }
    else
    {
      thisField.baseColor = thisField.form.fieldsBaseColor ;
    }

    baseBgColor = new String("thisField");
    if (typeof thisField.form.fieldsBaseBgColor == 'undefined')
    {
      thisField.baseBgColor = thisField.style.background ;
    }
    else
    {
      thisField.baseBgColor = thisField.form.fieldsBaseBgColor ;
    }

    changed = new Boolean("thisField");
    thisField.changed = false;
    thisField.isChanged = new Function('return testField(this)');

    thisField.setMandatory = new Function('valore', 'if (valore) {setMandatory(this);} else {setNotMandatory(this)};');

    thisField.reset = new Function('return resetField(this)');
/*
    Metto i valori di default per ogni kind di campo
*/
    switch (thisField.kind.toUpperCase())
    {
      case "NUMERO":
        if (typeof thisField.decimali == 'undefined')
          thisField.decimali = new String('');
      case "VALUTA":
      case "VALUTAINTERA":
        if (typeof thisField.decimali == 'undefined')
          thisField.decimali = new String('99');
        if (typeof(thisField.migliaia) == 'string')
        {
          switch (thisField.migliaia.toLowerCase())
          {
            case 'true' :
            case 'vero' :
            case 'yes' :
            case 'y' :
            case 'si' :
            case 's' :
            case '1' :
              thisField.migliaia = true;
              break;
            default :
              thisField.migliaia = false;
          }
        }
        else
        {
          switch (thisField.migliaia)
          {
            case false :
            case 0 :
              thisField.migliaia = false;
              break;
            default :
              thisField.migliaia = true;
          }
        }
        thisField.style.textAlign = "right";
        break;
      case "ABI":
      case "CAB":
      case "CAP":
        thisField.maxLength = 5;
        thisField.style.textAlign = "right";
        break;
      case "CODICEFISCALE":
        thisField.maxLength = 16;
        thisField.style.textTransform = "uppercase";
        break;
      case "PIVA":
        thisField.maxLength = 11;
        break;
      case "ORA":
	if (typeof thisField.maxLength == 'undefined')
		thisField.maxLength = 8;
	if (thisField.maxLength < 2)
		thisField.maxLength = 2;
	if ((thisField.maxLength > 2) && (thisField.maxLength < 5))
		thisField.maxLength = 2;
	if ((thisField.maxLength > 5) && (thisField.maxLength < 8))
		thisField.maxLength = 5;
	if (thisField.maxLength > 8)
		thisField.maxLength = 8;
        break;
      case "DATA":
        thisField.maxLength = 10;
        if (typeof thisField.baloonHelp == 'undefined')
        	thisField.baloonHelp = 'Fare doppio click per visualizzare il calendario.';
        else
        	thisField.baloonHelp = 'Fare doppio click per visualizzare il calendario.' + thisField.baloonHelp;

        if (typeof thisField.calendar == 'undefined')
        {
          calendar = new Boolean("thisField");
          thisField.calendar = true;
        }
        else
          if (typeof(thisField.calendar) == 'string')
          {
            switch (thisField.calendar.toLowerCase())
            {
              case 'true' :
              case 'vero' :
              case 'yes' :
              case 'y' :
              case 'si' :
              case 's' :
              case '1' :
                thisField.calendar = true;
                break;
              default :
                thisField.calendar = false;
            }
          }
          else
          {
            switch (thisField.calendar)
            {
              case true :
              case 1 :
                thisField.calendar = true;
                break;
              default :
                thisField.calendar = false;
            }
          }

        actualOnChangeNext = '';
        if (thisField.ondblclick != null)
        {
          actualOnChange = thisField.ondblclick;
          actualOnChangeFind = actualOnChange.toString().indexOf('{');
          actualOnChangeNext = actualOnChange.toString().substr(actualOnChangeFind+1, (actualOnChange.toString().length - actualOnChangeFind - 3) );
        }
        thisField.ondblclick = new Function('if ((this.calendar==true) && (this.readOnly!=true)) {showCalendario(this)}; '+actualOnChangeNext);

        break;
    }

    oldValue = new Object("thisField");
    switch (thisField.type.toUpperCase())
    {
      case 'SELECT-ONE' :
      case 'SELECT-MULTIPLE' :
        thisField.oldValue = thisField.selectedIndex;
        thisField.disabledOptions = new Array();
        break;

      case 'CHECKBOX' :
        thisField.oldValue = thisField.checked;
        break;

      default :
        initFormatField(thisField);
        thisField.oldValue = thisField.value;
    }
  }
}

//
// Richiede se nomeform.confirm != false, la conferma dell'operazione
//
function confirmForm(thisForm)
{
  switch (thisForm.confirm)
  {
    case true :
    case 'true' :
      return (confirm("Confermi l'operazione ?"));
      break;
    case false :
    case 'false' :
      return (true);
      break;
    default :
      return (confirm(thisForm.confirm));
  }
}

//
// Effettua il controllo presente nel onSubmit prima di eseguire la submit()
// Inquanto il metodo .submit() non esegue la onSubmit
//
function submitForm(thisForm)
{
  
  thisForm.isCancel = false;
  thisForm.isError = false;

  if (confirmForm(thisForm))
  {
    if (thisForm.onsubmit())
    {
      thisForm.submit();
    }
    else
    {
      submitFlag = false;
      thisForm.isError = true;
      if (typeof thisForm.onError != 'undefined')
        thisForm.onError();
    }
  }
  else
  {
    submitFlag = false;
    thisForm.isCancel = true;
    if (typeof thisForm.onCancel != 'undefined')
      thisForm.onCancel();
  }
}

//
// Effettua il controllo del submit
//
function onSubmitForm(thisForm)
{

  var strReturn = true;
  var strThisField = "";

  if (thisForm.fieldsMandatory == false)
  {
    strReturn = true;
  }
  else
  {
    if (thisForm.isWrong() == false)
    {
      strReturn = true;
    }
    else
    {
      strReturn = false;
      submitFlag = false;

      strThisField = thisForm.wrongFields[0];
      thisField = eval(thisForm.name + '.' + strThisField);

      alert(thisForm.wrongMsg());
    }
  }

  return (strReturn);

}

//
// Viene richiamata nei campi, per controllare il valore di un campo modificato da operatore
//
function resetFieldsFormat(thisForm)
{
  var i = 0;

  campi=thisForm.elements;

  for (i=0; i<campi.length; i++)
  {
    if (campi[i].type.toUpperCase() == "TEXT")
    {
      switch (campi[i].kind.toUpperCase())
      {
        case 'NUMERO' :
        case 'VALUTA' :
        case 'VALUTAINTERA' :
          campi[i].value = campi[i].getValue();
      }
    }
  }
}

//
// Viene richiamata nei campi, per controllare il valore di un campo modificato da operatore
//
function onChangeField(thisField)
{
  testField(thisField);
}


//
// Visualizza le differenze di un campo
//
function testFieldMsg(thisField)
{
  var bReturn = false;

  switch (thisField.type.toUpperCase())
  {
    case 'SELECT-ONE' :
      if (thisField.oldValue != thisField.selectedIndex) bReturn = true;
      return ' [ ' + bReturn + ' ] ' + 'SELECT-ONE:: ' + thisField.name + ': >' + thisField.oldValue + '< -- >' + thisField.selectedIndex;
      break;
    case 'SELECT-MULTIPLE' :
      if (thisField.oldValue != thisField.selectedIndex) bReturn = true;
      return ' [ ' + bReturn + ' ] ' + 'SELECT-MULTIPLE:: ' + thisField.name + ': >' + thisField.oldValue + '< -- >' + thisField.selectedIndex;
      break;
    case 'CHECKBOX' :
      if (thisField.oldValue != thisField.checked) bReturn = true;
      return ' [ ' + bReturn + ' ] ' + 'CHECKBOX:: ' + thisField.name + ': >' + thisField.oldValue + '< -- >' + thisField.checked;
      break;
    case 'RADIO' :
      campo = document.getElementsByName(thisField.name);
      if (campo[0].oldValue != whoIsChecked(thisField))
      {
        for (i=0; i<campo.length; i++)
        {
          bReturn = true;
        }
      }
      return ' [ ' + bReturn + ' ] ' + 'RADIO:: ' + thisField.name + ': >' + campo[0].oldValue + '< -- >' + whoIsChecked(thisField);
      break;
    default :
      if (thisField.oldValue != thisField.value) bReturn = true;
      return  ' [ ' + bReturn + ' ] ' + thisField.name + ': >' + thisField.oldValue + '< -- >' + thisField.value;
  }

}


//
// Verifica se una campo è diverso dal vecchio valore,
// utile quando si cambia il valore di un campo tramite javascript
//
function testField(thisField)
{
  var bReturn = false;

  switch (thisField.type.toUpperCase())
  {
    case 'SELECT-ONE' :
      if (thisField.oldValue != thisField.selectedIndex) bReturn = true;
      break;
    case 'SELECT-MULTIPLE' :
      if (thisField.oldValue != thisField.selectedIndex) bReturn = true;
      break;
    case 'CHECKBOX' :
      if (thisField.oldValue != thisField.checked) bReturn = true;
      break;
    case 'RADIO' :
      campo = document.getElementsByName(thisField.name);
      if (campo[0].oldValue != whoIsChecked(thisField))
      {
        for (i=0; i<campo.length; i++)
        {
          bReturn = true;
        }
      }
      break;
    default :
      thisField.setValue(thisField.getValue());
      if (thisField.oldValue != thisField.value) bReturn = true;
  }

  if (bReturn == true)
  {
    insertInChangedFields(thisField);
  }
  else
  {
    removeFromChangedFields(thisField);
  }

  setColorField(thisField);

  return bReturn;
}


//
// Verifica tutti i campi di una FORM se sono diversi dal rispettivo vecchio valore,
// utile quando si cambia il valore di uno o più campi tramite javascript
//
function testFields(thisForm)
{
  var i = 0;
  var Ritorna = false;
  var Dummy;

  campi=thisForm.elements;

  for (i=0; i<campi.length; i++)
  {
    if ((campi[i].type.toUpperCase() != "HIDDEN") && (campi[i].type.toUpperCase() != "SUBMIT") && (campi[i].type.toUpperCase() != "RESET") && (campi[i].type.toUpperCase() != "BUTTON") && (campi[i].type.toUpperCase() != "IMAGE"))
    {
      if (testField(eval(campi[i])) == true) Ritorna = true;
      Dummy = isWrongField(eval(campi[i]));
    }
  }
  return Ritorna
}

//
// Resetta lo stato di un campo e il valore torna a oldValue
//
function resetField(thisField)
{

  var i = 0;

  switch (thisField.type.toUpperCase())
  {
    case 'SELECT-ONE' :
      case 'SELECT-MULTIPLE' :
      thisField.selectedIndex = thisField.oldValue;
      break;
    case 'CHECKBOX' :
      thisField.checked = thisField.oldValue;
      break;
    case 'RADIO' :
      campo = document.getElementsByName(thisField.name);
      for (i=0; i<campo.length; i++)
      {
        campo[i].changed = false;
        campo[i].checked = false;
      }
      if (campo[0].oldValue >= 0) campo[campo[0].oldValue].checked = true;
      break;
    default :
      thisField.setValue(thisField.oldValue);
  }
  thisField.changed = false;

  removeFromChangedFields(thisField);
  removeFromWrongFields(thisField);

  thisField.isWrong();

  setColorField(thisField);

  return thisField.value;
}

//
// Resetta lo stato di tutti i campi, lo stato della FORM e i rispettivi valori tornano a oldValue
//
function resetFields(thisForm)
{
  var i = 0;

  campi=thisForm.elements;

  for (i=0; i<campi.length; i++)
  {
    if ((campi[i].type.toUpperCase() != "HIDDEN") && (campi[i].type.toUpperCase() != "SUBMIT") && (campi[i].type.toUpperCase() != "RESET") && (campi[i].type.toUpperCase() != "BUTTON") && (campi[i].type.toUpperCase() != "IMAGE"))
    {
      resetField(eval(campi[i]));
    }
  }

  thisForm.changed = false;
}

//
// Toglie la formattazione al contenuto di un campo di tipo text quando ci si posiziona sopra
// in modo da renderlo modificabile in base al valore di kind
//
function onFocusField(thisField)
{
  var strValue = '';
  switch (thisField.kind.toUpperCase())
  {
    case 'NUMERO' :
    case 'VALUTA' :
    case 'VALUTAINTERA' :
    case 'DATA' :
    case 'ORA' :
      strValue = thisField.getValue();
      thisField.value = strValue;
      break;
    default :
  }
}

//
// Formatta il contenuto di un campo di tipo text quando ci si abbandona
// in modo da renderlo visualizzato in base al valore di kind
//
// dontTest	se è TRUE non esegue il controllo all'uscita del campo
//
function onBlurField(thisField, dontTest)
{

  var strErrMsg = "";
  var strValue = '';

  if (dontTest == null)
	  dontTest = ((typeof(document.all.overDiv.style)!='undefined') && (document.all.overDiv.style.visibility=='visible'));

  if (dontTest == true)
  {
    switch (thisField.kind.toUpperCase())
    {
      case 'NUMERO' :
      case 'VALUTA' :
      case 'VALUTAINTERA' :
      case 'DATA' :
      case 'ORA' :
      case 'EMAIL' :
      case 'ABI' :
      case 'CAB' :
      case 'CAP' :
      case 'CODICEFISCALE' :
      case 'PIVA' :
      case 'LETTERE' :
      case 'LETTERESPAZIO' :
        strValue = thisField.getValue();
        thisField.setValue(strValue);
        break;
      default :
        if (typeof thisField.transform != 'undefined')
        {
          strValue = thisField.getValue();
          thisField.setValue(strValue);
        }
    }
  }
  else
  {
    strErrMsg = thisField.isWrong();
  
    if (strErrMsg == "")
    {
      switch (thisField.kind.toUpperCase())
      {
        case 'NUMERO' :
        case 'VALUTA' :
        case 'VALUTAINTERA' :
        case 'DATA' :
        case 'ORA' :
        case 'EMAIL' :
        case 'ABI' :
        case 'CAB' :
        case 'CAP' :
        case 'CODICEFISCALE' :
        case 'PIVA' :
        case 'LETTERE' :
        case 'LETTERESPAZIO' :
          strValue = thisField.getValue();
          thisField.setValue(strValue);
          break;
        default :
        if (typeof thisField.transform != 'undefined')
        {
          strValue = thisField.getValue();
          thisField.setValue(strValue);
        }
      }
    }
  }

  setColorField(thisField);

  if (strErrMsg != "")
  {
    thisField.wrongMsg();
  }
}

//
// Controlla i tasti BACKSPACE ed altri tasti in base al valore di kind
//
function onKeyField(thisField, e)
{
  var strValue = (''+thisField.value);

  switch (thisField.type.toUpperCase())
  {
    case 'HIDDEN' :
    case 'SUBMIT':
    case 'RESET':
    case 'BUTTON':
    case 'IMAGE' :
      break;
    case 'TEXTAREA' :
      if (typeof thisField.maxlength != 'undefined') 
      {
        if (thisField.value.length >= thisField.maxlength) 
        {
          if (((e.keyCode >= 16) && (e.keyCode <= 18)) || // shift, ctrl e alt
            ((e.keyCode >= 35) && (e.keyCode <= 40)) || // home, end e freccie cursore
            (e.keyCode == 46) || // canc
            (e.keyCode == 8) || // backspace
            (e.keyCode == 9)) // tab
          {}
          else
          {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
          }
        }
      }
      break;
    default :
      if (e.keyCode == 13) // invio diventa tab
      {
	e.keyCode = 9;
      }

      switch (thisField.kind.toUpperCase())
      {
        case 'NUMERO' :
        case 'VALUTA' :
          if (((e.keyCode >= 48) && (e.keyCode <= 57)) || // numeri tastiera
            ((e.keyCode >= 96) && (e.keyCode <= 105)) || // numeri tastierino
            ((e.keyCode >= 16) && (e.keyCode <= 18)) || // shift, ctrl e alt
            ((e.keyCode >= 35) && (e.keyCode <= 40)) || // home, end e freccie cursore
            ((thisField.decimali.length > 0) && (e.keyCode == 188)) || // virgola
            (e.keyCode == 45) || // ins
            (e.keyCode == 46) || // canc
            (e.keyCode == 8) || // backspace
            (e.keyCode == 9)) // tab
          {}
          else
          {
            if ((thisField.decimali.length > 0) &&
              (
              (e.keyCode == 110) || (e.keyCode == 190) // punto tastierino o punto tastiera
              ))
              thisField.value = thisField.value + ',';

            if (
		    (
		    (parseFloat(strValue) != 0) && (trimCF(strValue) != '')
            	    )
            	&&
		    (
		    (e.keyCode == 109) || (e.keyCode == 189) // meno tastierino o meno tastiera
            	    )
	        )
		{
		    if (strValue.indexOf('-') == -1)
	                {
		        thisField.value = '-' + trimCF(strValue);
		        }
		    else
	                {
			thisField.value = replaceChrCF(strValue, '-', '');
		        }
		}
            window.event.cancelBubble = true;
            window.event.returnValue = false;
          }
          break;
        case 'VALUTAINTERA' :
          if (((e.keyCode >= 48) && (e.keyCode <= 57)) || // numeri tastiera
            ((e.keyCode >= 96) && (e.keyCode <= 105)) || // numeri tastierino
            ((e.keyCode >= 16) && (e.keyCode <= 18)) || // shift, ctrl e alt
            ((e.keyCode >= 35) && (e.keyCode <= 40)) || // home, end e freccie cursore
            (e.keyCode == 45) || // ins
            (e.keyCode == 46) || // canc
            (e.keyCode == 8) || // backspace
            (e.keyCode == 9)) // tab
          {}
          else
          {
            if (
		    (
		    (parseFloat(strValue) != 0) && (trimCF(strValue) != '')
            	    )
            	&&
		    (
		    (e.keyCode == 109) || (e.keyCode == 189) // meno tastierino o meno tastiera
            	    )
	        )
		{
		    if (strValue.indexOf('-') == -1)
	                {
		        thisField.value = '-' + trimCF(strValue);
		        }
		    else
	                {
			thisField.value = replaceChrCF(strValue, '-', '');
		        }
		}
            window.event.cancelBubble = true;
            window.event.returnValue = false;
          }
          break;
        case 'DATA' :
          if (((e.keyCode >= 48) && (e.keyCode <= 57)) || // numeri tastiera
            ((e.keyCode >= 96) && (e.keyCode <= 105)) || // numeri tastierino
            ((e.keyCode >= 16) && (e.keyCode <= 18)) || // shift, ctrl e alt
            ((e.keyCode >= 35) && (e.keyCode <= 40)) || // home, end e freccie cursore
            (e.keyCode == 111) || // / tastiera
            (e.keyCode == 110) || // punto tastiera
            (e.keyCode == 190) || // punto tastierino
            (e.keyCode == 188) || // virgola
            (e.keyCode == 45) || // ins
            (e.keyCode == 46) || // canc
            (e.keyCode == 8) || // backspace
            (e.keyCode == 9)) // tab
          {}
          else
          {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
          }
          break;
        case 'ORA' :
          if (((e.keyCode >= 48) && (e.keyCode <= 57)) || // numeri tastiera
            ((e.keyCode >= 96) && (e.keyCode <= 105)) || // numeri tastierino
            ((e.keyCode >= 16) && (e.keyCode <= 18)) || // shift, ctrl e alt
            ((e.keyCode >= 35) && (e.keyCode <= 40)) || // home, end e freccie cursore
            (e.keyCode == 111) || // / tastiera
            (e.keyCode == 188) || // virgola
            (e.keyCode == 45) || // ins
            (e.keyCode == 46) || // canc
            (e.keyCode == 8) || // backspace
            (e.keyCode == 9)) // tab
          {}
          else
          {
            if ((thisField.decimali.length > 0) &&
              (
              (e.keyCode == 110) || (e.keyCode == 190) // punto tastierino o punto tastiera
              ))
              thisField.value = thisField.value + ':';
            window.event.cancelBubble = true;
            window.event.returnValue = false;
          }
          break;
        case 'PIVA' :
          if (((e.keyCode >= 48) && (e.keyCode <= 57)) || // numeri tastiera
            ((e.keyCode >= 96) && (e.keyCode <= 105)) || // numeri tastierino
            ((e.keyCode >= 16) && (e.keyCode <= 18)) || // shift, ctrl e alt
            ((e.keyCode >= 35) && (e.keyCode <= 40)) || // home, end e freccie cursore
            (e.keyCode == 45) || // ins
            (e.keyCode == 46) || // canc
            (e.keyCode == 8) || // backspace
            (e.keyCode == 9)) // tab
          {}
          else
          {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
          }
          break;
        case 'ABI' :
        case 'CAB' :
        case 'CAP' :
          if (((e.keyCode >= 48) && (e.keyCode <= 57)) || // numeri tastiera
            ((e.keyCode >= 96) && (e.keyCode <= 105)) || // numeri tastierino
            ((e.keyCode >= 16) && (e.keyCode <= 18)) || // shift, ctrl e alt
            ((e.keyCode >= 35) && (e.keyCode <= 40)) || // home, end e freccie cursore
            (e.keyCode == 45) || // ins
            (e.keyCode == 46) || // canc
            (e.keyCode == 8) || // backspace
            (e.keyCode == 9)) // tab
          {}
          else
          {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
          }
          break;
        case 'LETTERE' :
          if (((e.keyCode >= 65) && (e.keyCode <= 90)) || // lettere
            ((e.keyCode >= 16) && (e.keyCode <= 18)) || // shift, ctrl e alt
            ((e.keyCode >= 35) && (e.keyCode <= 40)) || // home, end e freccie cursore
            (e.keyCode == 45) || // ins
            (e.keyCode == 46) || // canc
            (e.keyCode == 8) || // backspace
            (e.keyCode == 9)) // tab
          {}
          else
          {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
          }
          break;
        case 'LETTERESPAZIO' :
          if (((e.keyCode >= 65) && (e.keyCode <= 90)) || // lettere
            (e.keyCode == 32) || // spazio
            ((e.keyCode >= 16) && (e.keyCode <= 18)) || // shift, ctrl e alt
            ((e.keyCode >= 35) && (e.keyCode <= 40)) || // home, end e freccie cursore
            (e.keyCode == 45) || // ins
            (e.keyCode == 46) || // canc
            (e.keyCode == 8) || // backspace
            (e.keyCode == 9)) // tab
          {}
          else
          {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
          }
          break;
        default :
      }
    break;
  }
}

//
// Inserisce nell'Array changedFields un campo
//
function insertInChangedFields(thisField)
{
    var lenChangedFields = thisField.form.changedFields.length;
    thisField.form.changedFields[lenChangedFields] = thisField.name
    thisField.form.changedFields.length = lenChangedFields + 1;
    thisField.changed = true;
    thisField.form.changed = true;
    setColorField(thisField);
}

//
// Rimuove dall'Array changedFields un campo
//
function removeFromChangedFields(thisField)
{
  var i = 0;
  var j = 0;

  for (i=0; i<thisField.form.changedFields.length; i++)
  {
    if (thisField.name == thisField.form.changedFields[i])
    {
      j = 1;
    }
    thisField.form.changedFields[i] = thisField.form.changedFields[i+j];
  }
  if (j == 1) --thisField.form.changedFields.length;

  if (thisField.form.changedFields.length == 0)
  {
    thisField.form.changed = false;
    }
  else
  {
    thisField.form.changed = true;
  }
}

//
// Inserisce nell'Array wrongFields un campo
//
function insertInWrongFields(thisField)
{
  var i = 0;
  var fieldFound = false;

//alert(thisField.form.wrongFields.length);

  for (i=0; i<thisField.form.wrongFields.length; i++)
  {
    if (thisField.name == thisField.form.wrongFields[i])
    {
      fieldFound = true;
      break;
    }
  }
  if (fieldFound == false)
  {
    var lenWrongFields = thisField.form.wrongFields.length;
    thisField.form.wrongFields[lenWrongFields] = thisField.name
    thisField.form.wrongFields.length = lenWrongFields + 1;
  }
}

//
// Rimuove dall'Array wrongFields un campo
//
function removeFromWrongFields(thisField)
{
  var i = 0;
  var j = 0;

  for (i=0; i<thisField.form.wrongFields.length; i++)
  {
    if (thisField.name == thisField.form.wrongFields[i])
    {
      j = 1;
    }
    thisField.form.wrongFields[i] = thisField.form.wrongFields[i+j];
  }
  if (j == 1) --thisField.form.wrongFields.length;
}

//
// Restituisce l'index checked di un campo Radio
//
function whoIsChecked(thisField)
{
  var i = 0;
  var Ritorna = -1;

  var campo = document.getElementsByName(thisField.name);
  if (campo.length == 0) campo = thisField;
  for (i=0; i<campo.length; i++)
  {
    if (campo[i].checked) Ritorna = i;
  }

  return Ritorna;
}

//
// Setta il valore di oldValue di un campo.
// E' sufficiente indicare il nome del campo e oldValue prende l'attuale valore del campo.
//
function setOldValueField(thisField)
{

  var i =0;

  if (thisField.type.toUpperCase() == 'RADIO')
  {
    campo = document.getElementsByName(thisField.name);
    for (i=0; i<campo.length; i++)
    {
      campo[i].changed = false;

      campo[i].oldValue = whoIsChecked(thisField);
    }
  }
  else
  {
    thisField.changed = false;

    switch (thisField.type.toUpperCase())
    {
      case 'SELECT-ONE' :
        thisField.oldValue = thisField.selectedIndex;
        break;
      case 'SELECT-MULTIPLE' :
        thisField.oldValue = thisField.selectedIndex;
        break;
      case 'CHECKBOX' :
        thisField.oldValue = thisField.checked;
        break;
      default :
        thisField.oldValue = thisField.getValue();
    }
  }

  resetField(thisField);
}

//
// Setta il valore di oldValue di tutti i campi.
//
function setOldValueFields(thisForm)
{
  var i = 0;

  campi=thisForm.elements;

  for (i=0; i<campi.length; i++)
  {
    if ((campi[i].type.toUpperCase() != "HIDDEN") && (campi[i].type.toUpperCase() != "SUBMIT") && (campi[i].type.toUpperCase() != "RESET") && (campi[i].type.toUpperCase() != "BUTTON") && (campi[i].type.toUpperCase() != "IMAGE"))
    {
      setOldValueField(eval(campi[i]));
    }
  }

  thisForm.changed = false;
}

//
// Dice alla form di gestire i campi obbligatori.
//
function setFieldsMandatory(thisForm)
{

  thisForm.fieldsMandatory = true;
  setColorFields(thisForm);
}

//
// Dice alla form di NON gestire i campi obbligatori.
//
function setFieldsNotMandatory(thisForm)
{

  thisForm.fieldsMandatory = false;
  setColorFields(thisForm);
}

//
// Setta un campo come obbligatorio.
//
function setMandatory(thisField)
{

  var i =0;

  if (thisField.type.toUpperCase() == 'RADIO')
  {
    campo = document.getElementsByName(thisField.name);
    for (i=0; i<campo.length; i++)
    {
      campo[i].mandatory = true;
    }
  }
  else
  {
    switch (thisField.type.toUpperCase())
    {
      case 'SELECT-ONE' :
        thisField.mandatory = true;
        break;
      case 'SELECT-MULTIPLE' :
        thisField.mandatory = true;
        break;
      case 'CHECKBOX' :
        break;
      default :
        thisField.mandatory = true;
    }
  }
  setColorField(thisField);
}

//
// Setta un campo come NON obbligatorio.
//
function setNotMandatory(thisField)
{

  var i =0;

  if (thisField.type.toUpperCase() == 'RADIO')
  {
    campo = document.getElementsByName(thisField.name);
    for (i=0; i<campo.length; i++)
    {
      campo[i].mandatory = false;
    }
  }
  else
  {
    switch (thisField.type.toUpperCase())
    {
      case 'SELECT-ONE' :
        thisField.mandatory = false;
        break;
      case 'SELECT-MULTIPLE' :
        thisField.mandatory = false;
        break;
      case 'CHECKBOX' :
        break;
      default :
        thisField.mandatory = false;
    }
  }

  removeFromWrongFields(thisField);

  setColorField(thisField);
}

//
// Setta il colore di sfondo e di testo di un campo.
// E' sufficiente indicare il nome del campo ed in base al suo stato di Changed e di Mandatory mette i colori.
//
function setColorField(thisField, textColor, bgColor)
{
  var i =0;

  if (thisField.type.toUpperCase() == 'RADIO')
  {
    if ((typeof thisField.readOnly=='undefined' || thisField.readOnly==false) && thisField.disabled==false)
    {
      campo = document.getElementsByName(thisField.name);
      for (i=0; i<campo.length; i++)
      {
        if (typeof textColor=='undefined')
          campo[i].style.color = (((campo[i].isWrong()!=""))?thisField.form.fieldsMandatoryColor:getFieldsBaseColor(campo[i]));
        else
          campo[i].style.color = textColor;
        if (typeof bgColor=='undefined')
          campo[i].style.background = (((campo[i].isWrong()!=""))?thisField.form.fieldsMandatoryBgColor:getFieldsBaseBgColor(campo[i]));
        else
          campo[i].style.background = bgColor;
      }
    }
  }
  else
  {
    if ((typeof thisField.readOnly=='undefined' || thisField.readOnly==false) && thisField.disabled==false)
    {
      switch (thisField.type.toUpperCase())
      {
        case 'SELECT-ONE' :
        case 'SELECT-MULTIPLE' :
          if (typeof thisField.multicolor=='undefined')
            thisField.multicolor = getFieldsBaseBgColor(thisField);
          if (thisField.options.length > 0)
          {
            if (typeof textColor=='undefined')
              thisField.options[0].style.color = (((thisField.isWrong()!=""))?thisField.form.fieldsMandatoryColor:getFieldsBaseColor(thisField));
            else
              thisField.options[0].style.color = textColor;
            if (typeof bgColor=='undefined')
              thisField.options[0].style.background = (((thisField.isWrong()!=""))?thisField.form.fieldsMandatoryBgColor:thisField.multicolor);
            else
              thisField.options[0].style.background = bgColor;
            for (i=1; i<thisField.options.length; i++)
            {
              if (typeof textColor=='undefined')
                thisField.options[i].style.color = getFieldsBaseColor(thisField);
              else
                thisField.options[i].style.color = textColor;
              if (typeof bgColor=='undefined')
                thisField.options[i].style.background = (((i % 2) == 0)?thisField.multicolor:getFieldsBaseBgColor(thisField));
              else
                thisField.options[i].style.background = bgColor;
            }
          }
          break;
        case 'CHECKBOX' :
          if (typeof textColor=='undefined')
            thisField.style.color = (((thisField.isWrong()!=""))?thisField.form.fieldsMandatoryColor:getFieldsBaseColor(thisField));
          else
            thisField.style.color = textColor;
          if (typeof bgColor=='undefined')
            thisField.style.background = (((thisField.isWrong()!=""))?thisField.form.fieldsMandatoryBgColor:getFieldsBaseBgColor(thisField));
          else
            thisField.style.background = bgColor;
          break;
        default :
          if (typeof textColor=='undefined')
            thisField.style.color = (((thisField.isWrong()!=""))?thisField.form.fieldsMandatoryColor:getFieldsBaseColor(thisField));
          else
            thisField.style.color = textColor;
          if (typeof bgColor=='undefined')
            thisField.style.background = (((thisField.isWrong()!=""))?thisField.form.fieldsMandatoryBgColor:getFieldsBaseBgColor(thisField));
          else
            thisField.style.background = bgColor;
      }
    }
  }
}

//
// Setta il colore di sfondo e di testo di tutti i campi.
//
function setColorFields(thisForm)
{
  var i = 0;

  campi=thisForm.elements;

  for (i=0; i<campi.length; i++)
  {
    if ((campi[i].type.toUpperCase() != "HIDDEN") && (campi[i].type.toUpperCase() != "SUBMIT") && (campi[i].type.toUpperCase() != "RESET") && (campi[i].type.toUpperCase() != "BUTTON") && (campi[i].type.toUpperCase() != "IMAGE"))
    {
      setColorField(eval(campi[i]));
    }
  }
}

//
// Restituisce il colore per i campi, facendo attenzione se è un campo obbligatorio.
//
function getFieldsBaseColor(thisField)
{

  return ((thisField.form.fieldsChanged==true && thisField.changed==true)?thisField.form.fieldsChangedColor:thisField.baseColor);

}

//
// Restituisce il colore di sfondo per i campi, facendo attenzione se è un campo obbligatorio.
//
function getFieldsBaseBgColor(thisField)
{

  return ((thisField.form.fieldsChanged==true && thisField.changed==true)?thisField.form.fieldsChangedBgColor:thisField.baseBgColor);

}


//
// Controlla il campo se è obbligatorio e/o errato
//
function isWrongField(thisField)
{

    var strReturn = "";
    var strValue = "";
    var strValueMax = "";
    var strValueMin = "";

    switch (thisField.type.toUpperCase())
    {
      case 'SELECT-ONE' :
      case 'SELECT-MULTIPLE' :
        if (thisField.selectedIndex>-1) strValue = thisField.getValueText();
        if ((thisField.mandatory == true) && (thisField.form.fieldsMandatory == true) && (trimCF(strValue) == "")) strReturn = "EMPTY";
//
//	Se il campo è vuoto non eseguo più controlli
//
        if (strReturn == "")
        {
	  if (thisField.getValue() == "") return "";
        }

        if (strReturn == "")
        {
          if ((typeof thisField.valuene != 'undefined') && (thisField.valuene != '') && (strReturn == ""))
          {
            if (thisField.value == thisField.valuene) strReturn = "NEQ";
          }
        }
        break;
      case 'RADIO' :
        campo = document.getElementsByName(thisField.name);
        if ((campo[0].mandatory == true) && (campo[0].form.fieldsMandatory == true))
        {
          strReturn = (whoIsChecked(thisField)==-1?"EMPTY":"");
        }
        break;
      case 'CHECKBOX' :
        break;
      default :
//
//	Controllo il valore di campo obbligatorio
//
        if ((thisField.mandatory == true) && (thisField.form.fieldsMandatory == true) && (trimCF(thisField.value) == "")) strReturn = "EMPTY";
//
//	Se il campo è vuoto non eseguo più controlli
//
        if (strReturn == "")
        {
	  if (thisField.getValue() == "") return "";
        }

        if (strReturn == "")
        {
          if (thisField.exceptionokFunction() == true) return "";
        }

        if (strReturn == "")
        {
          if (thisField.exceptionkoFunction() == false) strReturn = "VALUE";
        }

//
//	Controllo la validità del contenuto del campo
//
        if (strReturn == "")
        {
          switch (thisField.kind.toUpperCase())
          {
            case 'NUMERO' :
            case 'VALUTA' :
            case 'VALUTAINTERA' :
              strValue = thisField.getValue();
              strValue = replaceChrCF(strValue, ',' , '.');
              strReturn = (isNaN(strValue)==true?"VALUE":"");
              break;
            case 'DATA' :
              strReturn = (isDataRealeCF(thisField.getValue())==true?"":"VALUE");
              break;
            case 'ORA' :
              strReturn = (isOraRealeCF(thisField.getValue())==true?"":"VALUE");
              break;
            case 'EMAIL' :
              strReturn = (isEmailRealeCF(thisField.getValue())==true?"":"VALUE");
              break;
            case 'CODICEFISCALE' :
              strReturn = (isCodiceFiscaleRealeCF(thisField.getValue())==true?"":"VALUE");
              break;
            case 'PIVA' :
              strReturn = (isPartitaIvaRealeCF(thisField.getValue())==true?"":"VALUE");
              break;
           }
        }

//
//	Controllo se il valore del campo è nei limiti impostati
//
        if (strReturn == "")
        {
          switch (thisField.kind.toUpperCase())
          {
            case 'NUMERO' :
            case 'VALUTA' :
            case 'VALUTAINTERA' :
              strValue = thisField.getValue();
              strValue = replaceChrCF(strValue, ',' , '.');
              if ((typeof thisField.valueeq != 'undefined') && (thisField.valueeq != '') && (strReturn == ""))
              {
                if (parseFloat(strValue) != parseFloat(replaceChrCF(thisField.valueeq, ',', '.'))) strReturn = "RANGE";
              }
              if ((typeof thisField.valuene != 'undefined') && (thisField.valuene != '') && (strReturn == ""))
              {
                if (parseFloat(strValue) == parseFloat(replaceChrCF(thisField.valuene, ',', '.'))) strReturn = "RANGE";
              }
              if ((typeof thisField.valuelt != 'undefined') && (thisField.valuelt != '') && (strReturn == ""))
              {
                if (parseFloat(strValue) >= parseFloat(replaceChrCF(thisField.valuelt, ',', '.'))) strReturn = "RANGE";
              }
              if ((typeof thisField.valuelt != 'undefined') && (thisField.valuelt != '') && (strReturn == ""))
              {
                if (parseFloat(strValue) >= parseFloat(replaceChrCF(thisField.valuelt, ',', '.'))) strReturn = "RANGE";
              }
              if ((typeof thisField.valuele != 'undefined') && (thisField.valuele != '') && (strReturn == ""))
              {
                if (parseFloat(strValue) > parseFloat(replaceChrCF(thisField.valuele, ',', '.'))) strReturn = "RANGE";
              }
              if ((typeof thisField.valuege != 'undefined') && (thisField.valuege != '') && (strReturn == ""))
              {
                if (parseFloat(strValue) < parseFloat(replaceChrCF(thisField.valuege, ',', '.'))) strReturn = "RANGE";
              }
              if ((typeof thisField.valuegt != 'undefined') && (thisField.valuegt != '') && (strReturn == ""))
              {
                if (parseFloat(strValue) <= parseFloat(replaceChrCF(thisField.valuegt, ',', '.'))) strReturn = "RANGE";
              }
              if ((typeof thisField.valuemod != 'undefined') && (thisField.valuemod != '') && (strReturn == ""))
              {
                if ((parseFloat(strValue) % parseFloat(replaceChrCF(thisField.valuemod, ',', '.'))) != 0) strReturn = "MODULUS";
              }
              break;
            case 'DATA' :
              strValue = thisField.getValue();
              dateValue = new Date();
              dateValue.setFullYear(parseInt(strValue.substr(4,4), 10), (parseInt(strValue.substr(2,2), 10) - 1), parseInt(strValue.substr(0,2), 10));

              if ((typeof thisField.valueeq != 'undefined') && (thisField.valueeq != '') && (strReturn == ""))
              {
                dateCompare = new Date();
		if ((thisField.valueeq.toUpperCase() != "OGGI") && (thisField.valueeq.toUpperCase() != "TODAY"))
		{
                  strCompare = thisField.valueeq;
		  strCompare = replaceChrCF(strCompare, '/', '');
		  strCompare = replaceChrCF(strCompare, '.', '');
		  strCompare = replaceChrCF(strCompare, '-', '');
                  dateCompare.setFullYear(parseInt(strCompare.substr(4,4), 10), (parseInt(strCompare.substr(2,2), 10) - 1), parseInt(strCompare.substr(0,2), 10));
		}
                dateValue.setHours(0, 0, 0, 0);
                dateCompare.setHours(0, 0, 0, 0);
                if  (dateValue != dateCompare) strReturn = "RANGE";
              }
              if ((typeof thisField.valuene != 'undefined') && (thisField.valuene != '') && (strReturn == ""))
              {
                dateCompare = new Date();
		if ((thisField.valuene.toUpperCase() != "OGGI") && (thisField.valuene.toUpperCase() != "TODAY"))
		{
                  strCompare = thisField.valuene;
		  strCompare = replaceChrCF(strCompare, '/', '');
		  strCompare = replaceChrCF(strCompare, '.', '');
		  strCompare = replaceChrCF(strCompare, '-', '');
                  dateCompare.setFullYear(parseInt(strCompare.substr(4,4), 10), (parseInt(strCompare.substr(2,2), 10) - 1), parseInt(strCompare.substr(0,2), 10));
		}
                dateValue.setHours(0, 0, 0, 0);
                dateCompare.setHours(0, 0, 0, 0);
                if  (dateValue == dateCompare) strReturn = "RANGE";
              }
              if ((typeof thisField.valuelt != 'undefined') && (thisField.valuelt != '') && (strReturn == ""))
              {
                dateCompare = new Date();
		if ((thisField.valuelt.toUpperCase() != "OGGI") && (thisField.valuelt.toUpperCase() != "TODAY"))
		{
                  strCompare = thisField.valuelt;
		  strCompare = replaceChrCF(strCompare, '/', '');
		  strCompare = replaceChrCF(strCompare, '.', '');
		  strCompare = replaceChrCF(strCompare, '-', '');
                  dateCompare.setFullYear(parseInt(strCompare.substr(4,4), 10), (parseInt(strCompare.substr(2,2), 10) - 1), parseInt(strCompare.substr(0,2), 10));
		}
                dateValue.setHours(0, 0, 0, 0);
                dateCompare.setHours(0, 0, 0, 0);
                if  (dateValue >= dateCompare) strReturn = "RANGE";
              }
              if ((typeof thisField.valuele != 'undefined') && (thisField.valuele != '') && (strReturn == ""))
              {
                dateCompare = new Date();
		if ((thisField.valuele.toUpperCase() != "OGGI") && (thisField.valuele.toUpperCase() != "TODAY"))
		{
                  strCompare = thisField.valuele;
		  strCompare = replaceChrCF(strCompare, '/', '');
		  strCompare = replaceChrCF(strCompare, '.', '');
		  strCompare = replaceChrCF(strCompare, '-', '');
                  dateCompare.setFullYear(parseInt(strCompare.substr(4,4), 10), (parseInt(strCompare.substr(2,2), 10) - 1), parseInt(strCompare.substr(0,2), 10));
		}
                dateValue.setHours(0, 0, 0, 0);
                dateCompare.setHours(0, 0, 0, 0);
                if  (dateValue > dateCompare) strReturn = "RANGE";
              }
              if ((typeof thisField.valuege != 'undefined') && (thisField.valuege != '') && (strReturn == ""))
              {
                dateCompare = new Date();
		if ((thisField.valuege.toUpperCase() != "OGGI") && (thisField.valuege.toUpperCase() != "TODAY"))
		{
                  strCompare = thisField.valuege;
		  strCompare = replaceChrCF(strCompare, '/', '');
		  strCompare = replaceChrCF(strCompare, '.', '');
		  strCompare = replaceChrCF(strCompare, '-', '');
                  dateCompare.setFullYear(parseInt(strCompare.substr(4,4), 10), (parseInt(strCompare.substr(2,2), 10) - 1), parseInt(strCompare.substr(0,2), 10));
		}
                dateValue.setHours(0, 0, 0, 0);
                dateCompare.setHours(0, 0, 0, 0);
                if  (dateValue < dateCompare) strReturn = "RANGE";
              }
              if ((typeof thisField.valuegt != 'undefined') && (thisField.valuegt != '') && (strReturn == ""))
              {
                dateCompare = new Date();
		if ((thisField.valuegt.toUpperCase() != "OGGI") && (thisField.valuegt.toUpperCase() != "TODAY"))
		{
                  strCompare = thisField.valuegt;
		  strCompare = replaceChrCF(strCompare, '/', '');
		  strCompare = replaceChrCF(strCompare, '.', '');
		  strCompare = replaceChrCF(strCompare, '-', '');
                  dateCompare.setFullYear(parseInt(strCompare.substr(4,4), 10), (parseInt(strCompare.substr(2,2), 10) - 1), parseInt(strCompare.substr(0,2), 10));
		}
                dateValue.setHours(0, 0, 0, 0);
                dateCompare.setHours(0, 0, 0, 0);
                if  (dateValue <= dateCompare) strReturn = "RANGE";
              }
              break;
           }
        }
    }

/*
** IN SVILUPPO
**
    if (strReturn == "")
    {
      if (thisField.testFunction() == false) strReturn = "VALUE";
    }
*/

    if (strReturn != "")
    {
        insertInWrongFields(thisField);
    }
    else
    {
        removeFromWrongFields(thisField);
    }

    return (strReturn);
}

//
// Restituisce la stringa per il messaggio di errore del campo sbagliato.
//
function strWrongField(thisField)
{
  var strReturn = "";
  var strErrMsg = "";

  switch (thisField.isWrong())
  {
    case '' :
      strErrMsg = "";
      break;
    case 'EMPTY' :
      strErrMsg = "è obbligatorio!";
      break;
    case 'VALUE' :
      strErrMsg = "ha un valore non valido!";
      break;
    case 'FORMAT' :
      strErrMsg = "ha un formato non valido!";
      break;
    case 'NEQ' :	// solo x SELECT-ONE e SELECT-MULTIPLE
      strErrMsg = "deve essere diverso da '" + thisField.getValueText().toUpperCase() + "'";
      break;
    case 'MODULUS' :
      strErrMsg = "deve essere un multiplo di '" + thisField.valuemod + "'";
      break;
    case 'RANGE' :
      if ((typeof thisField.kind != 'undefined') && (thisField.kind.toUpperCase() == 'DATA'))
      {
        if ((typeof thisField.valueeq != 'undefined') && (thisField.valueeq != '')) strErrMsg = strErrMsg += "uguale " + (thisField.valueeq == "OGGI"?" alla data odierna ":" al " + thisField.valueeq + "");
        if ((typeof thisField.valuene != 'undefined') && (thisField.valuene != '')) strErrMsg = strErrMsg += (strErrMsg == ""?"":" e ") + "diverso" + (thisField.valuene == "OGGI"?" dalla data odierna ":" dal " + thisField.valuene + "");
        if ((typeof thisField.valuege != 'undefined') && (thisField.valuege != '')) strErrMsg = strErrMsg += (strErrMsg == ""?"":" e ") + "uguale o successivo" + (thisField.valuege == "OGGI"?" alla data odierna ":" al " + thisField.valuege + "");
        if ((typeof thisField.valuegt != 'undefined') && (thisField.valuegt != '')) strErrMsg = strErrMsg += (strErrMsg == ""?"":" e ") + "successivo" + (thisField.valuegt == "OGGI"?" alla data odierna ":" al " + thisField.valuegt + " (escluso)");
        if ((typeof thisField.valuelt != 'undefined') && (thisField.valuelt != '')) strErrMsg = strErrMsg += (strErrMsg == ""?"":" e ") + "antecedente" + (thisField.valuelt == "OGGI"?" alla data odierna ":" al " + thisField.valuelt + " (escluso)");
        if ((typeof thisField.valuele != 'undefined') && (thisField.valuele != '')) strErrMsg = strErrMsg += (strErrMsg == ""?"":" e ") + "uguale o antecedente" + (thisField.valuele == "OGGI"?" alla data odierna ":" al " + thisField.valuele + "");
        strErrMsg = "deve essere " + strErrMsg + " !";
      }
      else
      {
        if ((typeof thisField.valueeq != 'undefined') && (thisField.valueeq != '')) strErrMsg = strErrMsg += "uguale a " + thisField.valueeq + "";
        if ((typeof thisField.valuene != 'undefined') && (thisField.valuene != '')) strErrMsg = strErrMsg += (strErrMsg == ""?"":" e ") + "diverso da " + thisField.valuene + "";
        if ((typeof thisField.valuege != 'undefined') && (thisField.valuege != '')) strErrMsg = strErrMsg += (strErrMsg == ""?"":" e ") + "maggiore o uguale a " + thisField.valuege + "";
        if ((typeof thisField.valuegt != 'undefined') && (thisField.valuegt != '')) strErrMsg = strErrMsg += (strErrMsg == ""?"":" e ") + "maggiore di " + thisField.valuegt + " (escluso)";
        if ((typeof thisField.valuelt != 'undefined') && (thisField.valuelt != '')) strErrMsg = strErrMsg += (strErrMsg == ""?"":" e ") + "minore di " + thisField.valuelt + " (escluso)";
        if ((typeof thisField.valuele != 'undefined') && (thisField.valuele != '')) strErrMsg = strErrMsg += (strErrMsg == ""?"":" e ") + "minore o uguale a " + thisField.valuele + "";
        strErrMsg = "deve avere un valore " + strErrMsg + " !";
      }
      break;
    default :
      strErrMsg = "non è corretto!";
      break;
  }

  if (strErrMsg != "")
    if ((typeof thisField.title == 'undefined') || (thisField.title == ""))
      strReturn = "Il campo " + thisField.name.toUpperCase() + " " + strErrMsg;
    else
      strReturn = "Il campo \"" + thisField.title + "\" " + strErrMsg;

  return strReturn;
}

//
// Restituisce la stringa completa per il messaggio di errore dei campi sbagliati.
//
function strWrong(thisForm)
{

  var i = 0;
  var strReturn = "";

  if (thisForm.wrongFields.length > 0)
  {
    var strErrMsg = "";
    var strThisField = "";

    strThisField = thisForm.wrongFields[0];
    thisField = eval(thisForm.name + '.' + strThisField);

    strErrMsg = strWrongField(thisField)

    strReturn += strErrMsg;

  }

  return strReturn;
}

//
// Setta il valore di un campo eseguendo la onChange.
//
function setValue(thisField, valore, forceCheck)
{
  var i = 0;
  var strValue = '';

  if (thisField.type.toUpperCase() == 'RADIO')
  {
    campo = document.getElementsByName(thisField.name);
    for (i=0; i<campo.length; i++)
    {
      campo[i].checked = (i == valore);
    }
  }
  else
  {
    switch (thisField.type.toUpperCase())
    {
      case 'SELECT-ONE' :
        thisField.selectedIndex = valore;
        break;
      case 'SELECT-MULTIPLE' :
        thisField.selectedIndex = valore;
        break;
      case 'CHECKBOX' :
        thisField.checked = valore;
        break;
      default :
        strValue = ''+valore;
        if (typeof thisField.transform != 'undefined')
          strValue = formatStringCF(strValue, thisField.transform);
        switch (thisField.kind.toUpperCase())
        {
          case 'NUMERO' :
          case 'VALUTA' :
            thisField.value = strValue;
            strValue = thisField.getValue();

            strValue = formatDoubleCF(strValue, thisField.decimali, thisField.kind);

            if (! thisField.migliaia)
              strValue = replaceChrCF(strValue, '.', '');
            
            thisField.value = strValue;

            break;
          case 'VALUTAINTERA' :
            thisField.value = strValue;
            strValue = thisField.getValue();

            strValue= formatIntegerCF(strValue, thisField.kind);

            if (! thisField.migliaia)
              strValue = replaceChrCF(strValue, '.', '');
            
            thisField.value = strValue;

            break;
          case 'DATA' :
            thisField.value = strValue;
            strValue = thisField.getValue();

            // Inserisco i separatori
            strValue = dataConverterCF(strValue);

            thisField.value = strValue;
            break;
          case 'ORA' :
            thisField.value = strValue;
            strValue = thisField.getValue();

            // Inserisco i separatori
            strValue = oraConverterCF(strValue);
            strValue = strValue.substr(0, thisField.maxLength);

            thisField.value = strValue;
            break;
          case 'ABI' :
          case 'CAB' :
          case 'CAP' :
            thisField.value = strValue;
            strValue = thisField.getValue();

            thisField.value = replicateChrCF('0', (5 -strValue.length)) + strValue;

            break;
          default :
            thisField.value = strValue;
      }
    }
  }

  thisField.changed=true;

  if (forceCheck == true)
  {
    thisField.isWrong();
    setColorField(thisField);
    thisField.wrongMsg();
  }
  else
  {
    removeFromWrongFields(thisField);
  }
}

//
// Restituisce il valore di un campo senza l'eventuale formattazione
// Vedere anche la getValueText()
//
function getValue(thisField, perDB)
{
  var i =0;
  var strValue = "";
  var strReturn = "";

  if (typeof perDB == 'undefined') perDB = false;

  if (thisField.type.toUpperCase() == 'RADIO')
  {
    strReturn = whoIsChecked(thisField);
  }
  else
  {
    switch (thisField.type.toUpperCase())
    {
      case 'SELECT-ONE' :
        strReturn = thisField.selectedIndex;
        break;
      case 'SELECT-MULTIPLE' :
        strReturn = thisField.selectedIndex;
        break;
      case 'CHECKBOX' :
        strReturn = thisField.checked;
        break;
      default :
        switch (thisField.kind.toUpperCase())
        {
          case 'NUMERO' :
          case 'VALUTA' :
            strValue = thisField.value;
            strValue = replaceChrCF(strValue, '.', '');
            arVirgole = strValue.split(',');
            if (arVirgole.length > 2) strValue = replaceChrCF(strValue, ',', '');
            arVirgole = strValue.split(',');
            if (arVirgole[0].length == 0)
            {
              arVirgole[0] = '0';
            }
            if (arVirgole.length == 1)
            {
              if (thisField.kind.toUpperCase() == 'NUMERO')
              {
                var zeriDopoVirgola = '';
                if (thisField.decimali.length > 0)
                  if (thisField.decimali.substr(0,1) == '9')
                  {
                    zeriDopoVirgola = replicateChrCF('0', (thisField.decimali.length));
                    strValue = arVirgole[0] + ',' + zeriDopoVirgola;
                  }
              }
              else
              {
                strValue = arVirgole[0] + ',00';
              }
            }
            else
            {
              if (thisField.kind.toUpperCase() == 'NUMERO')
              {
                var zeriDopoVirgola = '';
                if (thisField.decimali.length > 0)
                {
                  if (thisField.decimali.substr(0,1) == '9')
                  {
                    zeriDopoVirgola = replicateChrCF('0', (thisField.decimali.length - arVirgole[1].length));
                    arVirgole[1] = arVirgole[1] + zeriDopoVirgola;
                  }
                  arVirgole[1] = arVirgole[1].substr(0, thisField.decimali.length);
                }
		if (arVirgole[1] == '')
                  strValue = '';
		else
                  strValue = arVirgole[0] + ',' + arVirgole[1];
              }
              else
              {
                arVirgole[1] = arVirgole[1] + '00';
                arVirgole[1] = arVirgole[1].substr(0,2);
                strValue = arVirgole[0] + ',' + arVirgole[1];
              }
            }
            strReturn = strValue;
            break;
          case 'VALUTAINTERA' :
            strValue = thisField.value;
            strValue = replaceChrCF(strValue, '.', '');
            arVirgole = strValue.split(',');
            if (arVirgole.length > 2) strValue = replaceChrCF(strValue, ',', '');
            arVirgole = strValue.split(',');
            if (arVirgole[0].length == 0)
            {
              arVirgole[0] = '0';
            }
            strValue = arVirgole[0] + ',00';
            strReturn = strValue;
            break;
          case 'DATA' :
            strValue = thisField.value;
            strValue = replaceChrCF(strValue, '.', '/');
            strValue = replaceChrCF(strValue, ',', '/');
            strValue = replaceChrCF(strValue, '-', '/');
            arData = strValue.split('/');
            if (arData.length == 3)
            {
              if (arData[0].length == 1)
                strValue = '0' + arData[0];
              else
                strValue = arData[0];
              if (arData[1].length == 1)
                strValue = strValue + '0' + arData[1];
              else
                strValue = strValue + arData[1];
              if (arData[2].length == 3)
                strValue = strValue + '2' + arData[2];
              else
                {
                if (arData[2].length == 2)
                  strValue = strValue + '20' + arData[2];
                else
                  strValue = strValue + arData[2];
                }
            }
            strValue = replaceChrCF(strValue, '/', '');
            strReturn = strValue;
            break;
          case 'ORA' :
            strValue = thisField.value;
            strValue = replaceChrCF(strValue, '.', ':');
            strValue = replaceChrCF(strValue, ',', ':');
            strValue = replaceChrCF(strValue, '-', ':');
            arOra = strValue.split(':');
            if (arOra.length == 3)
            {
              if (arOra[0].length == 1)
                strValue = '0' + arOra[0];
              else
                strValue = arOra[0];
              if (arOra[1].length == 1)
                strValue = strValue + '0' + arOra[1];
              else
                strValue = strValue + arOra[1];
              if (arOra[2].length == 1)
                strValue = strValue + '0' + arOra[2];
              else
                strValue = strValue + arOra[2];
            }
            strValue = replaceChrCF(strValue, ':', '');
            strReturn = strValue;
            break;
          default :
            strReturn = thisField.value;
        }
      if (perDB == true)
        strReturn = strReturn.replace(/,/gi, '.');
    }
  }

  return (strReturn);

}

//
// Restituisce il valore "testuale" di un campo.
//
function getValueText(thisField)
{
  var i =0;
  var strReturn = "";

  if (thisField.type.toUpperCase() == 'RADIO')
  {
    strReturn = campo[whoIsChecked(thisField)].value;
  }
  else
  {
    switch (thisField.type.toUpperCase())
    {
      case 'SELECT-ONE' :
        strReturn = thisField[thisField.selectedIndex].text;
        break;
      case 'SELECT-MULTIPLE' :
        strReturn = thisField[thisField.selectedIndex].text;
        break;
      case 'CHECKBOX' :
        strReturn = thisField.checked;
        break;
      default :
        strReturn = thisField.value;
    }
  }

  return (strReturn);

}

//
// Restituisce il valore "numerico" di un campo.
// Vale solo per i kind=NUMERO oppure kind=VALUTA oppure kind=VALUTAINTERA.
//
function getValueNumber(thisField)
{
  var nReturn = 0.0;

  switch (thisField.kind.toUpperCase())
  {
    case 'NUMERO' :
    case 'VALUTA' :
    case 'VALUTAINTERA' :
      nReturn = parseFloat(replaceChrCF(thisField.getValue(), ',', '.'));
      if (isNaN(nReturn)) nReturn = 0.0;
  }

  return (nReturn);

}

//
// Lancia una url combinata con il valore del campo tramite la linkPost().
//
// IN SVILUPPO
//
function testFunction(thisField)
{
/*
  var urlTest = '';
  urlTest = thisField.testurl+thisField.getValue()+'&testResult=parent.main.document.'+thisField.form.name+'.'+thisField.name;
  var tmpOnBlur = thisField.onblur;
  var tmpOnChange = thisField.onchange;
  
  thisField.onblur = '';
  thisField.onchange = '';

  linkPost(urlTest, thisField.testframe);

  return thisField.testResult;
*/
}

function watchHandler(aProp, anOldVal, aNewVal)
{
var myText = "";
myText += "Property name ...: ";
myText += aProp;
myText += "\n";
myText += "Old value .......: ";
myText += anOldVal;
myText += "\n";
myText += "New value .......: ";
myText += aNewVal;
myText += "\n";
alert(myText);
return aNewVal;
}

//
// Formatta un numero con decimali
// Inserisce la virgola per i decimali e (se noMigliaia <> true) i punti delle miglialia
// Utilizzata dalle setValue...
//
function formatDoubleCF(valore, ndecimali, tipo, noMigliaia)
{
  var i = 0;
  var strValue = valore;
  var strInteri = '';
  var strInteriF = '';
  var strMeno = '';
  var strSeparatore = '.';
  
  if (arguments[3] != null)
    if (arguments[3] == true)
      strSeparatore = ' ';

  if (strValue.indexOf('-') > -1)
  {
    strMeno = '-';
    strValue = replaceChrCF(strValue, '-', '');
  }

  strValue = replaceChrCF(strValue, '.', ',');
  arCampi = strValue.split(',');
  strInteri = arCampi[0];
  if (strInteri  != '') strInteri = '' + parseInt(strInteri , 10);

  if (strInteri.length > 3)
  {
    for (var i=strInteri.length-3; i>=0; i=i-3)
    {
      strInteriF = strSeparatore + strInteri.substr(i,3) + strInteriF;
    }
    if ((strInteri.length%3) > 0)
    {
      strInteriF = strInteri.substr(0,(strInteri.length%3)) + strInteriF;
    }
    else
    {
      strInteriF = strInteriF.substr(1,strInteriF.length);
    }
  }
  else
  {
    strInteriF = strInteri;
  }
  if (tipo.toUpperCase() == 'NUMERO')
  {
    if (arCampi.length > 1)
    {
      var zeriDopoVirgola = '';
      if (ndecimali.length > 0)
      {
        if (ndecimali.substr(0,1) == '9')
        {
          zeriDopoVirgola = replicateChrCF('0', ndecimali.length);
          arCampi[1] = arCampi[1] + zeriDopoVirgola;
        }
        arCampi[1] = arCampi[1].substr(0, ndecimali.length);
      }
    }
  }
  if (tipo.toUpperCase() == 'VALUTA')
  {
    if (arCampi.length > 1)
    {
      arCampi[1] = arCampi[1] + '00';
      arCampi[1] = arCampi[1].substr(0, 2);
    }
    else
    {
      arCampi[1] = '00';
    }
  }
  if (arCampi.length > 1) strInteriF = strInteriF + ',' + arCampi[1];

  strInteriF = strMeno + strInteriF;
  strInteriF = replaceChrCF(strInteriF, ' ', '');

  return strInteriF

}


//
// Formatta un numero intero
// Inserisce i punti delle migliali e la virgola per i decimali
// Inserisce la virgola per i decimali e (se noMigliaia <> true) i punti delle miglialia
// Utilizzata dalle setValue...
//
function formatIntegerCF(valore, tipo, noMigliaia)
{
  var i = 0;
  var strValue = valore;
  var strInteri = '';
  var strInteriF = '';
  var strMeno = '';
  var strSeparatore = '.';
  
  if (arguments[2] != null)
    if (arguments[2] == true)
      strSeparatore = ' ';

  if (strValue.indexOf('-') > -1)
  {
    strMeno = '-';
    strValue = replaceChrCF(strValue, '-', '');
  }

  arCampi = strValue.split(',');
  strInteri = arCampi[0];
  if (strInteri  != '') strInteri = '' + parseInt(strInteri , 10);

  if (strInteri.length > 3)
  {
    for (var i=strInteri.length-3; i>=0; i=i-3)
    {
      strInteriF = strSeparatore + strInteri.substr(i,3) + strInteriF;
    }
    if ((strInteri.length%3) > 0)
    {
      strInteriF = strInteri.substr(0,(strInteri.length%3)) + strInteriF;
    }
    else
    {
      strInteriF = strInteriF.substr(1,strInteriF.length);
    }
  }
  else
  {
    strInteriF = strInteri;
  }
  if (arCampi.length > 1) strInteriF = strInteriF + ',00';

  strInteriF = strMeno + strInteriF;
  strInteriF = replaceChrCF(strInteriF, ' ', '');

  return strInteriF

}


//
// Formatta il case di una stringa
// Utilizzata dalle setValue...
//
function formatStringCF(valore, tipo)
{

  strValue = valore;

  switch (tipo.toUpperCase())
  {
    case 'NORMAL' :
      strReturn = strValue;
      break;
    case 'UPPER' :
      strReturn = strValue.toUpperCase();
      break;
    case 'LOWER' :
      strReturn = strValue.toLowerCase();
      break;
    case 'CAP' :
      strReturn = strValue.toCapitalize(true);
      break;
    case 'CAPALL' :
      strReturn = strValue.toCapitalize();
      break;
    default :
      strReturn = strValue;
  }

  return strReturn

}


/*
** Visualizza il testo passato sottoforma di Baloon Help
**
** textMsg	se è FALSE nasconde il Ballon Help
*/
function baloonHelpCF(textMsg)
{
	mouseMove(window.event);

	if (typeof textMsg != "undefined")
	{
		if (typeof textMsg == "string")
		{
			return overlib(textMsg, WIDTH, 200 );
		}
		else
		{
			if (typeof textMsg == "object")
			{
				if (textMsg.kind.toUpperCase() == "DATA")
				{
					if ((textMsg.readOnly != true) && (textMsg.disabled != true) && (textMsg.calendar == true))
					{
						return overlib(textMsg.baloonHelp, WIDTH, 200 );
					}
					else
					{
						nd();
					}
				}
				else
				{
					if(typeof textMsg.baloonHelp != "undefined")
					{
						return overlib(textMsg.baloonHelp, WIDTH, 200 );
					}
					else
					{
						nd();
					}
				}
			}
			else
			{
				nd();
			}
		}
	}
	else
	{
		nd();
	}
}


// ***********************************************************************************
//
// DA QUI INIZIANO LE FUNZIONI DI CONTROLLO DEI CAMPI IN BASE ALLA TIPOLOGIA (.kind)
//
// Per ovviare ad eventuali casi di omonimia è stato inserito il suffissio CF (CheckForm)
//
// ***********************************************************************************

/*
Verifica se è una data reale
*/
function isDataRealeCF(dataValore)
{
        var bBisestile = false;

        var iGiorno = 0;
        var iMese = 0;
        var iAnno = 0;

	if (dataValore.length != 8)
      	  return false;

        iGiorno = parseInt(dataValore.substr(0,2), 10);
        iMese = parseInt(dataValore.substr(2,2), 10);
        iAnno = parseInt(dataValore.substr(4,4), 10);

        if ( (iAnno%4)==0 )
        {
                if ( (iAnno%400)==0 )
                {
                        bBisestile=true;
                }
                else
                {
                        if ( (iAnno%100)==0 )
                        {
                                bBisestile=false;
                        }
                        else
                        {
                                bBisestile=true;
                        }
                }
        }
        else
        {
                bBisestile=false;
        }

        if ( ((iMese==4) || (iMese==6) || (iMese==9) || (iMese==11)) && ((iGiorno>=1) && (iGiorno<=30)) )
        {
                return true;
        }
        else
        {
                if ( ((iMese==1) || (iMese==3) || (iMese==5) || (iMese==7) || (iMese==8) || (iMese==10) || (iMese==12)) && ((iGiorno>=1) && (iGiorno<=31)) )
                {
                        return true;
                }
                else
                {
                        if ( (iMese==2) && ( ((iGiorno>=1) && (iGiorno<=29)) && (bBisestile==true) || ((iGiorno>=1) && (iGiorno<=28)) && (bBisestile==false) ) )
                        {
                                return true;
                        }
                        else
                        {
                                return false;
                        }
                }
        }
}


/*
Verifica se è un'ora reale
*/
function isOraRealeCF(oraValore)
{
        var iOra = 0;
        var iMinuti = 0;
        var iSecondi = 0;

	if (oraValore.length < 2)
      	  return false;
	if (oraValore.length >= 2)
	        iOra = parseInt(oraValore.substr(0,2), 10);
	if (oraValore.length >= 4)
	        iMinuti = parseInt(oraValore.substr(2,2), 10);
	if (oraValore.length >= 6)
	        iSecondi = parseInt(oraValore.substr(4,2), 10);

	if (iOra >=24) return false;
	if (iMinuti >=60) return false;
	if (iSecondi >=60) return false;
	
	return true;

}


/*
Verifica se una email è attendibile
*/
function isEmailRealeCF(emailStr) {
	
	// 1 - controlla il TLD; 0 - non effettua il controlla
	var checkTLD=1;
	
	// Elenco dei suffissi dei domini accettati
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	
	var emailPat=/^(.+)@(.+)$/;
	
	// Caratteri non accettati
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	
	var validChars="\[^\\s" + specialChars + "\]";
	
	var quotedUser="(\"[^\"]*\")";
	
	// Per controllare eventuali email con indirizzo IP
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	
	var atom=validChars + '+';
	
	var word="(" + atom + "|" + quotedUser + ")";
	
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	
	var matchArray=emailStr.match(emailPat);
	
	if (matchArray==null) return false;

	var user=matchArray[1];
	var domain=matchArray[2];
	
	for (i=0; i<user.length; i++)
	{
		if (user.charCodeAt(i)>127) return false;
	}
	for (i=0; i<domain.length; i++)
	{
		if (domain.charCodeAt(i)>127) return false;
	}
	if (user.match(userPat)==null) return false;
	
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null)
	{
		for (var i=1;i<=4;i++)
		{
			if (IPArray[i]>255) return false;
		}
		return true;
	}
	
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++)
	{
		if (domArr[i].search(atomPat)==-1) return false;
	}
	
	if (checkTLD && domArr[domArr.length-1].length!=2 &&
		domArr[domArr.length-1].search(knownDomsPat)==-1) return false;
	
	if (len<2) return false;
	
	return true; // Email OK !!
}


/*
Verifica se un Codice Fiscale è attendibile
*/
function isCodiceFiscaleRealeCF(strFiscale, aEccezioniValide, aEccezioniNonValide){
	
	strFiscale = strFiscale.toUpperCase();
	var cost="010005070913151719210100050709131517192102041820110306081214161022252423";
	var alfabeto="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var numeri="0123456789";
	var numero1=0;
	var numero2=0;
	
	if (aEccezioniValide != null)
	{
		if (aEccezioniValide.search(strFiscale) > -1) return true;
	}

	if (aEccezioniNonValide != null)
	{
		if (aEccezioniNonValide.search(strFiscale) > -1) return false;
	}
	
	for(var w=2;w<15;w+=2)
	{
		var car=strFiscale.substring(w-1,w);
		if(alfabeto.indexOf(car)>-1)
			numero1=numero1+alfabeto.indexOf(car);
		else
			numero1=numero1+eval(car);
	}

	for(var w=1;w<16;w+=2)
	{
		car=strFiscale.substring(w-1,w);
		if(alfabeto.indexOf(car)>-1)
			n=alfabeto.indexOf(car)+11;
		else
			n=numeri.indexOf(car)+1;
		numero2=numero2+eval(cost.substring((n*2)-2,((n*2))));
	}
	
	if(strFiscale.substring(15,16)!=alfabeto.charAt((numero1+numero2)%26)) return false;

	return true;
}


/*
Verifica se una P.Iva è corretta
*/
function isPartitaIvaRealeCF(strPIva, aEccezioniValide, aEccezioniNonValide){

	var nEvenDigitTotal = 0;
	var nEvenDigitTwice = 0;
	var nOddDigitTotal = 0;
	var nInt = 0;
	var nRest = 0;
	var nIndex = 0;
	var nRightCheckDigit = 0;

	if (aEccezioniValide != null)
	{
		if (aEccezioniValide.search(strPIva) > -1) return true;
	}

	if (aEccezioniNonValide != null)
	{
		if (aEccezioniNonValide.search(strPIva) > -1) return false;
	}

	if (strPIva.length != 11) return false;
	for (nIndex = 1; nIndex < 11; nIndex++)
	{
		if (nIndex % 2){
		  nOddDigitTotal = nOddDigitTotal + Number(strPIva.substr(nIndex-1, 1));
		}
		else
		{
			nEvenDigitTwice = 2 * Number(strPIva.substr(nIndex-1, 1));
			nInt = (( (nEvenDigitTwice-(nEvenDigitTwice % 10)) / 10) - ( (nRest-(nRest % 10)) / 10));
			if (nInt > 0)
			{
				nRest = nEvenDigitTwice % 10;
				nEvenDigitTotal = nEvenDigitTotal + nInt + nRest;
			}
			else
				nEvenDigitTotal = nEvenDigitTotal + nEvenDigitTwice;
		}
	}
	nRightCheckDigit = 10 - ((nEvenDigitTotal + nOddDigitTotal) % 10);
	if (nRightCheckDigit == 10) nRightCheckDigit = 0;

	return (nRightCheckDigit == Number(strPIva.charAt(strPIva.length-1)));

}


/*
Aggiunge (o Sottrae) qtaD giorni dalla data strData, lavora con il formato GG/MM/AAAA
*/
function addDayCF(strData, qtaD)
{
	var strD = strData.substr(0,2);
	var strM = strData.substr(3,2);
	var strY = strData.substr(6,4);

	var newD = parseInt(strD, 10);
	newD = newD + qtaD;

	strD = '' + newD;

	var newData = new Date(parseInt(strY, 10), parseInt(strM, 10), parseInt(strD, 10));
	
	strD = '' + newData.getDate();
	strM = '' + (newData.getMonth() + 1);
	strY = '' + newData.getYear();

	strD = replicateChrCF('0', (2 - strD.length)) + strD;
	strM = replicateChrCF('0', (2 - strM.length)) + strM;

	return (strD + '/' + strM + '/' + strY);
	
}


/*
Aggiunge (o Sottrae) qtaM mesi dalla data strData, lavora con il formato GG/MM/AAAA
*/
function addMonthCF(strData, qtaM)
{
	var strD = strData.substr(0,2);
	var strM = strData.substr(3,2);
	var strY = strData.substr(6,4);

	var newM = parseInt(strM,10);
	newM = newM + qtaM;

	strM = '' + newM;

	var newData = new Date(parseInt(strY, 10), parseInt(strM, 10), parseInt(strD, 10));
	
	strD = '' + newData.getDate();
	strM = '' + (newData.getMonth() + 1);
	strY = '' + newData.getYear();

	strD = replicateChrCF('0', (2 - strD.length)) + strD;
	strM = replicateChrCF('0', (2 - strM.length)) + strM;

	return (strD + '/' + strM + '/' + strY);
	
}


/*
Aggiunge (o Sottrae) qtaY anni dalla data strData, lavora con il formato GG/MM/AAAA
*/
function addYearCF(strData, qtaY)
{
	var strD = strData.substr(0,2);
	var strM = strData.substr(3,2);
	var strY = strData.substr(6,4);

	var newY = parseInt(strY, 10);
	newY = newY + qtaY;

	strY = '' + newY;

	var newData = new Date(parseInt(strY, 10), parseInt(strM, 10), parseInt(strD, 10));
	
	strD = '' + newData.getDate();
	strM = '' + (newData.getMonth() + 1);
	strY = '' + newData.getYear();

	strD = replicateChrCF('0', (2 - strD.length)) + strD;
	strM = replicateChrCF('0', (2 - strM.length)) + strM;

	return (strD + '/' + strM + '/' + strY);
	
}

// ***********************************************************************************
//
// Aggiunta dei metodi per l'oggetto Date()
//
// Indispensabile per la gestione dei campi con .kind = "DATA"
//
// ***********************************************************************************

//
//  addDay(giorni)
//
Date.prototype.addDay = function(giorni)
{
	this.setDate(this.getDate() + giorni);
}
//
//  addMonth(mesi [, solare])
//
Date.prototype.addMonth = function(mesi, solare)
{
	if (typeof solare == 'undefined')
		solare = false;
	if (solare)
	{
//		Solare, es.: 31/08 + 1 mese = 01/10
		this.setMonth(this.getMonth() + mesi);
	}
	else
	{
//		Commerciale, es.: 31/08 + 1 mese = 30/09
		var dataTmp = new Date();
		dataTmp.setDataFormattata('01/'+this.getDataFormattata('MMsAAAA'));
		dataTmp.setMonth(dataTmp.getMonth() + mesi);
		if (this.getDate() > dataTmp.getLastDay())
			dataTmp.setDate(dataTmp.getLastDay());
		else
			dataTmp.setDate(this.getDate());
		this.setDataFormattata(dataTmp.getDataFormattata());
	}
}
//
//  addYear(anni [, solare])
//
Date.prototype.addYear = function(anni, solare)
{
	if (typeof solare == 'undefined')
		solare = false;
	if (solare)
	{
//		Solare, es.: 29/02/2004 + 1 anno = 28/02/2005
		this.setYear(this.getYear() + anni);
	}
	else
	{
//		Commerciale, es.: 29/02/2004 + 1 anno = 01/03/2005
		var dataTmp = new Date();
		dataTmp.setDataFormattata('01/'+this.getDataFormattata('MMsAAAA'));
		dataTmp.setFullYear(dataTmp.getFullYear() + anni);
		if (this.getDate() > dataTmp.getLastDay())
			dataTmp.setDate(dataTmp.getLastDay());
		else
			dataTmp.setDate(this.getDate());
		this.setDataFormattata(dataTmp.getDataFormattata());
	}
}
Date.prototype.getGiorno = function()
{
	var strGiorno = '0' + this.getDate();
	strGiorno = strGiorno.substr((strGiorno.length - 2), 2);
	return strGiorno;
}
Date.prototype.getMese = function()
{
	var strMese = '0' + (this.getMonth() + 1);
	strMese = strMese.substr((strMese.length - 2), 2);
	return strMese;
}
Date.prototype.getAnno = function()
{
	var strAnno = '19' + this.getFullYear();
	strAnno = strAnno.substr((strAnno.length - 4), 4);
	return strAnno;
}
Date.prototype.getOra = function()
{
	var strOra = '0' + this.getHours();
	strOra = strOra.substr((strOra.length - 2), 2);
	return strOra;
}
Date.prototype.getMinuto = function()
{
	var strMinuto = '0' + this.getMinutes();
	strMinuto = strMinuto.substr((strMinuto.length - 2), 2);
	return strMinuto;
}
Date.prototype.getSecondo = function()
{
	var strSecondo = '0' + this.getSeconds();
	strSecondo = strSecondo.substr((strSecondo.length - 2), 2);
	return strSecondo;
}
Date.prototype.setGiorno = function(valore)
{
	this.setDate(parseFloat(''+valore));
}
Date.prototype.setMese = function(valore)
{
	this.setMonth(parseFloat(''+valore) - 1);
}
Date.prototype.setAnno = function(valore)
{
	this.setFullYear(parseFloat(''+valore));
}
Date.prototype.setOra = function(valore)
{
	this.setHours(parseFloat(''+valore));
}
Date.prototype.setMinuto = function(valore)
{
	this.setMinutes(parseFloat(''+valore));
}
Date.prototype.setSecondo = function(valore)
{
	this.setSeconds(parseFloat(''+valore));
}
Date.prototype.getLastDay = function()
{
	var mese = this.getMonth();
	
	if (mese == 3 || mese == 5 || mese == 8 || mese == 10) {
		return 30;
	} else if (mese == 1 && this.isBisestile()) {
		return 29;
	} else if (mese == 1 && !this.isBisestile()) {
		return 28;
	} else {
		return 31;
	}
}
Date.prototype.isBisestile = function()
{
	var resto = (this.getYear() % 400);
	if (resto!=0) {
		resto = this.getYear() % 4;
		if( resto ==0) {
			return true;
		}
	}
	return false;
}
//
//  getDataFormattata([formato [, separatore]])
//
Date.prototype.getDataFormattata = function(formato, separatore)
{
	var strData = '';

	if (typeof formato == 'undefined')
		formato = 'GGsMMsAAAA';
	if (typeof separatore == 'undefined')
		separatore = '/';

	rExpS = /s/g;
	rExpGG = /GG/g;
	rExpMM = /MM/g;
	rExpAAAA = /AAAA/g;

	strData = formato;
	strData = strData.replace(rExpS, separatore);
	strData = strData.replace(rExpGG, this.getGiorno());
	strData = strData.replace(rExpMM, this.getMese());
	strData = strData.replace(rExpAAAA, this.getAnno());

	return strData;
}
//
//  setDataFormattata(valore [,formato])
//
Date.prototype.setDataFormattata = function(valore, formato)
{
	if (typeof formato == 'undefined')
		formato = 'GGsMMsAAAA';

	var anno, mese, giorno;
	if (formato.indexOf('AAAA') > -1)
		anno = parseFloat(valore.substr(formato.indexOf('AAAA'), 4));
	if (formato.indexOf('MM') > -1)
		mese = parseFloat((valore.substr(formato.indexOf('MM'), 2))) - 1;
	if (formato.indexOf('GG') > -1)
		giorno = parseFloat(valore.substr(formato.indexOf('GG'), 2));

	this.setFullYear(anno, mese, giorno);
	this.setHours(0, 0, 0, 0);
}
//
//  getOraFormattata([formato [, separatore]])
//
Date.prototype.getOraFormattata = function(formato, separatore)
{
	var strOra = '';

	if (typeof formato == 'undefined')
		formato = 'OOsMMsSS';
	if (typeof separatore == 'undefined')
		separatore = ':';

	rExpS = /s/g;
	rExpOO = /OO/g;
	rExpMM = /MM/g;
	rExpSS = /SS/g;

	strOra = formato;
	strOra = strOra.replace(rExpS, separatore);
	strOra = strOra.replace(rExpOO, this.getOra());
	strOra = strOra.replace(rExpMM, this.getMinuto());
	strOra = strOra.replace(rExpSS, this.getSecondo());

	return strOra;
}
//
//  setOraFormattata(valore [,formato])
//
Date.prototype.setOraFormattata = function(valore, formato)
{
	if (typeof formato == 'undefined')
		formato = 'OOsMMsSS';

	var ora = 0;
	var minuto = 0;
	var secondo = 0;
	if (formato.indexOf('SS') > -1)
		secondo = parseFloat(valore.substr(formato.indexOf('SS'), 2));
	if (formato.indexOf('MM') > -1)
		minuto = parseFloat(valore.substr(formato.indexOf('MM'), 2));
	if (formato.indexOf('OO') > -1)
		ora = parseFloat(valore.substr(formato.indexOf('OO'), 2));

//	this.setFullYear(anno, mese, giorno);
	this.setHours(ora, minuto, secondo, 0);
}
//
// calcolaDifferenzaGiorni(valore [,formato])
//
Date.prototype.calcolaDifferenzaGiorni = function(valore, formato)
{	
	if (typeof formato == 'undefined') formato = 'GGsMMsAAAA';

	dataConvertita = new Date();
	dataConvertita.setDataFormattata(valore, formato);

	var dat1 =this.getTime(); 
	var dat2 =dataConvertita.getTime();

	var diffMillesecondi = dat1-dat2; 

	var calcola = diffMillesecondi / 86400000; // 86400000 Millesecondi presenti in un giorno  

	return calcola;
}
//
// calcolaDifferenzaGiorniCommerciale(valore [,formato])
// può restituire anche un valore negativo
//
Date.prototype.calcolaDifferenzaGiorniCommerciale = function(valore, formato)
{	
	if (typeof formato == 'undefined') formato = 'GGsMMsAAAA';

	dataConvertita = new Date();
	dataConvertita.setDataFormattata(valore, formato);

	var giorno1 = this.getDate();
	var giorno2 = dataConvertita.getDate();
	if (giorno1 == 31)
		giorno1 = 30;
	if (giorno2 == 31)
		giorno2 = 30;
	
	var diffMesi = this.calcolaDifferenzaMesi(valore, formato);
	
	if (diffMesi == 0){
		calcola = giorno1 - giorno2;
	}else{
		if (diffMesi > 0){
			diffMesi --;
			calcola = diffMesi * 30 + ((30 - giorno2) + giorno1);	
		}else{
			diffMesi ++;
			calcola = diffMesi * 30 - ((30 - giorno1) + giorno2);
		}
	}
	return calcola;
}
//
// calcolaDifferenzaMesi(valore [,formato])
//
Date.prototype.calcolaDifferenzaMesi = function(valore, formato)
{	
	if (typeof formato == 'undefined') formato = 'GGsMMsAAAA';

	dataConvertita = new Date();
	dataConvertita.setDataFormattata(valore, formato);

	var anno1 = this.getFullYear(); 
	var anno2 = dataConvertita.getFullYear();

	var mese1 = this.getMonth(); 
	var mese2 = dataConvertita.getMonth();

	var diffMesi = ((anno1 - anno2) * 12) + (mese1 - mese2); 

	return diffMesi;
}
//
// calcolaDifferenzaAnni(valore [,formato])
//
Date.prototype.calcolaDifferenzaAnni = function(valore, formato)
{	
	if (typeof formato == 'undefined') formato = 'GGsMMsAAAA';

	dataConvertita = new Date();
	dataConvertita.setDataFormattata(valore, formato);

	var anno1 = this.getFullYear(); 
	var anno2 = dataConvertita.getFullYear();

	var diffAnni = (anno1 - anno2); 

	return diffAnni ;
}
//
//  calcolaEtaAttuariale(valore [,tipoData [,formato]])
//
//	tipoData	A -> passo la data di riferimento
//			N -> passo la data di nascita
//
Date.prototype.calcolaEtaAttuariale = function(valore, tipoData, formato)
{
	if (typeof tipoData == 'undefined') tipoData = 'A';
	if (typeof formato == 'undefined') formato = 'GGsMMsAAAA';

	if (tipoData == 'A')
	{
		dataNascita = this;
		dataDecorrenza = new Date();
		dataDecorrenza.setDataFormattata(valore, formato);
	}
	else
	{
		dataNascita = new Date();
		dataNascita.setDataFormattata(valore, formato);
		dataDecorrenza = this;
	}

	dataCompleanno = new Date(dataDecorrenza.getYear(), dataNascita.getMonth(), dataNascita.getDate(), 0, 0, 0, 0);
	
	if (parseFloat(dataCompleanno.getTime()) > parseFloat(dataDecorrenza.getTime())) 
	{
		dataCompleanno.addYear(-1);
	}

	newDataCompleanno = new Date();
	newDataCompleanno.setDataFormattata(dataCompleanno.getDataFormattata());
	newDataCompleanno.addMonth(6);

	var deltaAnno = 0;
	if (newDataCompleanno.getTime() < dataDecorrenza.getTime())
	{
		deltaAnno = 1;
	}

	return (dataCompleanno.getFullYear() - dataNascita.getFullYear() + deltaAnno);
}
//
//  calcolaEta(valore [,tipoData [,formato]])
//
//	tipoData	A -> passo la data di riferimento
//			N -> passo la data di nascita
//
Date.prototype.calcolaEta = function(valore, tipoData, formato)
{
	if (typeof tipoData == 'undefined') tipoData = 'A';
	if (typeof formato == 'undefined') formato = 'GGsMMsAAAA';

	if (tipoData == 'A')
	{
		dataNascita = this;
		dataDecorrenza = new Date();
		dataDecorrenza.setDataFormattata(valore, formato);
	}
	else
	{
		dataNascita = new Date();
		dataNascita.setDataFormattata(valore, formato);
		dataDecorrenza = this;
	}

	dataCompleanno = new Date(dataDecorrenza.getYear(), dataNascita.getMonth(), dataNascita.getDate(), 0, 0, 0, 0);
	
	var deltaAnno = 0;
	if (dataCompleanno.getTime() >= dataDecorrenza.getTime())
	{
		deltaAnno = 1;
	}

	return (dataCompleanno.getFullYear() - dataNascita.getFullYear() - deltaAnno);
}

// ***********************************************************************************
//
// Aggiunta dei metodi per l'oggetto Array()
//
// ***********************************************************************************
//
//  search(valore)
//
//	valore	è la stringa da cercare e si ferma al primo trovato
//		è possibile utilizzare il carattere jolly "%"
//
Array.prototype.search = function(valore)
{
	var valoreTmp = valore;
  	if ((valore.substr(0,1) != '%') && (valore.substr(0,valore.length) != '%'))
  	{
		for (var i=0; i<this.length; i++)
 			if (this[i]==valore) return i;
  	}
  	if ((valore.substr(0,1) == '%') && (valore.substr(0,valore.length) == '%'))
  	{
  		valoreTmp = valore.substr(0, (valore.length - 1))
  		valoreTmp = valoreTmp.substr(1, valoreTmp.length)
		for (var i=0; i<this.length; i++)
 			if (this[i].indexOf(valoreTmp) > 0) return i;
  	}
  	if ((valore.substr(0,1) == '%') && (valore.substr(0,valore.length) != '%'))
  	{
  		valoreTmp = valore.substr(0, (valore.length - 1))
  		valoreTmp = valoreTmp.substr(1, valoreTmp.length)
		for (var i=0; i<this.length; i++)
 			if (this[i].indexOf(valoreTmp) == (this[i].length - valoreTmp.length)) return i;
  	}
  	if ((valore.substr(0,1) != '%') && (valore.substr(0,valore.length) == '%'))
  	{
  		valoreTmp = valore.substr(0, (valore.length - 1))
  		valoreTmp = valoreTmp.substr(1, valoreTmp.length)
		for (var i=0; i<this.length; i++)
 			if (this[i].indexOf(valoreTmp) == 0) return i;
  	}

//	Se arriva quì, vuol dire che non ha trovato in nessun caso la valore
	return -1;
}


//
//  add(valore)
//
//	valore	è la stringa da inserire
//
Array.prototype.add = function(valore)
{
	var lunghezza = this.length;
	
	lunghezza = lunghezza + 1;
	
	this.length = lunghezza;
	
	this[lunghezza-1] = valore;
}


// ***********************************************************************************
//
// Aggiunta dei metodi per l'oggetto String()
//
// ***********************************************************************************
//
//  toCapitalize(sentence, forceLower)
//
//	sentece ->	se è FALSE lavora sulle parole [default]
//			se è TRUE lavora sulle frasi
//
//	forceLower ->	se è FALSE lascia i caratteri maiuscoli inalterati [default]
//			se è TRUE forza i rimanenti caratteri in muniscolo
//
//
String.prototype.toCapitalize = function(sentence, forceLower)
{
	var valore = this.toString();
	if (typeof sentence == 'undefined') sentence = false;
	if (typeof forceLower == 'undefined') forceLower = false;

	valore = trimCF(valore);
	if (sentence == true)
	{
		var crlf_rExp = /\r\n/gi;
		valore = valore.replace(crlf_rExp, " ");
		var valoreTmp = valore + ".";
	}
	else
	{
		var valoreTmp = valore + " ";
	}

	if (sentence == true)
	{
		var non_alphanumerics_rExp = /[\!\?]+/gi;
		var cleanedStr = valoreTmp.replace(non_alphanumerics_rExp, ".");
		var splitString = cleanedStr.split(".");
	}
	else
	{
		var non_alphanumerics_rExp = /[^A-Za-z0-9àòèéìù]+/gi;
		var cleanedStr = valoreTmp.replace(non_alphanumerics_rExp, " ");
		var splitString = cleanedStr.split(" ");
	}

	for (var i=0; i<(splitString.length -1); i++)
	{
		splitString[i] = trimCF(splitString[i]);

		rExpTmp = eval('/' + splitString[i] + '/gi');
	
		if (splitString[i].length == 1)
			splitString[i] = splitString[i].toUpperCase();
		else
			if (forceLower == true)
				splitString[i] = splitString[i].substr(0, 1).toUpperCase() + splitString[i].substr(1, (splitString[i].length-1)).toLowerCase();
			else
				splitString[i] = splitString[i].substr(0, 1).toUpperCase() + splitString[i].substr(1, (splitString[i].length-1)).toString();

		valore = valore.replace(rExpTmp, splitString[i]);
	}

	return valore;
}


// ***********************************************************************************
//
// Aggiunta dei metodi per l'oggetto Math()
//
// ***********************************************************************************
//
//  roundTo(valoreDaArrotondare, decimali)
//
//	Arrotonda il valore in base ai numeri decimali passati
//
//	valoreDaArrotondare ->	Valore da arrotondare
//
//	decimali ->		Q.tà di decimali voluta
//
//
Math.roundTo = new Function('valore', 'decimali', 'return roundToCF(valore, decimali)');

function roundToCF(valoreDaArrotondare, decimali)
{
	if (decimali < 0) return 0.0;

	var arrotondaPer = parseFloat(Math.pow(10, decimali), 10);

	var valore = 0.0;

	if (arrotondaPer == 0)
	{
		valore = parseFloat(parseInt(valoreDaArrotondare, 10), 10);
	}
	else
	{
		valore = valoreDaArrotondare * arrotondaPer;
		valore = Math.round(valore);
		valore = parseFloat((parseFloat(valore, 10) / arrotondaPer), 10);
	}

	return valore;
}


// ***********************************************************************************
//
// Inizializzazione e gestione della parte del datePicker
//
// Indispensabile per la gestione dei campi con .kind = "DATA"
//
// ***********************************************************************************

var weekend = [0,6];
var weekendColor = "C0C0C0";
var fontface = "Verdana";
var fontsize = 8;			// in "pt" punti

var gNow = new Date();
var ggWinContent;
var ggPosX = -1;
var ggPosY = -1;

Calendar.Months = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno",
"Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"];
Calendar.DOMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
Calendar.lDOMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

function Calendar(p_item, p_month, p_year, p_format) {
	if ((p_month == null) && (p_year == null))	return;

	if (p_month == null) {
		this.gMonthName = null;
		this.gMonth = null;
		this.gYearly = true;
	} else {
		this.gMonthName = Calendar.get_month(p_month);
		this.gMonth = new Number(p_month);
		this.gYearly = false;
	}

	this.gYear = p_year;
	this.gFormat = p_format;
	this.gBGColor = "white";
	this.gFGColor = "black";
	this.gTextColor = "black";
	this.gHeaderColor = "black";
	this.gReturnItem = p_item;
}

Calendar.get_month = Calendar_get_month;
Calendar.get_daysofmonth = Calendar_get_daysofmonth;
Calendar.calc_month_year = Calendar_calc_month_year;

function Calendar_get_month(monthNo) {
	return Calendar.Months[monthNo];
}

function Calendar_get_daysofmonth(monthNo, p_year) {
	/* 
	Check for leap year ..
	1.Years evenly divisible by four are normally leap years, except for... 
	2.Years also evenly divisible by 100 are not leap years, except for... 
	3.Years also evenly divisible by 400 are leap years. 
	*/
	if ((p_year % 4) == 0) {
		if ((p_year % 100) == 0 && (p_year % 400) != 0)
			return Calendar.DOMonth[monthNo];
	
		return Calendar.lDOMonth[monthNo];
	} else
		return Calendar.DOMonth[monthNo];
}

function Calendar_calc_month_year(p_Month, p_Year, incr) {
	/* 
	Will return an 1-D array with 1st element being the calculated month 
	and second being the calculated year 
	after applying the month increment/decrement as specified by 'incr' parameter.
	'incr' will normally have 1/-1 to navigate thru the months.
	*/
	var ret_arr = new Array();
	
	if (incr == -1) {
		// INDIETRO
		if (p_Month == 0) {
			ret_arr[0] = 11;
			ret_arr[1] = parseInt(p_Year, 10) - 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month, 10) - 1;
			ret_arr[1] = parseInt(p_Year, 10);
		}
	} else if (incr == 1) {
		// AVANTI
		if (p_Month == 11) {
			ret_arr[0] = 0;
			ret_arr[1] = parseInt(p_Year, 10) + 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month, 10) + 1;
			ret_arr[1] = parseInt(p_Year, 10);
		}
	}
	
	return ret_arr;
}

function Calendar_calc_month_year(p_Month, p_Year, incr) {
	/* 
	Will return an 1-D array with 1st element being the calculated month 
	and second being the calculated year 
	after applying the month increment/decrement as specified by 'incr' parameter.
	'incr' will normally have 1/-1 to navigate thru the months.
	*/
	var ret_arr = new Array();
	
	if (incr == -1) {
		// B A C K W A R D
		if (p_Month == 0) {
			ret_arr[0] = 11;
			ret_arr[1] = parseInt(p_Year, 10) - 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month, 10) - 1;
			ret_arr[1] = parseInt(p_Year, 10);
		}
	} else if (incr == 1) {
		// F O R W A R D
		if (p_Month == 11) {
			ret_arr[0] = 0;
			ret_arr[1] = parseInt(p_Year, 10) + 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month, 10) + 1;
			ret_arr[1] = parseInt(p_Year, 10);
		}
	}
	
	return ret_arr;
}

// Questo serve x la compatibilità con Navigator 3
new Calendar();

Calendar.prototype.getMonthlyCalendarCode = function() {
	var vCode = "";
	var vHeader_Code = "";
	var vData_Code = "";
	
	// Begin Table Drawing code here..
	vCode += ("<div align=center><TABLE BORDER=1 BGCOLOR=\"" + this.gBGColor + "\" style='font-size:" + fontsize + "pt;'>");
	
	vHeader_Code = this.cal_header();
	vData_Code = this.cal_data();
	vCode += (vHeader_Code + vData_Code);
	
	vCode += "</TABLE></div>";
	
	return vCode;
}

Calendar.prototype.show = function() {
	var vCode = "";

	// build content into global var ggWinContent
	ggWinContent += ("<FONT FACE='" + fontface + "' ><B>");
	ggWinContent += (this.gMonthName + " " + this.gYear);
	ggWinContent += "</B><BR>";
	
	// Show navigation buttons
	var prevMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, -1);
	var prevMM = prevMMYYYY[0];
	var prevYYYY = prevMMYYYY[1];

	var nextMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, 1);
	var nextMM = nextMMYYYY[0];
	var nextYYYY = nextMMYYYY[1];
	
	ggWinContent += ("<TABLE WIDTH='100%' BORDER=1 CELLSPACING=0 CELLPADDING=0 BGCOLOR='#e0e0e0' style='font-size:" + fontsize + "pt;'><TR><TD ALIGN=center>");
	ggWinContent += ("[<A HREF=\"javascript:void(0);\" " +
		"onMouseOver=\"window.status='Indietro di un anno'; return true;\" " +
		"onMouseOut=\"window.status=''; return true;\" " +
		"onClick=\"Build(" + 
		"'" + this.gReturnItem + "', '" + this.gMonth + "', '" + (parseInt(this.gYear, 10)-1) + "', '" + this.gFormat + "'" +
		");" +
		"\">&lt;Anno<\/A>]</TD><TD ALIGN=center>");
	ggWinContent += ("[<A HREF=\"javascript:void(0);\" " +
		"onMouseOver=\"window.status='Indietro di un mese'; return true;\" " +
		"onMouseOut=\"window.status=''; return true;\" " +
		"onClick=\"Build(" + 
		"'" + this.gReturnItem + "', '" + prevMM + "', '" + prevYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\">&lt;Mese<\/A>]</TD><TD ALIGN=center>");
	ggWinContent += "       </TD><TD ALIGN=center>";
	ggWinContent += ("[<A HREF=\"javascript:void(0);\" " +
		"onMouseOver=\"window.status='Avanti di un mese'; return true;\" " +
		"onMouseOut=\"window.status=''; return true;\" " +
		"onClick=\"Build(" + 
		"'" + this.gReturnItem + "', '" + nextMM + "', '" + nextYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\">Mese&gt;<\/A>]</TD><TD ALIGN=center>");
	ggWinContent += ("[<A HREF=\"javascript:void(0);\" " +
		"onMouseOver=\"window.status='Avanti di un anno'; return true;\" " +
		"onMouseOut=\"window.status=''; return true;\" " +
		"onClick=\"Build(" + 
		"'" + this.gReturnItem + "', '" + this.gMonth + "', '" + (parseInt(this.gYear, 10)+1) + "', '" + this.gFormat + "'" +
		");" +
		"\">Anno&gt;<\/A>]</TD></TR></TABLE><BR>");

	// Get the complete calendar code for the month, and add it to the
	//	content var
	vCode = this.getMonthlyCalendarCode();
	ggWinContent += vCode;
}

Calendar.prototype.showY = function() {
	var vCode = "";
	var i;

	ggWinContent += "<FONT FACE='" + fontface + "' ><B>"
	ggWinContent += ("Year : " + this.gYear);
	ggWinContent += "</B><BR>";

	// Show navigation buttons
	var prevYYYY = parseInt(this.gYear, 10) - 1;
	var nextYYYY = parseInt(this.gYear, 10) + 1;
	
	ggWinContent += ("<TABLE WIDTH='100%' BORDER=1 CELLSPACING=0 CELLPADDING=0 BGCOLOR='#e0e0e0' style='font-size:" + fontsize + "pt;'><TR><TD ALIGN=center>");
	ggWinContent += ("[<A HREF=\"javascript:void(0);\" " +
		"onMouseOver=\"window.status='Go back one year'; return true;\" " +
		"onMouseOut=\"window.status=''; return true;\" " +
		"onClick=\"Build(" + 
		"'" + this.gReturnItem + "', null, '" + prevYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\"><<Year<\/A>]</TD><TD ALIGN=center>");
	ggWinContent += "       </TD><TD ALIGN=center>";
	ggWinContent += ("[<A HREF=\"javascript:void(0);\" " +
		"onMouseOver=\"window.status='Go forward one year'; return true;\" " +
		"onMouseOut=\"window.status=''; return true;\" " +
		"onClick=\"Build(" + 
		"'" + this.gReturnItem + "', null, '" + nextYYYY + "', '" + this.gFormat + "'" +
		");" +
		"\">Year>><\/A>]</TD></TR></TABLE><BR>");

	// Get the complete calendar code for each month.
	// start a table and first row in the table
	ggWinContent += ("<TABLE WIDTH='100%' BORDER=0 CELLSPACING=0 CELLPADDING=5 style='font-size:" + fontsize + "pt;'><TR>");
	var j;
	for (i=0; i<12; i++) {
		// start the table cell
		ggWinContent += "<TD ALIGN='center' VALIGN='top'>";
		this.gMonth = i;
		this.gMonthName = Calendar.get_month(this.gMonth);
		vCode = this.getMonthlyCalendarCode();
		ggWinContent += (this.gMonthName + "/" + this.gYear + "<BR>");
		ggWinContent += vCode;
		ggWinContent += "</TD>";
		if (i == 3 || i == 7) {
			ggWinContent += "</TR><TR>";
			}

	}

	ggWinContent += "</TR></TABLE></font><BR>";
}

Calendar.prototype.cal_header = function() {
	var vCode = "";
	
	vCode = vCode + "<TR>";
	vCode = vCode + "<TD WIDTH='14%'><FONT FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Dom</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Lun</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Mar</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Mer</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Gio</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='14%'><FONT FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Ven</B></FONT></TD>";
	vCode = vCode + "<TD WIDTH='16%'><FONT FACE='" + fontface + "' COLOR='" + this.gHeaderColor + "'><B>Sab</B></FONT></TD>";
	vCode = vCode + "</TR>";
	
	return vCode;
}

Calendar.prototype.cal_data = function() {
	var vDate = new Date();
	vDate.setDate(1);
	vDate.setMonth(this.gMonth);
	vDate.setFullYear(this.gYear);

	var vFirstDay=vDate.getDay();
	var vDay=1;
	var vLastDay=Calendar.get_daysofmonth(this.gMonth, this.gYear);
	var vOnLastDay=0;
	var vCode = "";

	/*
	Get day for the 1st of the requested month/year..
	Place as many blank cells before the 1st day of the month as necessary. 
	*/
	vCode = vCode + "<TR>";
	for (i=0; i<vFirstDay; i++) {
		vCode = vCode + "<TD align=center WIDTH='14%'" + this.write_weekend_string(i) + "><FONT FACE='" + fontface + "'> </FONT></TD>";
	}

	// Write rest of the 1st week
	for (j=vFirstDay; j<7; j++) {
		vCode = vCode + "<TD align=center WIDTH='14%'" + this.write_weekend_string(j) + "><FONT FACE='" + fontface + "'>" + 
			"<A HREF='javascript:void(0);' " + 
				"onMouseOver=\"window.status=' " + this.format_data(vDay) + "'; return true;\" " +
				"onMouseOut=\"window.status=' '; return true;\" " +
				"onClick=\"document." + this.gReturnItem + ".setValue('" + 
				this.format_data(vDay) + 
				"',true);ggPosX=-1;ggPosY=-1;document." + this.gReturnItem + ".focus();nd();nd()\">" + 
				this.format_day(vDay) + 
			"</A>" + 
			"</FONT></TD>";
		vDay=vDay + 1;
	}
	vCode = vCode + "</TR>";

	// Write the rest of the weeks
	for (k=2; k<7; k++) {
		vCode = vCode + "<TR>";

		for (j=0; j<7; j++) {
			vCode = vCode + "<TD align=center WIDTH='14%'" + this.write_weekend_string(j) + "><FONT FACE='" + fontface + "'>" + 
				"<A HREF='javascript:void(0);' " +
					"onMouseOver=\"window.status=' " + this.format_data(vDay) + "'; return true;\" " +
					"onMouseOut=\"window.status=' '; return true;\" " +
					"onClick=\"document." + this.gReturnItem + ".setValue('" + 
					this.format_data(vDay) + 
					"',true);ggPosX=-1;ggPosY=-1;document." + this.gReturnItem + ".focus();nd();nd()\">" + 
//					"',true);window.scroll(0,ggPosY);ggPosX=-1;ggPosY=-1;document." + this.gReturnItem + ".focus();nd();nd()\">" + 
				this.format_day(vDay) + 
				"</A>" + 
				"</FONT></TD>";
			vDay=vDay + 1;

			if (vDay > vLastDay) {
				vOnLastDay = 1;
				break;
			}
		}

		if (j == 6)
			vCode = vCode + "</TR>";
		if (vOnLastDay == 1)
			break;
	}
	
	// Fill up the rest of last week with proper blanks, so that we get proper square blocks
	for (m=1; m<(7-j); m++) {
		if (this.gYearly)
			vCode = vCode + "<TD align=center WIDTH='14%'" + this.write_weekend_string(j+m) + 
			"><FONT FACE='" + fontface + "' COLOR='gray'> </FONT></TD>";
		else
			vCode = vCode + "<TD align=center WIDTH='14%'" + this.write_weekend_string(j+m) + 
			"><FONT FACE='" + fontface + "' COLOR='gray'>" + m + "</FONT></TD>";
	}
	
	return vCode;
}

Calendar.prototype.format_day = function(vday) {
	var vNowDay = gNow.getDate();
	var vNowMonth = gNow.getMonth();
	var vNowYear = gNow.getFullYear();

	if (vday == vNowDay && this.gMonth == vNowMonth && this.gYear == vNowYear)
		return ("<FONT COLOR=\"RED\"><B>" + vday + "</B></FONT>");
	else
		return (vday);
}

Calendar.prototype.write_weekend_string = function(vday) {
	var i;

	// Return special formatting for the weekend day.
	for (i=0; i<weekend.length; i++) {
		if (vday == weekend[i])
			return (" BGCOLOR=\"" + weekendColor + "\"");
	}
	
	return "";
}

Calendar.prototype.format_data = function(p_day) {
	var vData;
	var vMonth = 1 + this.gMonth;
	vMonth = (vMonth.toString().length < 2) ? "0" + vMonth : vMonth;
	var vMon = Calendar.get_month(this.gMonth).substr(0,3).toUpperCase();
	var vFMon = Calendar.get_month(this.gMonth).toUpperCase();
	var vY4 = new String(this.gYear);
	var vY2 = new String(this.gYear.substr(2,2));
	var vDD = (p_day.toString().length < 2) ? "0" + p_day : p_day;

	switch (this.gFormat) {
		case "MM\/DD\/YYYY" :
			vData = vMonth + "\/" + vDD + "\/" + vY4;
			break;
		case "MM\/DD\/YY" :
			vData = vMonth + "\/" + vDD + "\/" + vY2;
			break;
		case "MM-DD-YYYY" :
			vData = vMonth + "-" + vDD + "-" + vY4;
			break;
		case "YYYY-MM-DD" :
			vData = vY4 + "-" + vMonth + "-" + vDD;
			break;
		case "MM-DD-YY" :
			vData = vMonth + "-" + vDD + "-" + vY2;
			break;
		case "DD\/MON\/YYYY" :
			vData = vDD + "\/" + vMon + "\/" + vY4;
			break;
		case "DD\/MON\/YY" :
			vData = vDD + "\/" + vMon + "\/" + vY2;
			break;
		case "DD-MON-YYYY" :
			vData = vDD + "-" + vMon + "-" + vY4;
			break;
		case "DD-MON-YY" :
			vData = vDD + "-" + vMon + "-" + vY2;
			break;
		case "DD\/MONTH\/YYYY" :
			vData = vDD + "\/" + vFMon + "\/" + vY4;
			break;
		case "DD\/MONTH\/YY" :
			vData = vDD + "\/" + vFMon + "\/" + vY2;
			break;
		case "DD-MONTH-YYYY" :
			vData = vDD + "-" + vFMon + "-" + vY4;
			break;
		case "DD-MONTH-YY" :
			vData = vDD + "-" + vFMon + "-" + vY2;
			break;
		case "DD\/MM\/YYYY" :
			vData = vDD + "\/" + vMonth + "\/" + vY4;
			break;
		case "DD\/MM\/YY" :
			vData = vDD + "\/" + vMonth + "\/" + vY2;
			break;
		case "DD-MM-YYYY" :
			vData = vDD + "-" + vMonth + "-" + vY4;
			break;
		case "DD-MM-YY" :
			vData = vDD + "-" + vMonth + "-" + vY2;
			break;
		default :
			vData = vMonth + "\/" + vDD + "\/" + vY4;
	}

	return vData;
}

function Build(p_item, p_month, p_year, p_format) {
	gCal = new Calendar(p_item, p_month, p_year, p_format);

	// Customize your Calendar here..
	gCal.gBGColor="white";
	gCal.gLinkColor="black";
	gCal.gTextColor="black";
	gCal.gHeaderColor="black";

	// initialize the content string
	ggWinContent = "";

	// Choose appropriate show function
	if (gCal.gYearly) {
		// and, since the yearly calendar is so large, override the positioning and fontsize
		// warning: in IE6, it appears that "select" fields on the form will still show
		//	through the "over" div; Note: you can set these variables as part of the onClick
		//	javascript code before you call the show_yearly_calendar function
		if (ggPosX == -1) ggPosX = 10;
		if (ggPosY == -1) ggPosY = 10;
		if (fontsize == 8) fontsize = 6;
		// generate the calendar
		gCal.showY();
		}
	else {
		gCal.show();
		}

	// if this is the first calendar popup, use autopositioning with an offset
/*
	if (ggPosX == -1 && ggPosY == -1) {
		overlib(ggWinContent, AUTOSTATUSCAP, STICKY, CLOSECLICK, CSSSTYLE,
			TEXTSIZEUNIT, "pt", TEXTSIZE, 8, CAPTIONSIZEUNIT, "pt", CAPTIONSIZE, 8, CLOSESIZEUNIT, "pt", CLOSESIZE, 8,
			CAPTION, "Calendario", OFFSETX, 20, OFFSETY, -20);
*/
		// save where the 'over' div ended up; we want to stay in the same place if the user
		//	clicks on one of the year or month navigation links
		if ( (ns4) || (ie4) ) {
		        ggPosX = parseInt(over.left, 10);
		        ggPosY = parseInt(over.top, 10);
			} else if (ns6) {
			ggPosX = parseInt(over.style.left, 10);
			ggPosY = parseInt(over.style.top, 10);
			}
/*
	} else {
		// we have a saved X & Y position, so use those with the FIXX and FIXY options
*/
		overlib(ggWinContent, AUTOSTATUSCAP, STICKY, CLOSECLICK, CSSSTYLE,
			TEXTSIZEUNIT, "pt", TEXTSIZE, 8, CAPTIONSIZEUNIT, "pt", CAPTIONSIZE, 8, CLOSESIZEUNIT, "pt", CLOSESIZE, 8,
			CAPTION, "Calendario", FIXX, ggPosX, FIXY, ggPosY, WIDTH, 200);
//		}
//	window.scroll(ggPosX, ggPosY);
}


function showCalendario(thisField) {
	
	var meseField = '';
	var annoField = '';

	if (!thisField.isWrong())
	{
		if (thisField.getValue() != '')
		{
			meseField = '' + parseInt(thisField.getValue().substr(2,2), 10) - 1;
			annoField = thisField.getValue().substr(4,4);
		}
	}
	show_calendar(thisField.form.name + '.' + thisField.name, meseField, annoField, 'DD/MM/YYYY');
}

function show_calendar() {
	/* 
		p_month : 0-11 for Jan-Dec; 12 for All Months.
		p_year	: 4-digit year
		p_format: Date format (mm/dd/yyyy, dd/mm/yy, ...)
		p_item	: Return Item.
	*/

	p_item = arguments[0];
	if (arguments[1] == "" || arguments[1] == null)
		p_month = new String(gNow.getMonth());
	else
		p_month = arguments[1];
	if (arguments[2] == "" || arguments[2] == null)
		p_year = new String(gNow.getFullYear().toString());
	else
		p_year = arguments[2];
	if (arguments[3] == null)
		p_format = "YYYY-MM-DD";
	else
		p_format = arguments[3];

	Build(p_item, p_month, p_year, p_format);
}
/*
Yearly Calendar Code Starts here
*/
function show_yearly_calendar() {
	// Load the defaults..
	//if (p_year == null || p_year == "")
	//	p_year = new String(gNow.getFullYear().toString());
	//if (p_format == null || p_format == "")
	//	p_format = "YYYY-MM-DD";

	p_item = arguments[0];
	if (arguments[1] == "" || arguments[1] == null)
		p_year = new String(gNow.getFullYear().toString());
	else
		p_year = arguments[1];
	if (arguments[2] == null)
		p_format = "YYYY-MM-DD";
	else
		p_format = arguments[2];

	Build(p_item, null, p_year, p_format);
}


// ***********************************************************************************
//
// Inizializzazione e gestione della parte del overDiv
//
// Serve per gestire una finestra di tipo Layer o Div
// Indispensabile per il datePicker e per il baloonHelpCF
//
// ***********************************************************************************

document.write('<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>');

var INARRAY=1;
var CAPARRAY=2;
var STICKY=3;
var BACKGROUND=4;
var NOCLOSE=5;
var CAPTION=6;
var LEFT=7;
var RIGHT=8;
var CENTER=9;
var OFFSETX=10;
var OFFSETY=11;
var FGCOLOR=12;
var BGCOLOR=13;
var TEXTCOLOR=14;
var CAPCOLOR=15;
var CLOSECOLOR=16;
var WIDTH=17;
var BORDER=18;
var STATUS=19;
var AUTOSTATUS=20;
var AUTOSTATUSCAP=21;
var HEIGHT=22;
var CLOSETEXT=23;
var SNAPX=24;
var SNAPY=25;
var FIXX=26;
var FIXY=27;
var FGBACKGROUND=28;
var BGBACKGROUND=29;
var PADX=30;
var PADY=31;
var FULLHTML=34;
var ABOVE=35;
var BELOW=36;
var CAPICON=37;
var TEXTFONT=38;
var CAPTIONFONT=39;
var CLOSEFONT=40;
var TEXTSIZE=41;
var CAPTIONSIZE=42;
var CLOSESIZE=43;
var FRAME=44;
var TIMEOUT=45;
var FUNCTION=46;
var DELAY=47;
var HAUTO=48;
var VAUTO=49;
var CLOSECLICK=50;
var CSSOFF=51;
var CSSSTYLE=52;
var CSSCLASS=53;
var FGCLASS=54;
var BGCLASS=55;
var TEXTFONTCLASS=56;
var CAPTIONFONTCLASS=57;
var CLOSEFONTCLASS=58;
var PADUNIT=59;
var HEIGHTUNIT=60;
var WIDTHUNIT=61;
var TEXTSIZEUNIT=62;
var TEXTDECORATION=63;
var TEXTSTYLE=64;
var TEXTWEIGHT=65;
var CAPTIONSIZEUNIT=66;
var CAPTIONDECORATION=67;
var CAPTIONSTYLE=68;
var CAPTIONWEIGHT=69;
var CLOSESIZEUNIT=70;
var CLOSEDECORATION=71;
var CLOSESTYLE=72;
var CLOSEWEIGHT=73;
if(typeof ol_fgcolor=='undefined'){var ol_fgcolor="#CCCCFF";}
if(typeof ol_bgcolor=='undefined'){var ol_bgcolor="#333399";}
if(typeof ol_textcolor=='undefined'){var ol_textcolor="#000000";}
if(typeof ol_capcolor=='undefined'){var ol_capcolor="#FFFFFF";}
if(typeof ol_closecolor=='undefined'){var ol_closecolor="#9999FF";}
if(typeof ol_textfont=='undefined'){var ol_textfont="Verdana,Arial,Helvetica";}
if(typeof ol_captionfont=='undefined'){var ol_captionfont="Verdana,Arial,Helvetica";}
if(typeof ol_closefont=='undefined'){var ol_closefont="Verdana,Arial,Helvetica";}
if(typeof ol_textsize=='undefined'){var ol_textsize="1";}
if(typeof ol_captionsize=='undefined'){var ol_captionsize="1";}
if(typeof ol_closesize=='undefined'){var ol_closesize="1";}
if(typeof ol_width=='undefined'){var ol_width="200";}
if(typeof ol_border=='undefined'){var ol_border="1";}
if(typeof ol_offsetx=='undefined'){var ol_offsetx=10;}
if(typeof ol_offsety=='undefined'){var ol_offsety=10;}
if(typeof ol_text=='undefined'){var ol_text="Default Text";}
if(typeof ol_cap=='undefined'){var ol_cap="";}
if(typeof ol_sticky=='undefined'){var ol_sticky=0;}
if(typeof ol_background=='undefined'){var ol_background="";}
if(typeof ol_close=='undefined'){var ol_close="Chiudi";}
if(typeof ol_hpos=='undefined'){var ol_hpos=8;}
if(typeof ol_status=='undefined'){var ol_status="";}
if(typeof ol_autostatus=='undefined'){var ol_autostatus=0;}
if(typeof ol_height=='undefined'){var ol_height=-1;}
if(typeof ol_snapx=='undefined'){var ol_snapx=0;}
if(typeof ol_snapy=='undefined'){var ol_snapy=0;}
if(typeof ol_fixx=='undefined'){var ol_fixx=-1;}
if(typeof ol_fixy=='undefined'){var ol_fixy=-1;}
if(typeof ol_fgbackground=='undefined'){var ol_fgbackground="";}
if(typeof ol_bgbackground=='undefined'){var ol_bgbackground="";}
if(typeof ol_padxl=='undefined'){var ol_padxl=1;}
if(typeof ol_padxr=='undefined'){var ol_padxr=1;}
if(typeof ol_padyt=='undefined'){var ol_padyt=1;}
if(typeof ol_padyb=='undefined'){var ol_padyb=1;}
if(typeof ol_fullhtml=='undefined'){var ol_fullhtml=0;}
if(typeof ol_vpos=='undefined'){var ol_vpos=36;}
if(typeof ol_aboveheight=='undefined'){var ol_aboveheight=0;}
if(typeof ol_caption=='undefined'){var ol_capicon="";}
if(typeof ol_frame=='undefined'){var ol_frame=self;}
if(typeof ol_timeout=='undefined'){var ol_timeout=0;}
if(typeof ol_function=='undefined'){var ol_function=Function();}
if(typeof ol_delay=='undefined'){var ol_delay=0;}
if(typeof ol_hauto=='undefined'){var ol_hauto=0;}
if(typeof ol_vauto=='undefined'){var ol_vauto=0;}
if(typeof ol_closeclick=='undefined'){var ol_closeclick=0;}
if(typeof ol_css=='undefined'){var ol_css=51;}
if(typeof ol_fgclass=='undefined'){var ol_fgclass="";}
if(typeof ol_bgclass=='undefined'){var ol_bgclass="";}
if(typeof ol_textfontclass=='undefined'){var ol_textfontclass="";}
if(typeof ol_captionfontclass=='undefined'){var ol_captionfontclass="";}
if(typeof ol_closefontclass=='undefined'){var ol_closefontclass="";}
if(typeof ol_padunit=='undefined'){var ol_padunit="px";}
if(typeof ol_heightunit=='undefined'){var ol_heightunit="px";}
if(typeof ol_widthunit=='undefined'){var ol_widthunit="px";}
if(typeof ol_textsizeunit=='undefined'){var ol_textsizeunit="px";}
if(typeof ol_textdecoration=='undefined'){var ol_textdecoration="none";}
if(typeof ol_textstyle=='undefined'){var ol_textstyle="normal";}
if(typeof ol_textweight=='undefined'){var ol_textweight="normal";}
if(typeof ol_captionsizeunit=='undefined'){var ol_captionsizeunit="px";}
if(typeof ol_captiondecoration=='undefined'){var ol_captiondecoration="none";}
if(typeof ol_captionstyle=='undefined'){var ol_captionstyle="normal";}
if(typeof ol_captionweight=='undefined'){var ol_captionweight="bold";}
if(typeof ol_closesizeunit=='undefined'){var ol_closesizeunit="px";}
if(typeof ol_closedecoration=='undefined'){var ol_closedecoration="none";}
if(typeof ol_closestyle=='undefined'){var ol_closestyle="normal";}
if(typeof ol_closeweight=='undefined'){var ol_closeweight="normal";}
if(typeof ol_texts=='undefined'){var ol_texts=new Array("Text 0", "Text 1");}
if(typeof ol_caps=='undefined'){var ol_caps=new Array("Caption 0", "Caption 1");}
var otext="";
var ocap="";
var osticky=0;
var obackground="";
var oclose="Chiudi";
var ohpos=8;
var ooffsetx=2;
var ooffsety=2;
var ofgcolor="";
var obgcolor="";
var otextcolor="";
var ocapcolor="";
var oclosecolor="";
var owidth=100;
var oborder=1;
var ostatus="";
var oautostatus=0;
var oheight=-1;
var osnapx=0;
var osnapy=0;
var ofixx=-1;
var ofixy=-1;
var ofgbackground="";
var obgbackground="";
var opadxl=0;
var opadxr=0;
var opadyt=0;
var opadyb=0;
var ofullhtml=0;
var ovpos=36;
var oaboveheight=0;
var ocapicon="";
var otextfont="Verdana,Arial,Helvetica";
var ocaptionfont="Verdana,Arial,Helvetica";
var oclosefont="Verdana,Arial,Helvetica";
var otextsize="1";
var ocaptionsize="1";
var oclosesize="1";
var oframe=self;
var otimeout=0;
var otimerid=0;
var oallowmove=0;
var ofunction=Function();
var odelay=0;
var odelayid=0;
var ohauto=0;
var ovauto=0;
var ocloseclick=0;
var ocss=51;
var ofgclass="";
var obgclass="";
var otextfontclass="";
var ocaptionfontclass="";
var oclosefontclass="";
var opadunit="px";
var oheightunit="px";
var owidthunit="px";
var otextsizeunit="px";
var otextdecoration="";
var otextstyle="";
var otextweight="";
var ocaptionsizeunit="px";
var ocaptiondecoration="";
var ocaptionstyle="";
var ocaptionweight="";
var oclosesizeunit="px";
var oclosedecoration="";
var oclosestyle="";
var ocloseweight="";
var ox=0;
var oy=0;
var oallow=0;
var oshowingsticky=0;
var oremovecounter=0;
var over=null;
var ns4=(document.layers)? true:false;
var ns6=(document.getElementById)? true:false;
var ie4=(document.all)? true:false;
var ie5=false;

if(ie4)
{
	if((navigator.userAgent.indexOf('MSIE 5')> 0)||(navigator.userAgent.indexOf('MSIE 6')> 0))
	{
		ie5=true;
	}
	if(ns6)
	{
		ns6=false;
	}
}
if((ns4)||(ie4)||(ns6))
{
//	document.onmousemove=mouseMove
	if(ns4)document.captureEvents(Event.MOUSEMOVE)
}
else
{
	overlib=no_overlib;
	nd=no_overlib;
	ver3fix=true;
}


function no_overlib()
{
	return ver3fix;
}


function overlib()
{
	otext=ol_text;
	ocap=ol_cap;
	osticky=ol_sticky;
	obackground=ol_background;
	oclose=ol_close;
	ohpos=ol_hpos;
	ooffsetx=ol_offsetx;
	ooffsety=ol_offsety;
	ofgcolor=ol_fgcolor;
	obgcolor=ol_bgcolor;
	otextcolor=ol_textcolor;
	ocapcolor=ol_capcolor;
	oclosecolor=ol_closecolor;
	owidth=ol_width;
	oborder=ol_border;
	ostatus=ol_status;
	oautostatus=ol_autostatus;
	oheight=ol_height;
	osnapx=ol_snapx;
	osnapy=ol_snapy;
	ofixx=ol_fixx;
	ofixy=ol_fixy;
	ofgbackground=ol_fgbackground;
	obgbackground=ol_bgbackground;
	opadxl=ol_padxl;
	opadxr=ol_padxr;
	opadyt=ol_padyt;
	opadyb=ol_padyb;
	ofullhtml=ol_fullhtml;
	ovpos=ol_vpos;
	oaboveheight=ol_aboveheight;
	ocapicon=ol_capicon;
	otextfont=ol_textfont;
	ocaptionfont=ol_captionfont;
	oclosefont=ol_closefont;
	otextsize=ol_textsize;
	ocaptionsize=ol_captionsize;
	oclosesize=ol_closesize;
	otimeout=ol_timeout;
	ofunction=ol_function;
	odelay=ol_delay;
	ohauto=ol_hauto;
	ovauto=ol_vauto;
	ocloseclick=ol_closeclick;
	ocss=ol_css;
	ofgclass=ol_fgclass;
	obgclass=ol_bgclass;
	otextfontclass=ol_textfontclass;
	ocaptionfontclass=ol_captionfontclass;
	oclosefontclass=ol_closefontclass;
	opadunit=ol_padunit;
	oheightunit=ol_heightunit;
	owidthunit=ol_widthunit;
	otextsizeunit=ol_textsizeunit;
	otextdecoration=ol_textdecoration;
	otextstyle=ol_textstyle;
	otextweight=ol_textweight;
	ocaptionsizeunit=ol_captionsizeunit;
	ocaptiondecoration=ol_captiondecoration;
	ocaptionstyle=ol_captionstyle;
	ocaptionweight=ol_captionweight;
	oclosesizeunit=ol_closesizeunit;
	oclosedecoration=ol_closedecoration;
	oclosestyle=ol_closestyle;
	ocloseweight=ol_closeweight;
	if((ns4)||(ie4)||(ns6))
	{
		oframe=ol_frame;
		if(ns4)over=oframe.document.overDiv
		if(ie4)over=oframe.overDiv.style
		if(ns6)over=oframe.document.getElementById("overDiv");
	}
	var c=-1;
	var ar=arguments;
	for(i=0;i < ar.length;i++)
	{
		if(c < 0)
		{
			if(ar[i]==1)
			{
				otext=ol_texts[ar[++i]];
			}
			else
			{
				otext=ar[i];
			}
			c=0;
		}
		else
		{
			if(ar[i]==1){otext=ol_texts[ar[++i]];continue;}
			if(ar[i]==2){ocap=ol_caps[ar[++i]];continue;}
			if(ar[i]==3){osticky=1;continue;}
			if(ar[i]==4){obackground=ar[++i];continue;}
			if(ar[i]==NOCLOSE){oclose="";continue;}
			if(ar[i]==6){ocap=ar[++i];continue;}
			if(ar[i]==9 || ar[i]==7 || ar[i]==8){ohpos=ar[i];continue;}
			if(ar[i]==10){ooffsetx=ar[++i];continue;}
			if(ar[i]==11){ooffsety=ar[++i];continue;}
			if(ar[i]==12){ofgcolor=ar[++i];continue;}
			if(ar[i]==13){obgcolor=ar[++i];continue;}
			if(ar[i]==14){otextcolor=ar[++i];continue;}
			if(ar[i]==15){ocapcolor=ar[++i];continue;}
			if(ar[i]==16){oclosecolor=ar[++i];continue;}
			if(ar[i]==17){owidth=ar[++i];continue;}
			if(ar[i]==18){oborder=ar[++i];continue;}
			if(ar[i]==19){ostatus=ar[++i];continue;}
			if(ar[i]==20){oautostatus=1;continue;}
			if(ar[i]==21){oautostatus=2;continue;}
			if(ar[i]==22){oheight=ar[++i];oaboveheight=ar[i];continue;}// Same param again.
			if(ar[i]==23){oclose=ar[++i];continue;}
			if(ar[i]==24){osnapx=ar[++i];continue;}
			if(ar[i]==25){osnapy=ar[++i];continue;}
			if(ar[i]==26){ofixx=ar[++i];continue;}
			if(ar[i]==27){ofixy=ar[++i];continue;}
			if(ar[i]==28){ofgbackground=ar[++i];continue;}
			if(ar[i]==29){obgbackground=ar[++i];continue;}
			if(ar[i]==30){opadxl=ar[++i];opadxr=ar[++i];continue;}
			if(ar[i]==31){opadyt=ar[++i];opadyb=ar[++i];continue;}
			if(ar[i]==34){ofullhtml=1;continue;}
			if(ar[i]==36 || ar[i]==35){ovpos=ar[i];continue;}
			if(ar[i]==37){ocapicon=ar[++i];continue;}
			if(ar[i]==38){otextfont=ar[++i];continue;}
			if(ar[i]==39){ocaptionfont=ar[++i];continue;}
			if(ar[i]==40){oclosefont=ar[++i];continue;}
			if(ar[i]==41){otextsize=ar[++i];continue;}
			if(ar[i]==42){ocaptionsize=ar[++i];continue;}
			if(ar[i]==43){oclosesize=ar[++i];continue;}
			if(ar[i]==44){opt_FRAME(ar[++i]);continue;}
			if(ar[i]==45){otimeout=ar[++i];continue;}
			if(ar[i]==46){opt_FUNCTION(ar[++i]);continue;}
			if(ar[i]==47){odelay=ar[++i];continue;}
			if(ar[i]==48){ohauto=(ohauto==0)? 1 : 0;continue;}
			if(ar[i]==49){ovauto=(ovauto==0)? 1 : 0;continue;}
			if(ar[i]==50){ocloseclick=(ocloseclick==0)? 1 : 0;continue;}
			if(ar[i]==51){ocss=ar[i];continue;}
			if(ar[i]==52){ocss=ar[i];continue;}
			if(ar[i]==53){ocss=ar[i];continue;}
			if(ar[i]==54){ofgclass=ar[++i];continue;}
			if(ar[i]==55){obgclass=ar[++i];continue;}
			if(ar[i]==56){otextfontclass=ar[++i];continue;}
			if(ar[i]==57){ocaptionfontclass=ar[++i];continue;}
			if(ar[i]==58){oclosefontclass=ar[++i];continue;}
			if(ar[i]==59){opadunit=ar[++i];continue;}
			if(ar[i]==60){oheightunit=ar[++i];continue;}
			if(ar[i]==61){owidthunit=ar[++i];continue;}
			if(ar[i]==62){otextsizeunit=ar[++i];continue;}
			if(ar[i]==63){otextdecoration=ar[++i];continue;}
			if(ar[i]==64){otextstyle=ar[++i];continue;}
			if(ar[i]==65){otextweight=ar[++i];continue;}
			if(ar[i]==66){ocaptionsizeunit=ar[++i];continue;}
			if(ar[i]==67){ocaptiondecoration=ar[++i];continue;}
			if(ar[i]==68){ocaptionstyle=ar[++i];continue;}
			if(ar[i]==69){ocaptionweight=ar[++i];continue;}
			if(ar[i]==70){oclosesizeunit=ar[++i];continue;}
			if(ar[i]==71){oclosedecoration=ar[++i];continue;}
			if(ar[i]==72){oclosestyle=ar[++i];continue;}
			if(ar[i]==73){ocloseweight=ar[++i];continue;}
		}
	}
	if(odelay==0)
	{
		return overlib350();
	}
	else
	{
		odelayid=setTimeout("overlib350()", odelay);
		if(osticky){
			return false;
		}
		else
		{
		return true;
		}
	}
}


function nd()
{
	if(oremovecounter >=1){oshowingsticky=0};
	if((ns4)||(ie4)||(ns6))
	{
		if(oshowingsticky==0)
		{
			oallowmove=0;
			if(over !=null)hideObject(over);
		}
		else
		{
			oremovecounter++;
		}
	}
	return true;
}


function overlib350()
{
	var layerhtml;
	if(obackground !="" || ofullhtml)
	{
		layerhtml=ol_content_background(otext, obackground, ofullhtml);
	}
	else
	{
		if(ofgbackground !="" && ocss==CSSOFF)
		{
			ofgbackground="BACKGROUND=\""+ofgbackground+"\"";
		}
		if(obgbackground !="" && ocss==CSSOFF)
		{
			obgbackground="BACKGROUND=\""+obgbackground+"\"";
		}
		if(ofgcolor !="" && ocss==CSSOFF)
		{
			ofgcolor="BGCOLOR=\""+ofgcolor+"\"";
		}
		if(obgcolor !="" && ocss==CSSOFF)
		{
			obgcolor="BGCOLOR=\""+obgcolor+"\"";
		}
		if(oheight > 0 && ocss==51)
		{
			oheight="HEIGHT=" + oheight;
		}
		else
		{
			oheight="";
		}
		if(ocap=="")
		{
			layerhtml=ol_content_simple(otext);
		}
		else
		{
			if(osticky)
			{
				layerhtml=ol_content_caption(otext, ocap, oclose);
			}
			else
			{
				layerhtml=ol_content_caption(otext, ocap, "");
			}
		}
	}
	if(osticky)
	{
		oshowingsticky=1;
		oremovecounter=0;
	}
	layerWrite(layerhtml);
	if(oautostatus > 0)
	{
		ostatus=otext;
		if(oautostatus > 1)
		{
			ostatus=ocap;
		}
	}
	oallowmove=0;
	if(otimeout > 0)
	{
		if(otimerid > 0)clearTimeout(otimerid);
		otimerid=setTimeout("cClick()", otimeout);
	}
	disp(ostatus);
	if(osticky)
	{
		oallowmove=0;
		return false;
	}
	else
	{
		return true;
	}
}


function ol_content_simple(text)
{
	if(ocss==CSSCLASS)txt="<TABLE style=\"width: "+owidth+";\" WIDTH="+owidth+" BORDER=0 CELLPADDING="+oborder+" CELLSPACING=0 class=\""+obgclass+"\"><TR><TD><TABLE class=\"overTable\" WIDTH="+owidth+" BORDER=0 CELLPADDING=2 CELLSPACING=0 class=\""+ofgclass+"\"><TR><TD VALIGN=TOP><FONT class=\""+otextfontclass+"\">"+text+"</FONT></TD></TR></TABLE></TD></TR></TABLE>";
	if(ocss==CSSSTYLE)txt="<TABLE style=\"width: "+owidth+";\" WIDTH="+owidth+" BORDER=0 CELLPADDING="+oborder+" CELLSPACING=0 style=\"background-color: "+obgcolor+";height: "+oheight+oheightunit+";\"><TR><TD><TABLE class=\"overTable\" WIDTH="+owidth+" BORDER=0 CELLPADDING=2 CELLSPACING=0 style=\"color: "+ofgcolor+";background-color: "+ofgcolor+";height: "+oheight+oheightunit+";\"><TR><TD VALIGN=TOP><FONT style=\"font-family: "+otextfont+";color: "+otextcolor+";font-size: "+otextsize+otextsizeunit+";text-decoration: "+otextdecoration+";font-weight: "+otextweight+";font-style:"+otextstyle+"\">"+text+"</FONT></TD></TR></TABLE></TD></TR></TABLE>";
	if(ocss==CSSOFF)txt="<TABLE style=\"width: "+owidth+";\" WIDTH="+owidth+" BORDER=0 CELLPADDING="+oborder+" CELLSPACING=0 "+obgcolor+" "+oheight+"><TR><TD><TABLE class=\"overTable\" WIDTH="+owidth+" BORDER=0 CELLPADDING=2 CELLSPACING=0 "+ofgcolor+" "+ofgbackground+" "+oheight+"><TR><TD VALIGN=TOP><FONT FACE=\""+otextfont+"\" COLOR=\""+otextcolor+"\" SIZE=\""+otextsize+"\">"+text+"</FONT></TD></TR></TABLE></TD></TR></TABLE>";
	set_background("");
	return txt;
}


function ol_content_caption(text, title, close)
{
	closing="";
	closeevent="onMouseOver";
	if(ocloseclick==1)closeevent="onClick";
	if(ocapicon !="")ocapicon="<IMG SRC=\""+ocapicon+"\"> ";
	if(close !="")
	{
		if(ocss==CSSCLASS)closing="<TD ALIGN=RIGHT><A HREF=\"/\" "+closeevent+"=\"return cClick();\" class=\""+oclosefontclass+"\">"+close+"</A></TD>";
		if(ocss==CSSSTYLE)closing="<TD ALIGN=RIGHT><A HREF=\"/\" "+closeevent+"=\"return cClick();\" style=\"color: "+oclosecolor+";font-family: "+oclosefont+";font-size: "+oclosesize+oclosesizeunit+";text-decoration: "+oclosedecoration+";font-weight: "+ocloseweight+";font-style:"+oclosestyle+";\">"+close+"</A></TD>";
		if(ocss==CSSOFF)closing="<TD ALIGN=RIGHT><A HREF=\"/\" "+closeevent+"=\"return cClick();\"><FONT COLOR=\""+oclosecolor+"\" FACE=\""+oclosefont+"\" SIZE=\""+oclosesize+"\">"+close+"</FONT></A></TD>";
	}
	if(ocss==CSSCLASS)txt="<TABLE style=\"width: "+owidth+";\" WIDTH="+owidth+" BORDER=0 CELLPADDING="+oborder+" CELLSPACING=0 class=\""+obgclass+"\"><TR><TD><TABLE class=\"overTable\" WIDTH="+owidth+" BORDER=0 CELLPADDING=0 CELLSPACING=0><TR><TD><FONT class=\""+ocaptionfontclass+"\">"+ocapicon+title+"</FONT></TD>"+closing+"</TR></TABLE><TABLE class=\"overTable\" WIDTH="+owidth+" BORDER=0 CELLPADDING=2 CELLSPACING=0 class=\""+ofgclass+"\"><TR><TD VALIGN=TOP><FONT class=\""+otextfontclass+"\">"+text+"</FONT></TD></TR></TABLE></TD></TR></TABLE>";
	if(ocss==CSSSTYLE)txt="	<iframe style='width:221px; height:200px; position:absolute; Z-INDEX: -1;' frameborder=0 scrolling=no marginwidth=0 src='' marginheight=0></iframe><TABLE style=\"width: "+owidth+";\" WIDTH="+owidth+" BORDER=0 CELLPADDING="+oborder+" CELLSPACING=0 style=\"height:100%; Z-INDEX: 2;background-color: "+obgcolor+";background-image: url("+obgbackground+");height: "+oheight+oheightunit+";\"><TR><TD><TABLE class=\"overTable\" WIDTH="+owidth+" BORDER=0 CELLPADDING=0 CELLSPACING=0><TR><TD><FONT style=\"font-family: "+ocaptionfont+";color: "+ocapcolor+";font-size: "+ocaptionsize+ocaptionsizeunit+";font-weight: "+ocaptionweight+";font-style: "+ocaptionstyle+";\">"+ocapicon+title+"</FONT></TD>"+closing+"</TR></TABLE><TABLE class=\"overTable\" height=\"184px;\"  WIDTH="+owidth+" BORDER=0 CELLPADDING=2 CELLSPACING=0 style=\"color: "+ofgcolor+";background-color: "+ofgcolor+";\"><TR><TD VALIGN=TOP><FONT style=\"font-family: "+otextfont+";color: "+otextcolor+";font-size: "+otextsize+otextsizeunit+";text-decoration: "+otextdecoration+";font-weight: "+otextweight+";font-style:"+otextstyle+"\">"+text+"</FONT></TD></TR></TABLE></TD></TR></TABLE>";
	if(ocss==CSSOFF)txt="<TABLE style=\"width: "+owidth+";\" WIDTH="+owidth+" BORDER=0 CELLPADDING="+oborder+" CELLSPACING=0 "+obgcolor+" "+obgbackground+" "+oheight+"><TR><TD><TABLE class=\"overTable\" WIDTH="+owidth+" BORDER=0 CELLPADDING=0 CELLSPACING=0><TR><TD><B><FONT COLOR=\""+ocapcolor+"\" FACE=\""+ocaptionfont+"\" SIZE=\""+ocaptionsize+"\">"+ocapicon+title+"</FONT></B></TD>"+closing+"</TR></TABLE><TABLE class=\"overTable\" WIDTH="+owidth+" BORDER=0 CELLPADDING=2 CELLSPACING=0 "+ofgcolor+" "+ofgbackground+" "+oheight+"><TR><TD VALIGN=TOP><FONT COLOR=\""+otextcolor+"\" FACE=\""+otextfont+"\" SIZE=\""+otextsize+"\">"+text+"</FONT></TD></TR></TABLE></TD></TR></TABLE>";
	set_background("");
	return txt;
}


function ol_content_background(text, picture, hasfullhtml)
{
	if(hasfullhtml)
	{
		txt=text;
	}
	else
	{
		if(ocss==CSSCLASS)txt="<TABLE style=\"width: "+owidth+";\" WIDTH="+owidth+owidthunit+" BORDER=0 CELLPADDING=0 CELLSPACING=0 HEIGHT="+oheight+oheightunit+"><TR><TD COLSPAN=3 HEIGHT="+opadyt+opadunit+"></TD></TR><TR><TD WIDTH="+opadxl+opadunit+"></TD><TD VALIGN=TOP WIDTH="+(owidth-opadxl-opadxr)+opadunit+"><FONT class=\""+otextfontclass+"\">"+text+"</FONT></TD><TD WIDTH="+opadxr+opadunit+"></TD></TR><TR><TD COLSPAN=3 HEIGHT="+opadyb+opadunit+"></TD></TR></TABLE>";
		if(ocss==CSSSTYLE)txt="<TABLE style=\"width: "+owidth+";\" IDTH="+owidth+owidthunit+" BORDER=0 CELLPADDING=0 CELLSPACING=0 HEIGHT="+oheight+oheightunit+"><TR><TD COLSPAN=3 HEIGHT="+opadyt+opadunit+"></TD></TR><TR><TD WIDTH="+opadxl+opadunit+"></TD><TD VALIGN=TOP WIDTH="+(owidth-opadxl-opadxr)+opadunit+"><FONT style=\"font-family: "+otextfont+";color: "+otextcolor+";font-size: "+otextsize+otextsizeunit+";\">"+text+"</FONT></TD><TD WIDTH="+opadxr+opadunit+"></TD></TR><TR><TD COLSPAN=3 HEIGHT="+opadyb+opadunit+"></TD></TR></TABLE>";
		if(ocss==CSSOFF)txt="<TABLE style=\"width: "+owidth+";\" WIDTH="+owidth+" BORDER=0 CELLPADDING=0 CELLSPACING=0 HEIGHT="+oheight+"><TR><TD COLSPAN=3 HEIGHT="+opadyt+"></TD></TR><TR><TD WIDTH="+opadxl+"></TD><TD VALIGN=TOP WIDTH="+(owidth-opadxl-opadxr)+"><FONT FACE=\""+otextfont+"\" COLOR=\""+otextcolor+"\" SIZE=\""+otextsize+"\">"+text+"</FONT></TD><TD WIDTH="+opadxr+"></TD></TR><TR><TD COLSPAN=3 HEIGHT="+opadyb+"></TD></TR></TABLE>";
	}
	set_background(picture);
	return txt;
}


function set_background(pic)
{
	if(pic=="")
	{
		if(ie4)over.backgroundImage="none";
		if(ns6)over.style.backgroundImage="none";
	}
	else
	{
		if(ns4)
		{
			over.background.src=pic;
		}
		else if(ie4)
		{
			over.backgroundImage="url("+pic+")";
		}
		else if(ns6)
		{
			over.style.backgroundImage="url("+pic+")";
		}
	}
}


function disp(statustext)
{
	if((ns4)||(ie4)||(ns6))
	{
		if(oallowmove==0)
		{
			placeLayer();
			showObject(over);
			oallowmove=1;
		}
	}
	if(statustext !="")
	{
		self.status=statustext;
	}
}


function placeLayer()
{
	var placeX, placeY;
	if(ofixx > -1)
	{
		placeX=ofixx;
	}
	else
	{
		winoffset=(ie4)? oframe.document.body.scrollLeft : oframe.pageXOffset;
		if(ie4)iwidth=oframe.document.body.clientWidth;
		if(ns4)iwidth=oframe.innerWidth;// was screwed in mozilla, fixed now?
		if(ns6)iwidth=oframe.outerWidth;
		if(ohauto==1)
		{
			if((ox - winoffset)>((eval(iwidth))/ 2)){
				ohpos=7;
			}
			else
			{
				ohpos=8;
			}
		}
		if(ohpos==9)
		{// Center
			placeX=ox+ooffsetx-(owidth/2);
		}
		if(ohpos==8)
		{// Right
			placeX=ox+ooffsetx;
			if((eval(placeX)+ eval(owidth))>(winoffset + iwidth))
			{
				placeX=iwidth + winoffset - owidth;
				if(placeX < 0)placeX=0;
			}
		}
		if(ohpos==7)
		{// Left
			placeX=ox-ooffsetx-owidth;
			if(placeX < winoffset)placeX=winoffset;
		}
		if(osnapx > 1)
		{
			var snapping=placeX % osnapx;
			if(ohpos==7)
			{
				placeX=placeX -(osnapx + snapping);
			}
			else
			{
				placeX=placeX +(osnapx - snapping);
			}
			if(placeX < winoffset)placeX=winoffset;
		}
	}
	if(ofixy > -1)
	{
		placeY=ofixy;
	}
	else
	{
		scrolloffset=(ie4)? oframe.document.body.scrollTop : oframe.pageYOffset;
		if(ovauto==1)
		{
			if(ie4)iheight=oframe.document.body.clientHeight;
			if(ns4)iheight=oframe.innerHeight;
			if(ns6)iheight=oframe.outerHeight;
			iheight=(eval(iheight))/ 2;
			if((oy - scrolloffset)> iheight)
			{
				ovpos=35;
			}
				else
			{
				ovpos=36;
			}
		}
		if(ovpos==35)
		{
			if(oaboveheight==0)
			{
//				var divref=(ie4)? oframe.document.all['overDiv'] : over;
				var divref=(ie4)? oframe.document.all.overDiv : over;
				oaboveheight=(ns4)? divref.clip.height : divref.offsetHeight;
			}
			placeY=oy -(oaboveheight + ooffsety);
			if(placeY < scrolloffset)placeY=scrolloffset;
		}
		else
		{
			placeY=oy + ooffsety;
		}
		if(osnapy > 1)
		{
			var snapping=placeY % osnapy;
			if(oaboveheight > 0 && ovpos==35)
			{
				placeY=placeY -(osnapy + snapping);
			}
			else
			{
				placeY=placeY +(osnapy - snapping);
			}
			if(placeY < scrolloffset)placeY=scrolloffset;
		}
	}
	repositionTo(over, placeX, placeY);
}


function mouseMove(e)
{
	if((ns4)||(ns6)){ox=e.pageX;oy=e.pageY;}
	if(ie4){ox=event.x;oy=event.y;}
	if(ie5){ox=event.x+oframe.document.body.scrollLeft;oy=event.y+oframe.document.body.scrollTop;}
	if(oallowmove==1)
	{
		placeLayer();
	}
}


function cClick()
{
	hideObject(over);
	oshowingsticky=0;
	return false;
}


function compatibleframe(frameid)
{
	if(ns4)
	{
		if(typeof frameid.document.overDiv=='undefined')return false;
	}
	else if(ie4)
	{
//		if(typeof frameid.document.all["overDiv"]=='undefined')return false;
		if(typeof frameid.document.all.overDiv=='undefined')return false;
	}
	else if(ns6)
	{
		if(frameid.document.getElementById('overDiv')==null)return false;
	}
	return true;
}


function layerWrite(txt)
{
	txt +="\n";
	if(ns4)
	{
		var lyr=oframe.document.overDiv.document
		lyr.write(txt)
		lyr.close()
	}
	else if(ie4)
	{
//		oframe.document.all["overDiv"].innerHTML=txt
		oframe.document.all.overDiv.innerHTML=txt
	}
	else if(ns6)
	{
		range=oframe.document.createRange();
		range.setStartBefore(over);
		domfrag=range.createContextualFragment(txt);
		while(over.hasChildNodes())
		{
			over.removeChild(over.lastChild);
		}
		over.appendChild(domfrag);
	}
}


/*
Rende visibile l'oggetto obj
*/
function showObject(obj)
{
	if(ns4)obj.visibility="show";
	else if(ie4)obj.visibility="visible";
	else if(ns6)obj.style.visibility="visible";
}


/*
Rende non visibile l'oggetto obj
*/
function hideObject(obj)
{
	if(ns4)obj.visibility="hide";
	else if(ie4)obj.visibility="hidden";
	else if(ns6)obj.style.visibility="hidden";
	if(otimerid > 0)clearTimeout(otimerid);
	if(odelayid > 0)clearTimeout(odelayid);
	otimerid=0;
	odelayid=0;
	self.status="";
}


/*
Riposiziona l'oggetto obj in base a xL e yL

xL è la coordinata X
yL è la coordinata Y

*/
function repositionTo(obj,xL,yL)
{
	if((ns4)||(ie4))
	{
		obj.left=xL;
		obj.top=yL;
	}
	else if(ns6)
	{
		obj.style.left=xL + "px";
		obj.style.top=yL+ "px";
	}
}


function opt_FRAME(frm)
{
	oframe=compatibleframe(frm)? frm : ol_frame;
	if((ns4)||(ie4 ||(ns6)))
	{
		if(ns4)over=oframe.document.overDiv;
		if(ie4)over=oframe.overDiv.style;
		if(ns6)over=oframe.document.getElementById("overDiv");
	}
	return 0;
}


function opt_FUNCTION(callme)
{
	otext=callme()
	return 0;
}


// ***********************************************************************************
//
// FUNZIONI PER LA GESTIONE DEI LINK EMBEDED
//
// Per ovviare al rischio dell'injecting, al posto dei link, cioè di invii con 
// metodo GET, il link viene trasformato in una chiamata POST
//
// ***********************************************************************************

//document.write('<div id="jollyForm" style="position:absolute; visibility:hidden; z-index:1000;"><form unload=false id="jolly" name="jolly" action="" method="POST" confirm=false ></form></div>');

/*
Esegue una chiamta Post passandogli una stringa con una chiamata GET
*/
function linkPost(strLink, strTarget)
{

  var fJolly = document.createElement('FORM');

  fJolly.setAttribute('method', 'POST');
  fJolly.setAttribute('id', 'jolly');
  fJolly.setAttribute('name', 'jolly');

  document.body.appendChild(fJolly);

  if (strLink != '')
  {
    var strAction = strLink.substr(0, strLink.indexOf('?'));
    if (strLink.indexOf('?') > 0)
    {
      var strFields = strLink.substr((strLink.indexOf('?')+1));
      var aFields = strFields.split('&');
      for (n=0; n<aFields.length; n++)
      {
      	var aField = aFields[n].split('=');
      	if (aField.length > 1)
      	{
          removeFieldJolly(aField[0]);
          addFieldJolly(aField[0], aField[1]);
      	}
      }
    }
    else
    {
      strAction = strLink
    }
    document.forms['jolly'].action = strAction;
    if (typeof strTarget == 'undefined')
	    document.forms['jolly'].target = '_self';
    else
	    document.forms['jolly'].target = strTarget;
    submitFlag = true;
    document.forms['jolly'].submit();
  }
}

/*
Aggiunge il campo INPUT HIDDEN alla form JOLLY
*/
function addFieldJolly(fieldName, fieldValue)
{
  addFieldCF(document.forms['jolly'], 'HIDDEN', fieldName, fieldValue);
}

/*
Rimuove il campo INPUT HIDDEN alla form JOLLY
*/
function removeFieldJolly(fieldName)
{
  removeFieldCF(document.forms['jolly'], fieldName);
}

/*
Aggiunge un campo INPUT ad una FORM
*/
function addFieldCF(form, fieldType, fieldName, fieldValue)
{
  if (typeof eval('document.forms[\''+form.name+'\'].'+fieldName) == 'undefined')
  {
    var input = document.createElement('INPUT');
    if (document.all)
    {
      input.type = fieldType;
      input.id = fieldName;
      input.name = fieldName;
      input.value = fieldValue;
    }
    else if (document.getElementById)
    {
      input.setAttribute('type', fieldType);
      input.setAttribute('id', fieldName);
      input.setAttribute('name', fieldName);
      input.setAttribute('value', fieldValue);
    }
    form.appendChild(input);
  }
}

/*
Restituisce un campo INPUT di una FORM
*/
function getFieldCF(form, fieldName)
{
  if (!document.all)
    return form[fieldName];
  else
    for (var e = 0; e < form.elements.length; e++)
      if (form.elements[e].name == fieldName)
        return form.elements[e];
  return null;
}        

/*
Rimuove un campo INPUT di una FORM
*/
function removeFieldCF(form, fieldName) {
  var field = getFieldCF(form, fieldName);
  if (field && !field.length)
    field.parentNode.removeChild(field);
}

/*
Cerca un campo INPUT di una FORM: Se c'è lo toglie, se non c'è lo crea
*/
function toggleFieldCF(form, fieldName, value) {
  var field = getFieldCF(form, fieldName);
  if (field)
    removeFieldCF(form, fieldName);
  else
    addFieldCF(form, 'hidden', fieldName, value);
}


// ***********************************************************************************
//
// DA QUI INIZIANO LE FUNZIONI DI UTILITA'
//
// Per ovviare ad eventuali casi di omonimia è stato inserito il suffisso CF (CheckForm)
//
// ***********************************************************************************

/*
Sostituisce uno o più caratteri con uno o più altri caratteri in una stringa
*/
function replaceChrCF(stringa, carattereDaTrovare, carattereDaSostituire)
{
  var i = 0;
  var singoloChar = "";
  var nuovaStringa = "";

  while ( i < stringa.length )
  {
    singoloChar = stringa.charAt(i);

    if ( singoloChar == carattereDaTrovare )
    {
      nuovaStringa += carattereDaSostituire;
    }
    else
    {
      nuovaStringa += singoloChar;
    }
  i++;
  }

  return nuovaStringa;
}

/*
Restituisce una stringa contenente un carattere ripetuto n volte
*/
function replicateChrCF(carattere, lunghezza)
{
  var nuovaStringa = "";

  while (nuovaStringa.length < lunghezza)
  {
    nuovaStringa += carattere;
  }

  return nuovaStringa;
}

/*
Elimina tutti i blank all'inizio e alla fine della stringa
*/
function trimCF( stringa ) {

	re = /\s+$|^\s+/g;

	return stringa.replace(re, "");
}

/*
Rende visibile l'oggetto obj
*/
function showCF(obj)
{
	obj.style.visibility="visible";
}

/*
Rende non visibile l'oggetto obj
*/
function hideCF(obj)
{
	obj.style.visibility="hidden";
}

/*
Rende visibile l'oggetto obj, espandendo l'area visualizzata
*/
function expandCF(obj)
{
	obj.style.display="inline";
}

/*
Rende non visibile l'oggetto obj, collassando l'area visualizzata
*/
function collapseCF(obj)
{
	obj.style.display="none";
}


/*
Riposiziona l'oggetto obj in base a xL e yL

xL è la coordinata X
yL è la coordinata Y

*/
function moveCF(obj,xL,yL)
{
	obj.style.left=xL + "px";
	obj.style.top=yL+ "px";
}


/*
Converte il formato una data

Parametri obbligatori:
	valore		-> String	Data nel formato indicato dentro formatoDa

Parametri opzionali:
	separatore	-> String	il tipo di separatore, default '/'
	formatoA	-> String	Il formato in cui si vuole convertire, default 'GGsMMsAAAA'
	formatoDa	-> String	Il formato di origine della data da convertire, default 'GGMMAAAA'

*/
function dataConverterCF(valore, separatore, formatoDa, formatoA)
{
	var ritorna = '';

	if ((valore != null) && (trimCF(valore) != ''))
	{
		if (separatore == null) separatore = "/";
		if (formatoA == null) formatoA = "GGsMMsAAAA";
		if (formatoDa == null) formatoDa = "GGMMAAAA";
		if (valore.length == 3)
			valore = '0' + valore.substr(0,1) + '0' + valore.substr(1,1) + '200' + valore.substr(2,1);
		if (valore.length == 4)
			valore = valore + '2000';
		if (valore.length == 5)
			valore = valore.substr(0,4) + '200' + valore.substr(4,1);
		if (valore.length == 6)
			valore = valore.substr(0,4) + '20' + valore.substr(4,2);
		if (valore.length == 7)
			if (valore.substr(4,1) == '0')
				valore = valore.substr(0,4) + '2' + valore.substr(4,3)
			else
				valore = valore.substr(0,4) + '1' + valore.substr(4,3)

		dataDaConvertire = new Date();
		dataDaConvertire.setDataFormattata(valore, formatoDa);

		ritorna = dataDaConvertire.getDataFormattata(formatoA, separatore);
	}

	return ritorna;
}


/*
Converte il formato un'ora

Parametri obbligatori:
	valore		-> String	Ora nel formato indicato dentro formatoDa

Parametri opzionali:
	separatore	-> String	il tipo di separatore, default ':'
	formatoA	-> String	Il formato in cui si vuole convertire, default 'OOsMMsSS'
	formatoDa	-> String	Il formato di origine della data da convertire, default 'OOMMSS'

*/
function oraConverterCF(valore, separatore, formatoDa, formatoA)
{
	var ritorna = '';

	if ((valore != null) && (trimCF(valore) != ''))
	{
		if (separatore == null) separatore = ":";
		if (formatoA == null) formatoA = "OOsMMsSS";
		if (formatoDa == null) formatoDa = "OOMMSS";

		if (valore.length == 3)
			valore = '0' + valore.substr(0,1) + '0' + valore.substr(1,1) + '0' + valore.substr(2,1);
		if (valore.length == 4)
			valore = valore + '00';
		if (valore.length == 5)
			valore = valore.substr(0,4) + '0' + valore.substr(4,1);

		oraDaConvertire = new Date();
		oraDaConvertire.setOraFormattata(valore, formatoDa);

		ritorna = oraDaConvertire.getOraFormattata(formatoA, separatore);
	}

	return ritorna;
}


/*
Calcola l'età attuariale
*/
function calcolaEtaAttuarialeCF(strNascita, strDecorrenza) 
{
	dataNascita = new Date();
	dataNascita.setDataformattata(strNascita, 'GGsMMsAAAA');

	return dataNascita.calcolaEtaAttuariale(strDecorrenza, 'A', 'GGsMMsAAAA');
}



/*
Elimina una voce da un campo combobox (o lista)

thisField è il campo combobox

strBy può contenere:
	INDEX	vuol dire che si vuole rimuovere in base alla posizione della voce
	VALUE	vuol dire che si vuole rimuovere in base al valore della voce
	TEXT	vuol dire che si vuole rimuovere in base al testo della voce

valore o è un intero x INDEX oppure una stringa x VALUE e TEXT

Ritorna TRUE se va tutto bene
	FALSE se non trova la voce da eliminare o x errore

NB Cancella tutte le voci in caso di righe con valori identici, nel caso di VALUE o TEXT

*/
function removeOptionCF( thisField, strBy, valore ) {

	if (typeof thisField == 'undefined')
	{
		alert('IL CAMPO NON ESISTE - function addOptionCF(thisField, valore, descrizione) ');
		return false;
	}
		
	if ((thisField.type.toUpperCase() != 'SELECT-ONE') && (thisField.type.toUpperCase() != 'SELECT-MULTIPLE'))
	{
		alert('Il campo ' + thisField.name.toUpperCase() + ' non è di tipo combobox (o lista)');
		return false;
	}

	switch (strBy.toUpperCase())
	{
		case 'INDEX' :
			if ((valore >= 0) && (valore <= thisField.options.length))
			{
				thisField.options[valore] = null;
			}
			else
			{
				return false;
			}
			break;
		case 'VALUE' :
			for (var i=0; i < thisField.options.length; i++)
			{
				if (thisField.options[i].value == valore)
				{
					thisField.options[i--] = null;
				}
			}
			break;
		case 'TEXT' :
			for (var i=0; i < thisField.options.length; i++)
			{
				if (thisField.options[i].text == valore)
				{
					thisField.options[i--] = null;
				}
			}
			break;
	}

	return true;
}


/*
Aggiunge una voce ad un campo combobox (o lista)

thisField è il campo combobox
valore è una stringa
descrizione è una stringa

Ritorna TRUE se va tutto bene
	FALSE se non trova la voce da eliminare o x errore

NB Vedere removeOptionCF

*/
function addOptionCF(thisField, valore, descrizione) {

	if (typeof thisField == 'undefined')
	{
		alert('IL CAMPO NON ESISTE - function addOptionCF(thisField, valore, descrizione) ');
		return false;
	}
		
	if ((thisField.type.toUpperCase() != 'SELECT-ONE') && (thisField.type.toUpperCase() != 'SELECT-MULTIPLE'))
	{
		alert('Il campo ' + thisField.name.toUpperCase() + ' non è di tipo combobox (o lista)');
		return false;
	}

	thisField.options[thisField.options.length] = new Option(descrizione, valore);
	return true;

}

/*
Disabilita una voce da un campo combobox (o lista)

thisField è il campo combobox

strBy può contenere:
	INDEX	vuol dire che si vuole disabilitare in base alla posizione della voce
	VALUE	vuol dire che si vuole disabilitare in base al valore della voce
	TEXT	vuol dire che si vuole disabilitare in base al testo della voce

valore o è un intero x INDEX oppure una stringa x VALUE e TEXT

Ritorna TRUE se va tutto bene
	FALSE se non trova la voce da eliminare o x errore

NB Vedere enableOptionCF

*/
function disableOptionCF( thisField, strBy, valore ) {

	if (typeof thisField == 'undefined')
	{
		alert('IL CAMPO NON ESISTE - function addOptionCF(thisField, valore, descrizione) ');
		return false;
	}
		
	if ((thisField.type.toUpperCase() != 'SELECT-ONE') && (thisField.type.toUpperCase() != 'SELECT-MULTIPLE'))
	{
		alert('Il campo ' + thisField.name.toUpperCase() + ' non è di tipo combobox (o lista)');
		return false;
	}

	var posizione = (thisField.disabledOptions.length>=0?thisField.disabledOptions.length:0);
	switch (strBy.toUpperCase())
	{
		case 'INDEX' :
			if ((valore >= 0) && (valore <= thisField.options.length))
			{
				thisField.disabledOptions.length = posizione + 1;
				thisField.disabledOptions[posizione] = new Array(thisField.options[valore].text, thisField.options[valore].value, valore);
				thisField.options[valore] = null;
			}
			else
			{
				return false;
			}
			break;
		case 'VALUE' :
			for (var i=0; i < thisField.options.length; i++)
			{
				if (thisField.options[i].value == valore)
				{
					thisField.disabledOptions.length = posizione + 1;
					thisField.disabledOptions[posizione] = new Array(thisField.options[i].text, thisField.options[i].value, i);
					thisField.options[i--] = null;
				}
			}
			break;
		case 'TEXT' :
			for (var i=0; i < thisField.options.length; i++)
			{
				if (thisField.options[i].text == valore)
				{
					thisField.disabledOptions.length = posizione + 1;
					thisField.disabledOptions[posizione] = new Array(thisField.options[i].text, thisField.options[i].value, i);
					thisField.options[i--] = null;
				}
			}
			break;
	}
	
	return true;
}


/*
Riabilita una voce da un campo combobox (o lista)

thisField è il campo combobox

strBy può contenere:
	INDEX	vuol dire che si vuole riabilitare in base alla posizione della voce
	VALUE	vuol dire che si vuole riabilitare in base al valore della voce
	TEXT	vuol dire che si vuole riabilitare in base al testo della voce

valore o è un intero x INDEX oppure una stringa x VALUE e TEXT

Ritorna TRUE se va tutto bene
	FALSE se non trova la voce da eliminare o x errore

NB Vedere disableOptionCF

*/
function enableOptionCF( thisField, strBy, valore ) {

	if (typeof thisField == 'undefined')
	{
		alert('IL CAMPO NON ESISTE - function addOptionCF(thisField, valore, descrizione) ');
		return false;
	}
		
	if ((thisField.type.toUpperCase() != 'SELECT-ONE') && (thisField.type.toUpperCase() != 'SELECT-MULTIPLE'))
	{
		alert('Il campo ' + thisField.name.toUpperCase() + ' non è di tipo combobox (o lista)');
		return false;
	}

	switch (strBy.toUpperCase())
	{
		case 'INDEX' :
			if ((valore >= 0) && (valore <= thisField.disabledOptions.length))
			{
				for (var j=(thisField.options.length-1); j >= thisField.disabledOptions[valore][2] ; j--)
				{
					thisField.options[j+1] = new Option(thisField.options[j].text, thisField.options[j].value);
				}
				thisField.options[thisField.disabledOptions[valore][2]] = new Option(thisField.disabledOptions[valore][0], thisField.disabledOptions[valore][1]);
				for (var j=valore; j < thisField.disabledOptions.length; j++)
				{
					thisField.disabledOptions[j] = new Array(thisField.disabledOptions[j+1][0], thisField.disabledOptions[j+1][1], thisField.disabledOptions[j+1][2]);
				}
				thisField.disabledOptions.length = thisField.disabledOptions.length - 1;
			}
			else
			{
				return false;
			}
			break;
		case 'VALUE' :
			for (var i=0; i < thisField.disabledOptions.length; i++)
			{
				if (thisField.disabledOptions[i][1] == valore)
				{
					for (var j=(thisField.options.length-1); j >= thisField.disabledOptions[i][2] ; j--)
					{
						thisField.options[j+1] = new Option(thisField.options[j].text, thisField.options[j].value);
					}
					thisField.options[thisField.disabledOptions[i][2]] = new Option(thisField.disabledOptions[i][0], thisField.disabledOptions[i][1]);
					for (var j=i; j < thisField.disabledOptions.length; j++)
					{
						thisField.disabledOptions[j] = new Array(thisField.disabledOptions[j+1][0], thisField.disabledOptions[j+1][1], thisField.disabledOptions[j+1][2]);
					}
					thisField.disabledOptions.length = thisField.disabledOptions.length - 1;
					i = i - 1;
				}
			}
			break;
		case 'TEXT' :
			for (var i=0; i < thisField.disabledOptions.length; i++)
			{
				if (thisField.disabledOptions[i][0] == valore)
				{
					for (var j=(thisField.options.length-1); j >= thisField.disabledOptions[i][2] ; j--)
					{
						thisField.options[j+1] = new Option(thisField.options[j].text, thisField.options[j].value);
					}
					thisField.options[thisField.disabledOptions[i][2]] = new Option(thisField.disabledOptions[i][0], thisField.disabledOptions[i][1]);
					for (var j=i; j < thisField.disabledOptions.length; j++)
					{
						thisField.disabledOptions[j] = new Array(thisField.disabledOptions[j+1][0], thisField.disabledOptions[j+1][1], thisField.disabledOptions[j+1][2]);
					}
					thisField.disabledOptions.length = thisField.disabledOptions.length - 1;
					i = i - 1;
				}
			}
			break;
	}

	return true;

}


