/*
   CONVALIDA FORM

   v.1.8 - 25/05/2004 max
     Modificata funzione previewImage()
   v.1.7 - 01/04/2004 max
     Aggiunta gestione OKIF per 'checkbox' e 'radio'
   v.1.6 - ??/??/2003 max: isDate
     Aggiunta funzione per verifica sintattica e semantica di data e orario
   v.1.5 - 03/12/2003 max
     Gestito focus se oggetto disabilitato
   v.1.4

   Funzione generica per la convalida di FORM:
   è richiesto che ogni campo che deve essere conforme ad uno specifico
   formato venga descritto da un'apposita rex nell'attributo REX dell'oggetto
   HTML stesso. 
   La FORM deve definire l'handler onSubmit per invocare la funzione convalida.
   
   Sintassi:
   <FORM ... onsubmit="return convalida(this)">
   
   <INPUT ... REX=".+">
   <INPUT ... REX="^\\w+\$" ALERT="Nome utente non valido">
   <INPUT ... REX="^\\S+\$" ALERT="Password non valida">
   <INPUT ... REX="^\\d+\$" ALERT="Numero non valido">
   <INPUT ... REX="^/?(\\w+/)*\\w*\$" ALERT="Percorso non valido">
   <INPUT ... REX="^[\\w\\.]+@(\\w+\\.)+\\w+\$" ALERT="Email non valida">
   <INPUT ... OKIF="wc(this.value)<26" ALERT="...">
   <INPUT ... OKIF="this.value.lenght<101" ALERT="...">
   <INPUT ... REX=".+" OKIF="wc(this.value)<5" ALERT="almeno una parola, al più 4 parole">
   DATA OBBLIGATORIA (ORE:MIN:SEC OPZIONALI):
   <INPUT ... REX="^\d{1,2}-\d{1,2}-\d{4}( \d{1,2}(:\d{1,2}(:\d{1,2})?)?)?$" OKIF="isDate(this.value)" ALERT="Data non valida">
   DATA O NULLA:
   <INPUT ... REX="(^\d{1,2}-\d{1,2}-\d{4}( \d{1,2}(:\d{1,2}(:\d{1,2})?)?)?)?$" OKIF="this.value.length==0||isDate(this.value)" ALERT="Data non valida">

   <SELECT ... OKIF="this.selectedIndex>0" ALERT="Selezionare un valore">
    <OPTION> < Seleziona > </OPTION>
    <OPTION value="...">...</OPTION>
    ...
   </SELECT>

   L'attributo OKIF (che viene tentato dopo la REX) puo' contenere una espressione 
   javascript che viene valutata con eval. Il riferimento a this, ovviamente non è
   corretto (in quanto la sede di esecuzione della convalida è il form e non i suoi
   componenti) e viene sostituito con il riferimento all'input appropriato.
   Il messaggio evidenziato nella alert può essere indicato con l'attributo ALERT.
   
   Funziona su input          type
   -------------------------- ----------------
   [X] INPUT TYPE="password"  "password" 
   [X] INPUT TYPE="text"      "text" 
   [*] INPUT TYPE="radio"     "radio" 
   [*] INPUT TYPE="checkbox"  "checkbox" 
   [X] INPUT TYPE="file"      "file" 
   [X] TEXTAREA               "textarea" 
   [X] SELECT                 "select-one" 
   [ ] SELECT MULTIPLE        "select-multiple" 
   [X] INPUT TYPE="hidden"    "hidden" 
   [-] INPUT TYPE="button"    "button" 
   [-] INPUT TYPE="reset"     "reset" 
   [-] INPUT TYPE="submit"    "submit"

   dove:
   [ ] non implementato
   [X] implementato REX, OKIF (e ALERT)
   [*] implementato solo OKIF (e ALERT)
   [-] non prevista

   To do:
     [ ] Verifica e gestione inclusione multipla di questo documento
     [ ] Verifica su SELECT
     [ ] Verifica checking di almeno uno su un gruppo per radio
         --> ad esempio inserendo il campo ONEOFTHESE="1" dove il numero indica la famiglia
     [ ] Verifica checking di almeno uno su un gruppo di checkox
     [X] Verifica numero massimo di parole in textarea
     [ ] Aggiungere la chiamata a convalida a tutti i form nella pagina
     [ ] Verifica formato numerico e conversione per invio

   NOTA x NETSCAPE (4.77 e precendenti) (4.79 ?)
   Non funziona a meno di aggiungere a mano i parametri nel modo seguente:

      document.forms.formname.elementname.REX = ".+"
      document.forms.formname.elementname.OKIF = "this.value.lenght<101"
      document.forms.formname.elementname.ALERT = "Non conforme"

   dove formname e elementname vanno sostituiti con i nomi rispettivi.
*/

