/*
0. trim(stringa): elimina gli spazi al'inizio e alla fine della stringa
1. check_date(field): Validazione date
2. numeralsOnly(evt): Controllo campo numerico
3. Field_Validator(label): Validazione label
4. Select_Validator(label): Validazione select
5. Email_Validator(email): Validazione email 
6. MinLenght_Validator(label, minLenght, name): Check min lunghezza field
7. MaxLenght_Validator(label, maxLenght, name): Check max lunghezza field
8. Password_Validator(label, label2): Check controllo password
9. RegExp_Validator(label, type, name): Regular expression caratteri
    1. Lettere, spazi ed il carattere [']
    2. Lettere, numeri ed i caratteri [_-]
    3. Solo numeri
10. Select_EnableField(fieldMaster, fieldSlave, selectedId): Abilitazione di un campo al change di una select
11. Select_Validator2level(fieldMaster, fieldSlave, selectedId): validazione obbligatorietà di secondo livello: select  
12. Check_Validator(label1, label2): validazione check inserimento scelta tipo utente
13. Check_GenericValidator(label1, field): validazione check generico
14. Check_GenericPanel(label, panel);  gestione pannello via checkbox
*/


//00. get alert lingue
function GetText(lang, textITA, textENG, textESP, textCAT)
{
    switch (lang) {
        case "ITA":
            alert(textITA);
            break;

      case "ENG":
        alert(textENG);
      break;

      case "ESP":
        alert(textESP);
      break;
      
      case "CAT":
        alert(textCAT);
      break;

      default:
       alert(textENG);
            } 
            
}


//0. trim string

function trim(stringa)
{    
    while (stringa.substring(0,1) == ' ')
    {        
        stringa = stringa.substring(1, stringa.length);    
    }    
    while (stringa.substring(stringa.length-1, stringa.length) == ' ')
    {
            stringa = stringa.substring(0,stringa.length-1);    
            }    
    return stringa;
}

    
//1. validazione data  
function check_date(field){
var checkstr = "0123456789";
var DateField = field;
var Datevalue = "";
var DateTemp = "";
var seperator = "-";
var day;
var month;
var year;
var leap = 0;
var err = 0;
var i;
   err = 0;
   DateValue = DateField.value;
   /* Delete all chars except 0..9 */
   for (i = 0; i < DateValue.length; i++) {
      if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {
         DateTemp = DateTemp + DateValue.substr(i,1);
      }
   }
   DateValue = DateTemp;
   /* Always change date to 8 digits - string*/
   /* if year is entered as 2-digit / always assume 20xx */
   if (DateValue.length == 6) {
      DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); }
   if (DateValue.length != 8) {
      err = 19;}
   /* year is wrong if year = 0000 */
   year = DateValue.substr(4,4);
   if (year == 0) {
      err = 20;
   }
   /* Validation of month*/
   month = DateValue.substr(2,2);
   if ((month < 1) || (month > 12)) {
      err = 21;
   }
   /* Validation of day*/
   day = DateValue.substr(0,2);
   if (day < 1) {
     err = 22;
   }
   /* Validation leap-year / february / day */
   if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0)) {
      leap = 1;
   }
   if ((month == 2) && (leap == 1) && (day > 29)) {
      err = 23;
   }
   if ((month == 2) && (leap != 1) && (day > 28)) {
      err = 24;
   }
   /* Validation of other months */
   if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {
      err = 25;
   }
   if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {
      err = 26;
   }
   /* if 00 ist entered, no error, deleting the entry */
   if ((day == 0) && (month == 0) && (year == 00)) {
      err = 0; day = ""; month = ""; year = ""; seperator = "";
   }
   /* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
   if (err == 0) {
      DateField.value = day + seperator + month + seperator + year;
   }
   /* Error-message if err != 0 */
   else {
      alert("¡La fecha no es correcta!");
      DateField.select();
      DateField.focus();
   }
}

    
//1a. confronto 2 date
function confronta_data(d1, d2, lang){
        
        if (d1.value == "" ||  d2.value == "")
            return true;
    
        var textITA = "La data iniziale deve essere precedente quella finale";
                    var textENG = "The arrival date must be earlier than departure";
                    var textESP = "La fecha de llegada debe ser anterior a la fecha de salida";
                    var textCAT = "El dia d'arribada ha de ser anterior al dia de sortida";
                    var textFRA = "La date d'arrivée doit être plus tôt que le départ";
    
        data1 = d1.value;
        data2 = d2.value;
        data1str = data1.substr(6)+data1.substr(3, 2)+data1.substr(0, 2);
        data2str = data2.substr(6)+data2.substr(3, 2)+data2.substr(0, 2);
         data1str=data1str.replace(' ',"");
        data2str=data2str.replace(' ',"");
        //controllo se la seconda data è successiva alla prima
        if (data2str-data1str<0) {
            GetText(lang, textITA, textENG, textESP, textCAT);
            return false;
            
        }else{
            return true; 
            
        }
       
}


//1b. la data non può essere inferiore della data odirna
function check_dataOdiernaMin(d1, lang){
        
       if (d1.value =="")
                return true;
    
        var textITA = "La data di partenza non può essere anteriore alla data odierna";
                    var textENG = "Departure date can not be earlier than today";
                    var textESP = "La fecha de salida no debe ser anterior al día de hoy";
                    var textCAT = "El dia de sortida no pot ser anterior al dia d'avui";
                    var textFRA = "La date de départ ne peut pas être antérieure à aujourd'hui";
                    
        data1 = d1.value;
        data1str = data1.value;
        data1str = data1.substr(6)+data1.substr(3, 2)+data1.substr(0, 2);
        
        
         var data = new Date();
         
         if (data.getDate() < 10)
            dataD = "0" + data.getDate().toString();
         else
            dataD = data.getDate().toString();
         
         if (data.getMonth() + 1 < 10)
            dataM = "0" + (data.getMonth() + 1).toString();
         else
            dataM = (data.getMonth() + 1).toString();
         
         dataY = data.getFullYear().toString();
         
         data2str  = dataY + dataM + dataD;
        
        
        data1str=data1str.replace(' ',"");
         data2str=data2str.replace(' ',"");
        
        if (data1str-data2str<0) {
            GetText(lang, textITA, textENG, textESP, textCAT);
            return false;
            
        }else{
            return true; 
            
        }
        
}



    
//2. controllo campo numerico    
    function numeralsOnly(evt) {
        evt = (evt) ? evt : event;
        var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : 
            ((evt.which) ? evt.which : 0));
        
       
        
        if (charCode > 31 && charCode != 46 && (charCode < 48 || charCode > 57 ) ) {
            alert("¡Puedes introducir solo números!"); 
            return false;
        }
        return true;
    }


    
//3. validazione label
function Field_Validator(label)
                {
                 if (trim(label.value) == "")
                    {
                    alert("Rellenar todos los campos con (*) ");
                     label.focus();
                    return (false);
                    }
                    return (true);
                }

// ricerca               
//3a. validazione label con scelta testo
function Field_ValidatorText(label, lang, string)
                {                               
                    var textITA = "Per eseguire la ricerca è necessario compilare il campo \"" + string  +"\"!";
                    var textENG = "You must choose a \"" + string  +"\"";
                    var textESP = "Para buscar debes debes elegir un \"" + string  +"\"";
                    var textCAT = "Per buscar cal escollir un \"" + string  +"\"";
                    var textFRA = "Pour effectuer une recherche est de choisir un \"" + string  +"\"";
                    
                    
                    if (trim(label.value) == "")
                    {
                        GetText(lang, textITA, textENG, textESP, textCAT);  
                        
                        
                     label.focus();
                    return (false);
                    }
                    return (true);
                }

//4a.  validazione label con scelta testo               
function Select_ValidatorText(label, lang, string)
                {
                    var textITA = "Per eseguire la ricerca è necessario compilare il campo \"" + string  +"\"!";
                    var textENG = "You must choose a \"" + string  +"\"";
                    var textESP = "Para buscar debes elegir un \"" + string  +"\"";
                    var textCAT = "Per buscar cal escollir un \"" + string  +"\"";
                    var textFRA = "Pour effectuer une recherche est de choisir un \"" + string  +"\"";
                    
                    if (label.value == "0" || label.value == "" || label.value == "-")
                    {
                    GetText(lang, textITA, textENG, textESP, textCAT);
                     label.focus();
                    return (false);
                    }
                    return (true);
                } 
                
                