/* CONVALIDA */
/* funziona per IE(Win6.0.28,MacOSX5.1.4): v.1.1 01/10/2001 */
/* funziona per NN6(Win): v.1.2 28/10/2002 */
/* funziona per Moz5[Mozilla5,Konqueror,Galeon]: v.1.3 28/10/2002 */
/* funziona per Op6: v.1.3 28/10/2002 */

function convalida ( frm ) {
  if( Moz4 ) {
    alert("Uscita forzata.")  // DEBUG
    return true;
  }
  if ( frm.nodeName != 'FORM' ) {
    alert( "ERROR: convalida form:\nl'oggetto passato onsubmit non e' una FORM!" )
    if(frm.nodeName) alert('frm.nodeName: ' + frm.nodeName )
    else alert('frm.nodeName not defined (?)')
    return false
  }
  for (i=0; i<frm.length; i++) {
    ele = frm.elements[ i ];
    switch ( ele.type ){
      case "select-one" :
        if ( NN6 || Moz5 ) {
          if ( ele.hasAttribute("OKIF") && !eval(ele.getAttribute("OKIF").replace(/this/ig, "ele")) ) {
            if ( ele.hasAttribute("ALERT") ) {
              alert (ele.getAttribute("ALERT") );
            } else {
              alert ("Campo non conforme");
            }
            setFocus(ele)
            //ele.focus();
            //if (Moz5) setTimeout(refocus,500,ele);
            return false;
          }
        } else {
          if ( ele["OKIF"] && !eval(ele["OKIF"].replace(/this/ig, "ele")) ) {
            if ( ele["ALERT"] ) {
              alert (ele["ALERT"]);
            } else {
              alert ("Campo non conforme");
            }
            setFocus(ele)
            //ele.focus();
            return false;
          }
        }
        break; // end case: select-one
      case "text" :
      case "hidden" :
      case "password" :
      case "textarea" :
        if ( NN6 || Moz5 ) {
          if ( (ele.hasAttribute("REX") && !ele.value.match(new RegExp(ele.getAttribute("REX") ))) || 
               (ele.hasAttribute("OKIF") && !eval(ele.getAttribute("OKIF").replace(/this/ig, "ele")))
             )
          {
            if ( ele.hasAttribute("ALERT") ) {
              alert (ele.getAttribute("ALERT") );
            } else {
              alert ("Campo non conforme");
            }
            setFocus(ele)
            //ele.focus();
            //if (Moz5) setTimeout(refocus,500,ele);
            return false;
          }
        } else {
          if ( (ele["REX"] && !ele.value.match(new RegExp(ele["REX"]))) || 
               (ele["OKIF"] && !eval(ele["OKIF"].replace(/this/ig, "ele")))
             )
          {
            if ( ele["ALERT"] ) {
              alert (ele["ALERT"]);
            } else {
              alert ("Campo non conforme");
            }
            setFocus(ele)
            //ele.focus();
            return false;
          }
        }
        break; // end case: text, password, textarea
      case "checkbox" :
      case "radio" :
        if ( NN6 || Moz5 ) {
          if ( (ele.hasAttribute("OKIF") && !eval(ele.getAttribute("OKIF").replace(/this/ig, "ele"))) )
          {
            if ( ele.hasAttribute("ALERT") ) {
              alert (ele.getAttribute("ALERT") );
            } else {
              alert ("Campo non conforme");
            }
            setFocus(ele)
            return false;
          }
        } else {
          if ( (ele["OKIF"] && !eval(ele["OKIF"].replace(/this/ig, "ele"))) )
          {
            if ( ele["ALERT"] ) {
              alert (ele["ALERT"]);
            } else {
              alert ("Campo non conforme");
            }
            setFocus(ele)
            return false;
          }
        }
        break; // end case: checkbox
      default : 
        ;  // do nothing by default
    }  // end switch
  }  // end for

  return true

}  // end convalida


/* SETFOCUS */
function setFocus(ele) {
  if ( ele.disabled ) {
    alert( 'Il campo è disabilitato: '+ ele.name )
    return
  }
  ele.focus();
  if (Moz5) setTimeout(refocus,500,ele);
}

/* REFOCUS */
function refocus(elm) {
  elm.focus()
}

/* VERIFICA SE IL TESTO PASSATO E' UNA DATA VALIDA DEL TIPO GG MM AAAA hh mm ss */
/* NOTA: QUALSIASI SEPARATORE E' AMMESSO */
function isDate( sd ) {
  //sd = '1-12-2003 18:45:24'
  var i=0;

  // array string date
  var asd = sd.split(/\D/)
  if( asd.length < 3 || asd.length > 6 ) return false

  // array numeric date
  var and = new Array()
  for(i=0; i<asd.length; i++) and[ i ] = parseInt(asd[ i ],10)

  // add zeroes up to 6
  for(i=and.length; i<6; i++) and[ i ] = 0

  // create the Date
  var d = new Date(and[2], and[1]-1, and[0], and[3], and[4], and[5])

  // array date
  var ad = new Array()  
  ad[0] = d.getDate()
  ad[1] = d.getMonth()+1
  ad[2] = d.getFullYear()
  ad[3] = d.getHours()
  ad[4] = d.getMinutes()
  ad[5] = d.getSeconds() 
 
  // begin the verify
  var ok = true
  for(i=0; i<6; i++) {
    if(ad[ i ]!=and[ i ]) {
      ok = false
      break
    }
  }

  //alert( d.toString() + " / " + ad.join('#') + " / " + and.join('#') + " / " + ok )
  return ok
}

/* CONTEGGIO CARATTERI */
function contacar(testo, max, msg) {
  if (testo.value.length > max) {
    if (msg) alert(msg);
    return false;
  } else {
    return true;
  }
}

/* CONTEGGIO PAROLE */
function contaparole(testo,max,msg) {
  if (wc(testo.value) > max) {
    if (msg) alert(msg);
    return false;
  } else {
    return true;
  }
}

/* CONTA LE PAROLE IN UN TESTO */
function wc(str) {
  //re = /\w+/;           // SOLO PAROLE
  re = /([^\s]+)/;        // PAROLE E NUMERI PUNTATI: ok NN 4.77
  RegExp.multiline = true;
  nw = 0;
  found = re.exec(str);
  while (found) {
    nw++;
    str = found.input.substring(found.index + found[ 0 ].length);
    found = re.exec(str);
  }
  return nw;
}



function previewImage( oid, value, box ) {

  var hide = false
  var ext = /\.(gif|jpeg|jpg|jpe|png)$/i  // ESTENSIONI VALIDE PER IL PREVIEW
  var nw = 0
  var nh = 0

  var img  = document.getElementById("img_" + oid)  // IMG PER IL PREVIEW
  var himg = document.getElementById("himg_" + oid) // IMG NASCOSTO PER IL PRECARICAMENTO
  var dim  = document.getElementById("dim_" + oid)  // TAG PER LA VISUALIZZAZIONE DELLE DIMENSIONI
  var dimg = document.getElementById("dimg_" + oid) // DIV PER NASCODERE IL PREVIEW

  //alert( value )
  if ( value != '' ) {

    // NOME IMMAGINE
    if ( value.indexOf('\\') >= 0 ) {
      sep = '\\'
    } else {
      sep = '/'
    }
    sval = value.split( sep )
    imageuploadname = sval[sval.length - 1]
    if ( imageuploadname.match(ext) ) {
      hide = false
      himg.src = 'file:///' + value;
      img.src = 'file:///' + value;
      dimg.style.display = '';
    } else {
      hide = true
      img.src = 'http://10.0.1.200/or/ESY/esy/imgs/image.gif';
      dim.innerHTML = '&nbsp;';
      dimg.style.display = "none";
    }
    //document.getElementById('ifn').value = imageuploadname;  // DEBUG
  }

  if ( box < 8 ) box = 8

  img.style.display = "none";
  if ( hide ) {
    dim.innerHTML = '&nbsp;';
  } else {
    dim.innerHTML = himg.width + 'x' + himg.height;
  }

  if ( himg.width > box || himg.height > box ){
    if ( himg.width > himg.height ) {
      nw = box
      nh = Math.round( himg.height * box / himg.width )
    } else {
      nw = Math.round( himg.width * box / himg.height )
      nh = box
    }
    img.width = nw;
    img.height = nh;
  } else {
    img.width  = himg.width;
    img.height  = himg.height;
  }

  img.style.display = "";

}

/* ----------------------------------------------------------------------- */
/* APRE UNA FINESTRA E VISUALIZZA TUTTE LE PROPRIETA' DELL'OGGETTO PASSATO */

function displayObject(ob) {
  w = open()
  w.document.writeln("<pre>")
  for (i in ob)
      w.document.writeln(i + " = `" + ob[ i ] + "`")
  w.document.writeln("------------------------------")
  w.document.writeln("fine.")
  w.document.close()
}


/* ----------------------------------------------------------------------- */
/* IDENTIFICAZIONE DEL TIPO DI CLIENT                                      */

nav = navigator.userAgent;

IE = NN = NN6 = Moz5 = Moz4 = Op6 = false
if (nav.search("Linux") != -1 && nav.search("Opera/6") != -1) {
  Op6 = true;
}
if ((nav.search("Linux") != -1 || nav.search("Macintosh") != -1) && nav.search("Mozilla/5") != -1) {
  Moz5 = true;
}
if (nav.search("Linux") != -1 && nav.search("Mozilla/4") != -1) {
  Moz4 = true;
}
if (nav.search("Windows") != -1 && nav.search("Mozilla/5") != -1) {
  NN6 = true;
}
if (nav.search("Windows") != -1 && nav.search("Mozilla/4") != -1 && nav.search("MSIE") == -1) {
  NN = true;
}
if (nav.search("MSIE") != -1) {
  IE = true;
}