//4. validazione select          
  function Select_Validator(label)
                {
                 if (label.value == "0" || label.value == "" || label.value == "-")
                    {
                    alert("Rellenar todos los campos con (*) ");
                     label.focus();
                    return (false);
                    }
                    return (true);
                } 
                

//5. validazione email    
  function Email_Validator(email)
{  
   
  var goodEmail = email.value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
   if (!goodEmail)
   {
        alert('Debes introducir una dirección \"Email\" valida.');
        email.focus();
       return (false);
   }
   return (true);
}
 
//6. check min lunghezza field
function MinLenght_Validator(label, minLenght, name)
{  
  
  if (label.value.length < minLenght && label.value != "")
   {
         alert("El campo \"" + name + "\" no puede ser inferior a " + minLenght + " caracteres.");
        label.focus();
        return (false);
   }
   return (true);
   
   }
 
  //7. check max lunghezza field
function MaxLenght_Validator(label, maxLenght, name)
{  
  
  if (label.value.length > maxLenght && label.value != "")
   {
         alert("El campo \"" + name + "\" no puede ser superior a " + maxLenght + " caracteres.");
        label.focus();
        return (false);
   }
   return (true);
   
   }
   
//8. check controllo password
function Password_Validator(label, label2)
{  
  
  if (label.value !=  label2.value)
   {
         alert("La contraseña no corresponde.");
        label.focus();
        return (false);
   }
   return (true);
   
   }

   
//9. regular expression: lettere + numeri + spazi
function RegExp_Validator(label, type, name)
{  
    var myRegExp;
    var valid;
    switch (type)
    {
        case 1:   //lettere ed uno spazio
              myRegExp = /[^a-z ']/i;
              break; 
        case 2:   //lettere e numeri
              myRegExp = /[^a-z\d_-]/i;
              break;
        case 3:   //numeri
              myRegExp = /[^\d]/i;
              break;
        }    
    
    valid  = !(myRegExp.test(label.value));
    //alert (label.value + " " + valid);
    
    if (valid == false) 
    {
    
        switch (type)
    {
        case 1:   //lettere ed uno spazio
              alert("En el campo \"" + name +  "\" puedes introducir solo letras, espacios y el caracter [\'].");
              break; 
        case 2:   //lettere e numeri
              alert("En el campo \"" + name +  "\" puedes introducir solo letras, números y los caracteres [_-]");  
              break;
        case 3:  //numeri
               alert("En el campo \"" + name +  "\" puedes introducir solo números");  
              break;
    }    
          
    
        label.focus();
        return (false);
    }
    

 return (true);      
}   

  
//10. Abilitazione di un campo al change di una select     
function Select_EnableField(fieldMaster, fieldSlave, selectedId)
{
    if (fieldMaster.value == selectedId)
        fieldSlave.disabled = false;
    else
        fieldSlave.disabled = true; 
}


//11. validazione obbligatorietà di secondo livello: select
function Select_Validator2level(fieldMaster, fieldSlave, selectedId)
{
    if (fieldMaster.value != selectedId)
    {
       return (true);
    }
    else
    {
        if  (fieldSlave.value == "")
        {
            alert("Rellenar el campo con (*) ");
            fieldSlave.focus();
            return (false);
        }   
    }
    return (true);
    }  
 

 //12. validazione check inserimento scelta tipo utente          
  function Check_Validator(label1, label2)
                {
                 if ((label1.checked == false) && (label2.checked == false))
                    {
                    alert("Seleccionar una opción entre: 'Turista' o 'Propietario' ");
                     return (false);
                    }
                      
                    return (true);
                }                  
               
  //13. validazione check generico
  function Check_GenericValidator(label1, field)
                {
                 if ((label1.checked == false))
                    {
                    alert("Debes seleccionar el campo: \"" + field + "\"");
                     return (false);
                    }
                      
                    return (true);
                } 
                
                
                
 //14. gestione pannello via checkbox

 function Check_GenericPanel(label, panel) 
 {
    if (document.getElementById) { // DOM3 = IE5, NS6
        
      if (label.checked == false)  
        document.getElementById(panel).style.display = 'none';
      else
        document.getElementById(panel).style.display = 'block';  
    }

                  
 }
 
