// ******************************************************
// ******************************************************

// VALIDATIONS (EN JAVASCRIPT) DE PLUSIEURS TEXT FIELD.
//   EXEMPLES: LES AERODROME_ID, LES DEPARTURE_ID, LES DESTINATION_ID, ETC.
//
// ******************************************************
// ******************************************************





// -------------------------------------------------------------------
// ENLEVER LES ESPACES (AVANT ET APRES).
// -------------------------------------------------------------------

function stripSpacesBeforeAfter(x) 
{
 
  // Remove spaces at the end:   
  var i = x.length - 1;
  var j = 0;
  var tab;
  for( ; i >= 0 && x.charAt(i) == ' '; i-- );

  // i now points to last non-blank character:
  x = x.substring( 0, i+1 );
  
  // Remove spaces at the beginning:
  while (x.substring(0,1) == ' ') 
    x = x.substring(1);

  return x;
}





// -------------------------------------------------------------------
// LAISSER UN SEUL ESPACE ENTRE LES MOTS.
// -------------------------------------------------------------------

function enleverEspacesEnTrop( contenuTextBox )
{
  var nouvelleChaine = ""; 
  tab = contenuTextBox.split(" ");

  for( var i = 0; i < tab.length; i++ )
  {
    if( tab[i].length > 0 )
      nouvelleChaine = nouvelleChaine + tab[i] + " ";
  } 
 
  return nouvelleChaine;
}





// -------------------------------------------------------------------
// ENLEVER LES ESPACES AU DEBUT ET A LA FIN
// LAISSER UN SEUL ESPACE ENTRE LES MOTS.
// -------------------------------------------------------------------

function stripSpacesInside(x) 
{
  // Remove spaces at the end:   
  var i = x.length - 1;
  var j = 0;
  var tab;
  for( ; i >= 0 && x.charAt(i) == ' '; i-- );

  // i now points to last non-blank character:
  x = x.substring( 0, i+1 );

  // Remove spaces at the beginning:
  while (x.substring(0,1) == ' ') 
    x = x.substring(1);

  // Replace spaces by '':
  x = replace( x, ' ', '' );

  return x;
}





// -------------------------------------------------------------------
// VERIFIER S'IL Y A SEULEMENT DES CARACTERES ALPHA-NUMERIQUES 
// -------------------------------------------------------------------

function verifierCaracteres(x)
{
  var valid="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

  for (var i=0; i< x.length; i++) 
  {
    if (valid.indexOf(x.charAt(i)) < 0) 
	  return false;
  }

  return true;
}





// -------------------------------------------------------------------
// VERIFIER SI
//   --> CHAQUE ID EST DE LONGUEUR 4 (S'IL N'Y PAS DE COORDONNEES).
//   -->    OU
//   --> CHAQUE ID EST DE LONGUEUR 4 OU 10 ou 11 (S'IL Y A DES COORDONNEES).
// -------------------------------------------------------------------

function verifierTailleID2( lesID, possede_coordonnees )
{
  if( possede_coordonnees == true )
  {
    if( !contientEspaces( lesID ) )
    {
      var lng = lesID.length-1;
      if( lng !=  4 && lng != 10 && lng != 11 )
       return false;
      else
       return true;
    }

    else
    {
     var tabID = new Array();
  
     tabID = lesID.split(' ');
     
     for( var i = 0; i < tabID.length -1; i++ )
     {
       if( tabID[i].length != 4 &&
           tabID[i].length != 10 && tabID[i].length != 11 )
         return false;
     }
     return true;
    }
  }
  
  else
  {
    if( !contientEspaces( lesID ) )
    {
      var lng = lesID.length - 1;

      if( lng !=  4 )
       return false;
      else
       return true;
    }

    else
    {
     var tabID = new Array();
  
     tabID = lesID.split(' ');
     
     for( var i = 0; i < tabID.length -1; i++ )
     {
       if( tabID[i].length != 4 )
       return false;
     }
     return true;
    }
  }
}





// -------------------------------------------------------------------
// REMPLACER DANS "STRING" TOUS LES "TEXT" PAR "BY"
// -------------------------------------------------------------------

function replace(string,text,by) {
     // Replaces text with by in string
     var strLength = string.length, txtLength = text.length;
     if ((strLength == 0) || (txtLength == 0)) return string;

     var i = string.indexOf(text);
     if ((!i) && (text != string.substring(0,txtLength))) return string;
     if (i == -1) return string;

     var newstr = string.substring(0,i) + by;

     if (i+txtLength < strLength)
         newstr += replace(string.substring(i+txtLength,strLength),text,by);

     return newstr;
 }





// -------------------------------------------------------------------
// VERIFIER SI LE CONTENU RECU CONTIENT DES ESPACES
// -------------------------------------------------------------------

function contientEspaces(x)
{
  for( var i = 0; i < x.length - 1; i++ )
  {
   if( x.charAt(i) == ' ' )
   {
    return true;  
   }
  }
  
  return false;
}





// -------------------------------------------------------------------
// VERIFIER S'IL Y A, AU MAXIMUM, 1 AERODROME_ID.
// NOTE: IL PEUT N'EN CONTENIR AUCUN.
// -------------------------------------------------------------------

function verifier_1_aerodrome(x)
{
  if( contientEspaces(x) )
    return false;
  else
    return true;
}





// -------------------------------------------------------------------
// VALIDER LES COORDONNEES.
//
// TAILLE: 10 OU 11 CARACTERES
//
// FORMAT: N4523W17408 
//      N: N               (1 CARACTERE)       (POSITION 0)
//     45: ENTRE 0 ET 90   (2 CARACTERES)      (POSITIONS 1 ET 2)
//     23: ENTRE 0 ET 59   (2 CARACTERES)      (POSITIONS 3 ET 4)
//      W: W               (1 CARACTERE)       (POSITION 5)
//         W  seulement, peu importe la langue Ref RAMAT, Termium et MANAB
//    174: ENTRE 0 ET 180  (2 OU 3 CARACTERES) (POSITIONS 6 ET 7, OU 6 ET 7 ET 8)
//     08: ENTRE 0 ET 59   (2 CARACTERES)      (POSITIONS 8 ET 9, OU 9 ET 10)
//
// Fonction appellee par (si la longueur de chaine de caractere est de 
//                        10 ou 11 seulement)
//         testerDepart
//         testerDestination
//         testerEnRoute
// 
// Parametres passes lors de l appel
//            x      : la coordonee elle meme (une seule)
//            langue : 
//            type   : le type de ID (depart, destination, enroute)
// -------------------------------------------------------------------

function validerCoordonnees(x, langue, type)
{

  var tab    = '';
  var id     = '';
  var token  = '';
  var token2 = '';
  
  var erreur = true;
  var ret    = true;

  tab = x.split(" ");

// type = depart, destination, enroute sinon traduire sort vide
  var descripteur = traduire( langue, type )

  msg1f='';
  msg2f='';
  msg3f='';
  msg4f='';
  msg5f='';
  msg6f='';

  msg1e='';
  msg2e='';
  msg3e='';
  msg4e='';
  msg5e='';
  msg6e='';

  msgASEPe='';
  msgASEPf='';

  msgtotal='';

  tailleID = x.length-1;

  for( var i = 0; i < tab.length; i++ )
  {
    if( tab[i].length == 10 || tab[i].length == 11 )
    {
      id = stripSpacesInside(tab[i]);
 
      // POSITION 0 ---------------------------------------
      token = id.charAt(0);
      if( token != 'N')
      {
// le premier caractere definissant la Latitude n est pas N.
         msg1f='\nLa latitude doit se trouver dans l\'hémisphère Nord (N).'
         msg1e='\nLatitude should be in northern hemisphere (N).'

        erreur = false;
      }
  
      // POSITION 5 --------------------------------------- 
      token = id.charAt(5);
//      if( token != 'W' && token != 'O' )
      if( token != 'W')
      {
// le permier caractere definissant la longitude n est pas W.
        msg2f='\nLa longitude doit être Ouest (W).'
        msg2e='\nLongitude should be West (W).'

        erreur = false;
      }

      // POSITIONS 1-2-3-4 ---------------------------------
// verifier que ce soient des chiffres seulement
      token = id.charAt(1) + id.charAt(2) + id.charAt(3) + id.charAt(4);

      if( !verifierCaracteresNumeriques( token ) )
      {
        msg3f='\nSeuls les caractères numériques sont permis pour definir les degrés / minutes de latitude.'
        msg3e='\nOnly numerical characters are allowed to define degree / minutes of latitude.'
	erreur = false
      }
      else
      {
        token = id.charAt(1) + id.charAt(2);
        if( token < 0 || token > 90 )
        {
// les degres de latitude ne sont pas valides.
          msg3f='\nLes degrés de latitude doivent être entre 00 et 90 Nord.'
          msg3e='\nDegrees of latitude should be between 00 and 90 North.'

          erreur = false;
        }

        token = id.charAt(3) + id.charAt(4);
        if( token < 0 || token > 59 )
        {
// les minutes de latitude ne sont pas valides.
          msg4f='\nLes minutes de latitude doivent être entre 00 et 59.'
          msg4e='\nMinutes of latitude should be between 00 and 59.'

          erreur = false;
        }
      } 
  
      // POSITIONS 6-7-8-9-10 -----------------------------
// verifier qe ce soit des chiffres seulement
      token  = id.charAt(6) + id.charAt(7) + id.charAt(8) + id.charAt(9) + id.charAt(10);

      if( !verifierCaracteresNumeriques( token ) )
      {
        msg5f='\nSeuls les caractères numériques sont permis pour définir les degrés / minutes de longitude.'
        msg5e='\nOnly numerical characters are allowed to define degree / minutes of longitude.'
        erreur = false;
      }
      else
      {
        token  = id.charAt(6) + id.charAt(7) + id.charAt(8);
        token2 = id.charAt(9) + id.charAt(10);
 
        if( (token2.length ) == 1 )
        {
          token  = id.charAt(6) + id.charAt(7);
          token2 = id.charAt(8) + id.charAt(9);
    
          if( token < 0 || token > 180 || token2 < 0 || token2 > 59 )
          {
// on a 2 chiffres pour definir les degres de longitude
// les degres de longitude ne sont pas valides.
// les minutes de longitude ne sont as valides.
            msg5f='\nLes degrés de longitude doivent être entre entre 000 et 180 Ouest et les minutes entre 00 et 59.'
            msg5e='\nDegrees of longitude should be numbers 000 and 180 West and minutes between 00 and 59.'

            erreur = false;
          }
        }

        else
        {
          if( token < 0 || token > 180 || token2 < 0 || token2 > 59 )
          {
// 3 chiffres pour definir les degres de longitude
// les degres de longitude ne sont pas valides.
// les minutes de longitude ne sont as valides.
            msg6f='\nLes degrés de longitude doivent être entre 000 et 180 Ouest et les minutes entre 00 et 59.'
            msg6e='\nDegrees of longitude should be between 000 and 180 West and minutes between 00 and 59.'

            erreur = false;
          }
        }
      }
    }
  } 
// ici j ai valide le detail dans la coordonnees Lat Long allons voir si elle est dans 
// le domaine de ASEP.

     contenu_tmp=stripSpacesBeforeAfter(x)
     ret = projASEP.validerLatLon( contenu_tmp, langue );

     if (ret == false )
     {
       msgASEPe= 'The latitude/longitude coordinate provided is outside the ASEP domain. Please use the MAP VIEW.';
       msgASEPf= 'La coordonnée latitude/longitude entrée est en dehors du domaine de ASEP. Utiliser la VERSION CARTE.';
       erreur = false;
     }

// rassemblement des differents messages d erreur rencontres et affiche si msgtotal est non vide
	if ( langue == 'francais')
 	{
          msgtotal= msg1f + msg2f + msg3f + msg4f + msg5f + msg6f + msgASEPf;
	}
	else
	{
          msgtotal= msg1e + msg2e + msg3e + msg4e + msg5e + msg6e + msgASEPe;
	}

        if ( msgtotal == '')
        {
          return erreur;
        }
        else
        {
          if ( langue == 'francais' )
          {
      	    alert ('Il y a un problème avec la coordonnée latitude/longitude entrée pour ' + descripteur +'.\n' + '\n' + 'Vous avez entré ' + x + '\n' + '\n' + msgtotal +  '\n\nCliquez sur un des liens suivants : *Départ, Points enroute ou *Destination pour obtenir plus d\'information sur le format possible.');
           }
           else
           {
              alert('There is a problem with the latitude/longitude coordinate entered for ' + descripteur + '.\n' + '\n' + 'You have entered ' + x + '\n' + '\n' + msgtotal +  '\n\nClick on one of the  *Departure, Enroute Points or *Destination links to get more information about possible format.');
           }
        }
  return erreur; 
}



// -------------------------------------------------------------------
// VERIFIER S'IL Y A, AU MAXIMUM, "NOMBRE" AERODROME_ID.
// NOTE: IL PEUT Y EN AVOIR AUCUN.
// -------------------------------------------------------------------

function verifier_nb_aerodromes(x, nombre)
{
  var quantite = 0;
  
  for( var i = 0; i < x.length; i++ )
  {
    if( x.charAt(i) == ' ' )
      quantite = quantite + 1;
  }
  
  if( quantite > nombre )
    return false;
  else
    return true;

}





/////
// -------------------------------------------------------------------
// COMPTER LE NOMBRE DE IDs PRESENTS DANS UN TEXT FIELD.
// -------------------------------------------------------------------

function compterNombreID( contenuTextBox )
{
  var nombre = 0;
  var contenu = "";

  contenu = enleverEspacesEnTrop( contenuTextBox );
  contenu = stripSpacesBeforeAfter( contenu );
  
  for( var i = 0; i < contenu.length; i++ )
  {
    if( contenu.charAt(i) != ' ' )
    {
      nombre = nombre + 1;
      while( contenu.charAt(i) != 0 )
        i++;
    }
  } 

  return nombre;
}





// -------------------------------------------------------------------
// COMPTER LE NOMBRE D'ESPACES
// -------------------------------------------------------------------

function compterEspaces( texte )
{
  var nombre = 0;
  var valid="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
 
  for( var i = 0; i < texte.length; i++ )
  { 
    if( valid.indexOf(texte.charAt(i)) < 0 )
      nombre = nombre + 1;   
  }
   
  return nombre;
}





// -------------------------------------------------------------------
// VERIFIER SI LE CONTENU EST VIDE.
// -------------------------------------------------------------------

function empty(x) 
{ 
 
  if (x.length > 0) 
    return false; 
  else 
    return true; 
}





// -------------------------------------------------------------------
// VERIFIER QUE LE TEXT FIELD "Stations" (METAR) REMPLIT LES 
// CONDITIONS SUIVANTES:
//   --> MINIMUM 1 ID
//   --> 1 ESPACE ENTRE CHAQUE ID
//   --> CARACTERES ALPHA-NUMERIQUES
//   --> TAILLE DES IDs: 4
// -------------------------------------------------------------------

function testerMetar( langue )
{
  var nouveau = '';
  var erreur = true;


  // LIRE LE ID DANS LA PAGE HTML
  var contenuField = document.Produit.Stations.value.toUpperCase();


  // ENLEVER LES ESPACES AU DEBUT, A LA FIN ET A L'INTERIEUR
  contenuField = stripSpacesBeforeAfter( contenuField );

  var contenu_tmp  = enleverEspacesEnTrop( contenuField );

  for( var i = 0; i < contenu_tmp.length - 1; i++ )
    nouveau = nouveau + contenu_tmp.charAt(i);  


  // ID OBLIGATOIRE
  if( contenu_tmp == "" )
  {
    if( langue == 'anglais' )
    {
      alert('Please enter an aerodrome ID.');
      return false;
    }
    else
    {
      alert('Veuillez entrer un identificateur d\'aérodrome.');
      return false;
    }
  }
  
  var contenu_colle = "";


  // ECRIRE LE NOUVEAU ID DANS LE TEXT FIELD DE LA PAGE HTML
  document.Produit.Stations.value = nouveau;


  // VERIFIER QUE LE ID EST COMPOSE DE CARACTERES ALPHA-NUMERIQUES SEULEMENT
  contenu_colle = stripSpacesInside( contenu_tmp );

  if( !verifierCaracteres( contenu_colle ) )
  {
    if( langue == 'anglais' )
    {
      alert('Only alphanumeric characters allowed.');
      return false;
    }
    else
    {
      alert('Seuls les caractères alphanumériques sont permis.');
      return false;	
    }
  }

  // VERIFIER LA TAILLE DU ID
  if( !verifierTailleID2( contenu_tmp, false ) )
  {
    if( langue == 'anglais' )
    {
      alert('Please use 4 alphanumeric characters to define the aerodrome ID.');
      return false;	
    }
    else
    {
      alert('Veuillez utiliser 4 caractères alphanumériques pour définir l\'identificateur de l\'aérodrome.');
      return false;	
    }
  }
  
  return true;
}





// -------------------------------------------------------------------
// VERIFIER QUE LE TEXT FIELD "Aerodrome ID" REMPLIT LES CONDITIONS SUIVANTES:
//   --> MINIMUM 1 ID
//   --> MAXIMUM 1 ID
//   --> CARACTERES ALPHA-NUMERIQUES
//   --> TAILLE DES ID: 4
// -------------------------------------------------------------------

function testerAerodrome( langue )
{
  var nouveau = '';    
  var retour = true;


  // LIRE LE ID DANS LA PAGE HTML
  var contenuField = document.Produit.AerodromeId.value.toUpperCase();


  // ENLEVER LES ESPACES AU DEBUT, A LA FIN ET A L'INTERIEUR
  contenuField = stripSpacesBeforeAfter( contenuField );

  var contenu_tmp  = enleverEspacesEnTrop( contenuField );

  for( var i = 0; i < contenu_tmp.length - 1; i++ )
    nouveau = nouveau + contenu_tmp.charAt(i);  


  // ID OBLIGATOIRE
  if( contenu_tmp == "" )
  {
    if( langue == 'anglais' )
    {
      alert('Please enter an aerodrome ID.');
      return false;      
    }
    else
    {
      alert('Veuillez entrer un identificateur d\'aérodrome.');
      return false;
    }
  }

  var contenu_colle = "";


  // ECRIRE LE NOUVEAU ID DANS LE TEXT FIELD DE LA PAGE HTML
  document.Produit.AerodromeId.value = nouveau;


  // 1 SEUL ID PERMIS
  if( !verifier_1_aerodrome( contenu_tmp ) )
  {
    if( langue == 'anglais' )
    {
      alert('Only 1 aerodrome ID allowed.');  
      return false;
    }
    else
    {
      alert('Un seul indentificateur d\'aérodrome est permis.');
      return false;
    }
  }

  contenu_colle = stripSpacesInside( contenu_tmp );


  // VERIFIER QUE LE ID EST COMPOSE DE CARACTERES ALPHA-NUMERIQUES SEULEMENT
  if( !verifierCaracteres( contenu_colle ) )
  {
    if( langue == 'anglais' )
    {
      alert('Only alphanumeric characters allowed.');
      return false;
    }
    else
    {
      alert('Seuls les caractères alphanumériques sont permis.');
      return false;
    }
  }

  // VERIFIER LA TAILLE DU ID
  if( !verifierTailleID2( contenu_tmp, false ) && contenu_tmp != '' )
  {
    if( langue == 'anglais' )
    {
      alert('Please use 4 alphanumeric characters to define the aerodrome ID.');
      return false;
    }
    else
    {
      alert('Veuillez utiliser 4 caractères alphanumériques pour définir l\'identificateur de l\'aérodrome.');
      return false;
    }
  }
  
  return true;

}





// -------------------------------------------------------------------
// VERIFIER QUE LE TEXT FIELD "Departure ID" REMPLIT LES CONDITIONS SUIVANTES:
//   --> MINIMUM: 1 ID
//   --> MAXIMUM: 1 ID
//   --> CARACTERES ALPHA-NUMERIQUES
//   --> TAILLE DES ID: 4 OU 10 OU 11
//
// Fonction appelee par testerRouteBriefing
// -------------------------------------------------------------------

function testerDepart( langue )
{
  var nouveau = '';  
  var ret = true;

  // LIRE LE ID DANS LA PAGE HTML
  var contenuField = document.Produit.Depart.value.toUpperCase();

  // ENLEVER LES ESPACES AU DEBUT, A LA FIN ET A L'INTERIEUR
  contenuField = stripSpacesBeforeAfter( contenuField );

  var contenu_tmp  = enleverEspacesEnTrop( contenuField );

  for( var i = 0; i < contenu_tmp.length - 1; i++ )
    nouveau = nouveau + contenu_tmp.charAt(i);  

  // ID OBLIGATOIRE
  if( contenu_tmp == "" )
  {
    if( langue == 'anglais' )
    {
      alert('Please enter a departure ID.');
      return false;
    }
    else
    {
      alert('Veuillez entrer un identificateur pour l\'aérodrome de départ.');
      return false;
    }
  }
 
  var contenu_colle = "";


  // ECRIRE LE NOUVEAU ID DANS LE TEXT FIELD DE LA PAGE HTML
  document.Produit.Depart.value = nouveau;


  // 1 SEUL ID PERMIS
  if( !verifier_1_aerodrome( contenu_tmp ) )
  {
    if( langue == 'anglais' )
    {
      alert('Only 1 aerodrome ID allowed for departure.');  
      return false;
    }
    else
    {
      alert('Un seul indentificateur d\'aérodrome est permis pour le départ.');
      return false;
    }
  }

  contenu_colle = stripSpacesInside( contenu_tmp );


  // VERIFIER QUE LE ID EST COMPOSE DE CARACTERES ALPHA-NUMERIQUES SEULEMENT
  if( !verifierCaracteres( contenu_colle ) )
  {
    if( langue == 'anglais' )
    {
      alert('Only alphanumeric characters allowed.');
      return false;
    }
    else
    {
      alert('Seuls les caractères alphanumériques sont permis.');
      return false;
    }
  }

  // VERIFIER LA TAILLE DU ID QUI DOIT ETRE DE 4, 10 OU 11 CARACTERES.
  // C EST LE SEUL TEST QUE CETTE FONCTION FAIT.

  if( !verifierTailleID2( contenu_tmp, true ) && contenu_tmp != '' )
  {
    if( langue == 'anglais' )
      str = "departure ID";
    else {
      str = "l\'identificateur de l\'aérodrome de départ";
      print_coordinate_errmsg( langue, str );
      return false;
    }
  }

  // VALIDER COORDONNEE DEVRAIT ETRE APPELE SEULEMENT SI COORDONNEE CONTIENT 
  // UN ID DE TAILLE 10 OU 11 ALORS QU AVANT ARRIVEE DE ASEP validerCoordonnees ETAIT
  // TOUJOURS APPELEE. ATtention au EnRoute (il peut y avoir 15 EnRoute)

// trouve le nombre de coordonnee lat long dans contenu_tmp
// boucle sur ce nombre et va dans validerCoordonnees avec chacune de celle ci
// si une seule ereur est trouvee alros quitte.

  var taille = contenu_tmp.length-1;
  if( taille == 10  || taille == 11 )
  {
// on est en presence d une coordonnee lat long
    ret = validerCoordonnees( contenu_tmp, langue, 'depart' );
    return ret;
  }
  return true;
}




// -------------------------------------------------------------------
// AFFICHAGE DE MESSAGE D ERREUR A L USAGER EN CE QUI TRAITE DU 
// FORMAT DES IDENTIFICATEURS D AERODROME DANS LE CAS DE LA PAGE
// DU ROUTE (introduit lors de ASEP). 
// Permet d avoir la valeur de langue et du descripteur (depart, destination etc).
// -------------------------------------------------------------------


function print_coordinate_errmsg( langue, descr )
{
   if( langue == 'anglais' )
      {
      alert('The format provided for ' + descr + ' is not valid.\n\nFormat should be:\r1. a 4 characters ID or \r2. a Lat / Long coordinate (using 10 or 11 characters).\n\nClick on the ' + descr + ' link get more information about possible format.');
      }
   else
      {
      alert('Le format entré pour ' + descr + ' n\'est pas valide.\n\nLe format doit être : \r1. un identificateur de 4 caractères ou alors \r2. une coordonnee Lat / Long de 10 a 11 caractères.\n\nCliquez sur le lien ' + descr + ' pour obtenir plus d\'information sur le format possible.');
      }
}



// -------------------------------------------------------------------
// VERIFIER QUE LE TEXT FIELD "Destination ID" REMPLIT LES 
// CONDITIONS SUIVANTES:
//   --> MINIMUM: 1 ID
//   --> MAXIMUM: 1 ID
//   --> CARACTERES ALPHA-NUMERIQUES
//   --> TAILLE DES ID: 4 OU 10 OU 11
// -------------------------------------------------------------------

function testerDestination(langue)
{
  var nouveau = '';

 
  // LIRE LE ID DANS LA PAGE HTML
  var contenuField = document.Produit.Destination.value.toUpperCase();


  // ENLEVER LES ESPACES AU DEBUT, A LA FIN ET A L'INTERIEUR
  contenuField = stripSpacesBeforeAfter( contenuField );

  var contenu_tmp  = enleverEspacesEnTrop( contenuField );

  for( var i = 0; i < contenu_tmp.length - 1; i++ )
    nouveau = nouveau + contenu_tmp.charAt(i);  


  // ID OBLIGATOIRE
  if( contenu_tmp == "" )
  {
    if( langue == 'anglais' )
    {
      alert('Please enter a destination ID.');

      return false;
    }
    else
    {
      alert('Veuillez entrer un identificateur pour l\'aérodrome de destination.');
      return false;
    }
  }
 
  var contenu_colle = "";


  // ECRIRE LE NOUVEAU ID DANS LE TEXT FIELD DE LA PAGE HTML
  document.Produit.Destination.value = nouveau;


  // 1 SEUL ID PERMIS
  if( !verifier_1_aerodrome( contenu_tmp ) )
  {
    if( langue == 'anglais' )
    {
      alert('Only 1 destination ID allowed.');  
      return false;
    }
    else
    {
      alert('Un seul identificateur pour la destination est permis.');  
      return false;
    }
  }

  contenu_colle = stripSpacesInside( contenu_tmp );


  // VERIFIER QUE LE ID EST COMPOSE DE CARACTERES ALPHA-NUMERIQUES SEULEMENT
  if( !verifierCaracteres( contenu_colle ) )
  {
    if( langue == 'anglais' )
    {
      alert('Only alphanumeric characters allowed.');
      return false;
    }
    else
    {
      alert('Seuls les caractères alphanumériques sont permis.');
      return false;
    }
  }



  // VERIFIER LA TAILLE DU ID QUI DOIT ETRE DE 4, 10 OU 11 CARACTERES.
  // C EST LE SEUL TEST QUE CETTE FONCTION FAIT.

  if( !verifierTailleID2( contenu_tmp, true ) && contenu_tmp != '' )
  {
    if( langue == 'anglais' )
      str = "destination ID";
    else
      str = "l\'identificateur de l\'aérodrome de destination";
      print_coordinate_errmsg( langue, str );
      return false;
  }

  // VALIDER COORDONNEE DEVRAIT ETRE APPELE SEULEMENT SI COORDONNEE CONTIENT 
  // UN ID DE TAILLE 10 OU 11 ALORS QU AVANT ARRIVEE DE ASEP validerCoordonnees ETAIT
  // TOUJOURS APPELEE.

  var taille = contenu_tmp.length-1;

  if( taille == 10  || taille == 11 )
  {
// on est en presence d une coordonnee lat long
    ret = validerCoordonnees( contenu_tmp, langue, 'destination' );
    return ret;
  }
}





// -------------------------------------------------------------------
// VERIFIER QUE LE TEXT FIELD "EnRoute Airport ID" REMPLIT LES 
// CONDITIONS SUIVANTES:
//   --> MINIMUM: 0 ID
//   --> MAXIMUM: 15 ID
//   --> 1 ESPACE ENTRE CHAQUE ID
//   --> CARACTERES ALPHA-NUMERIQUES
//   --> TAILLE DES ID: 4 OU 10 OU 11
// -------------------------------------------------------------------

function testerEnRoute(langue)
{
  var nouveau = '';
  var tab_contenu = new Array();
  var ret = true;


  // LIRE LE(S) ID(S) DANS LA PAGE HTML
  var contenuField = document.Produit.EnRoute.value.toUpperCase();

  // ENLEVER LES ESPACES AU DEBUT, A LA FIN ET A L'INTERIEUR
  contenuField = stripSpacesBeforeAfter( contenuField );
  // contenuField a des blancs entre les ID entres.

  var contenu_tmp  = enleverEspacesEnTrop( contenuField );

  for( var i = 0; i < contenu_tmp.length - 1; i++ )
    nouveau = nouveau + contenu_tmp.charAt(i);  

  var contenu_colle = "";


  // ECRIRE LE(S) NOUVEAU(X) ID(S) DANS LE TEXT FIELD DE LA PAGE HTML
  document.Produit.EnRoute.value = nouveau;

  contenu_colle = stripSpacesInside( contenu_tmp );


  // VERIFIER QUE LE ID EST COMPOSE DE CARACTERES ALPHA-NUMERIQUES SEULEMENT
  if( !verifierCaracteres( contenu_colle ) )
  {
    if( langue == 'anglais' )
    {
      alert('Only alphanumeric characters allowed.');
      return false;
    }
    else
    {
      alert('Seuls les caractères alphanumériques sont permis.');
      return false;
    }
  }

  
  // VERIFIER QUE LE NOMBRE MAXIMAL DE ID EST 15.
  if( !verifier_nb_aerodromes( contenu_tmp, 15 ) )
  {
    if( langue == 'anglais' )
    {
      alert('The maximum number of enroute aerodrome is 15.');
      return false;
    }
    else
    {
      alert('Le nombre maximum d\'aérodromes enroute est de 15.');  
      return false;
    }
  }

  // VERIFIER LA TAILLE DU ID QUI DOIT ETRE DE 4, 10 OU 11 CARACTERES.
  // C EST LE SEUL TEST QUE CETTE FONCTION FAIT.

  if( !verifierTailleID2( contenu_tmp, true ) && contenu_tmp != '' )
  {

    if( langue == 'anglais' )
      str = "enroute ID";
    else
      str = "le (les) identificateur(s)  enroute";
      print_coordinate_errmsg( langue, str );
      return false;

  }

// compter combien de ID dans contenu_tmp et conserver la taille du vecteur (nbre)

    tab_contenu=contenuField.split(' ');
    nbre=tab_contenu.length;

  // VALIDER COORDONNEE DEVRAIT ETRE APPELE SEULEMENT SI COORDONNEE CONTIENT 
  // UN ID DE TAILLE 10 OU 11 ALORS QU AVANT ARRIVEE DE ASEP validerCoordonnees ETAIT
  // TOUJOURS APPELEE. ATtention au EnRoute (il peut y avoir 15 EnRoute)

    for ( var i = 0; i < nbre; i ++ )
    {
      var taille = tab_contenu[i].length;

      if( taille == 10  || taille == 11 )
      {
      ret = validerCoordonnees( tab_contenu[i], langue, 'enroute' );
      if(!ret) return ret;
      }
    }

//  if( !validerCoordonnees( contenu_tmp, langue, 'enroute' ) )
//    return false;
   return true;

}





// -------------------------------------------------------------------
// VERIFIER QUE LE TEXT FIELD "Alternate ID" REMPLIT LES CONDITIONS SUIVANTES:
//   --> MINIMUM: 0 ID
//   --> MAXIMUM: 3 ID
//   --> 1 ESPACE ENTRE CHAQUE ID
//   --> CARACTERES ALPHA-NUMERIQUES
//   --> TAILLE DES ID: 4
// -------------------------------------------------------------------

function testerAlternates(langue)
{
  var nouveau = '';


  // LIRE LE(S) ID(S) DANS LA PAGE HTML
  var contenuField = document.Produit.Alternates.value.toUpperCase();


  // ENLEVER LES ESPACES AU DEBUT, A LA FIN ET A L'INTERIEUR
  contenuField = stripSpacesBeforeAfter( contenuField );

  var contenu_tmp  = enleverEspacesEnTrop( contenuField );

  for( var i = 0; i < contenu_tmp.length - 1; i++ )
    nouveau = nouveau + contenu_tmp.charAt(i);  

  var contenu_colle = "";


  // ECRIRE LE(S) NOUVEAU(X) ID(S) DANS LE TEXT FIELD DE LA PAGE HTML
  document.Produit.Alternates.value = nouveau;

  contenu_colle = stripSpacesInside( contenu_tmp );


  // VERIFIER QUE LE ID EST COMPOSE DE CARACTERES ALPHA-NUMERIQUES SEULEMENT
  if( !verifierCaracteres( contenu_colle ) )
  {
    if( langue == 'anglais' )
    {
      alert('Only alphanumeric characters allowed.');
      return false;
    }
    else
    {
      alert('Seuls les caractères alphanumériques sont permis.');
      return false;
    }
  }
  

  // VERIFIER QUE LE NOMBRE MAXIMAL DE ID EST 3.
  if( !verifier_nb_aerodromes( contenu_tmp, 3 ) )
  {
    if( langue == 'anglais' )
    {
      alert('The maximum number of alternate aerodromes is 3.');
      return false;
    }
    else
    {
      alert('Le nombre maximum d\'aérodromes de dégagement est de 3.');  
      return false;
    }     
  }

  // VERIFIER LA TAILLE DU ID
  if( !verifierTailleID2( contenu_tmp, false ) && contenu_tmp.length != 0 )
  {
    if( langue == 'anglais' )
    {
      alert('Please use 4 alphanumeric characters to define the alternate ID.');
      return false;
    }
    else
    {
      alert('Veuillez utiliser 4 caractères alphanumériques pour définir l\'identificateur de l\'aérodrome de dégagement.');
      return false;
    }
  }

  return true;

}




// -------------------------------------------------------------------
// COMPARER LES "En route ID" AVEC LES "Departure ID" et "Destination ID"
// -------------------------------------------------------------------

function comparerEnRoute_Depart_Destination( route, dep, des )
{
//  if( route != '' )
  var nombre = compterNombreID( route );
  if( nombre == 1 )
  {
    var tab   = new Array();
    var lng   = 0;
    
    tab   = route.split(' ');
    lng   = tab.length;

    for( var j = 0; j < lng; j++ )
    {
      if( dep == tab[j] && des == tab[j] )
      {
        return true;
      }
    }

    return false;
  } 

  else
    return false;

}





// -------------------------------------------------------------------
// COMPARER LE "Departure ID" et le "Destination ID".
// -------------------------------------------------------------------

function comparerDepart_Destination( dep, des, route )
{
  if( dep == des && route == '' && dep != '' && des != '' )
    return true;
  else
    return false;  
}





// -------------------------------------------------------------------
// COMPARER LES CHAMPS SUIVANTS DE LA PAGE "Route Briefing":
//   --> "Departure ID" et "Destination ID"
//   --> "Enroute Airport(s) ID" et "Departure ID"
//   --> "Enroute Airport(s) ID" et "Destination ID"
// -------------------------------------------------------------------

function comparer( langue )
{
  if( comparerDepart_Destination( document.Produit.Depart.value,
                                  document.Produit.Destination.value,
                                  document.Produit.EnRoute.value ) )
  {
    if( langue == 'anglais' )
    {
      alert('Departure and destination ID must be different.');
      return false;
    }
    else
    {
      alert('Les identificateurs d\'aérodromes de départ et de destination doivent être différents.');
      return false;
    }
  }


  if( comparerEnRoute_Depart_Destination( document.Produit.EnRoute.value,
                                          document.Produit.Depart.value,
                                          document.Produit.Destination.value ) )
  {
    if( langue == 'anglais' )
    {
      alert('The \"departure ID\" and the \"destination ID\" should not be the same as the \"enroute airport(s) ID\". ');
      return false;
    }
    else
    {
      alert('Le ID du départ et de la destination ne doivent pas être le même que celui du \"enroute airport(s)\". ');
      return false;
    }
  }
  return true;
}


// -------------------------------------------------------------------
// Si le choix ASEP / PESA est selectionne, verifie qu'une option est prise
// et vice-et-versa.
// -------------------------------------------------------------------

function testerAsep( langue )
{
   var lOptionChoisie;
   var lSelection = 0; // De 0-Complete à 7-Aucune.
   var lErrMsg = "", lErrMsgDebut, lEt;
   var aChampsObl;
   if( langue == 'anglais' )
      {
      lErrMsgDebut = "For the ASEP products, you must select ";
      lEt = " and ";
      aChampsObl = new Array("an altitude", "a departure time", "an estimated time enroute"); 
      }
   else
      {
      lErrMsgDebut = "Pour les produits PESA, veuillez choisir ";
      lEt = " et ";
      aChampsObl = new Array("une altitude", "une heure de départ", "une durée prévue en route"); 
      }
   with ( document.Produit )
      {
      lOptionChoisie = ( rwt_asepCat.checked || rwt_asepFQ.checked || rwt_asepHWind.checked
         || rwt_asepHtWind.checked || rwt_asepCld.checked || rwt_asepMslp.checked
         || rwt_asepIcg.checked || rwt_asepTT.checked );
      lSelection = ( niveauVol.selectedIndex>0 ? 0:1 )
         + ( hreAsep.selectedIndex>0 ? 0:2)
         + ( tpsEstime.selectedIndex>0 ? 0:4 );
      }
   switch ( lSelection )
      {
      case 0:
         if ( ! lOptionChoisie )
            {
            if( langue == 'anglais' )
               {
               lErrMsg = "Please select at least one product option in ASEP selection";
               }  
            else
               {
               lErrMsg = "Veuillez choisir au moins un produit parmis les choix de PESA";
               }
            }
         break;
      case 1:
         lErrMsg = lErrMsgDebut + aChampsObl[0]; 
         break;
      case 2:
         lErrMsg = lErrMsgDebut + aChampsObl[1]; 
         break;
      case 3:
         lErrMsg = lErrMsgDebut + aChampsObl[0] + lEt + aChampsObl[1]; 
         break;
      case 4:
         lErrMsg = lErrMsgDebut + aChampsObl[2]; 
         break;
      case 5:
         lErrMsg = lErrMsgDebut + aChampsObl[0] + lEt + aChampsObl[2]; 
         break;
      case 6:
         lErrMsg = lErrMsgDebut + aChampsObl[1] + lEt + aChampsObl[2]; 
         break;
      default:
         if ( lOptionChoisie )
            {
            lErrMsg = lErrMsgDebut + aChampsObl[0] + ", " + aChampsObl[1] + lEt + aChampsObl[2];
            } 
         break;
      }
   if (lErrMsg != "")
      {
      alert(lErrMsg + ".");
      }
   return (lErrMsg == "");
}   



// ===================================================================
// ===================================================================

// VALIDER LA PAGE "Route Briefing"

// ===================================================================
// ===================================================================

function testerRouteBriefing( langue )
  {
  var notam_msg_a = 'To obtain NOTAM: (1) you must select at least one NOTAM type and (2) choose between the option Corridor or Waypoint.';
  var notam_msg_f = 'Pour obtenir des NOTAM, vous devez (1) sélectionner au moins un type de NOTAM et (2) choisir entre les options Corridor et Waypoint.';

  // Tester ==false car les fonctions retournent parfois null au lieu de true
  if (testerDepart( langue )==false) return false;
  if (testerEnRoute( langue )==false) return false;
  if (testerDestination( langue )==false) return false;
  if (testerAlternates( langue )==false) return false;
  if (comparer( langue )==false) return false;
  if (testerAsep( langue )==false) return false;
  // Check if user has selected any weather product
  if ( valider_selection_produits(langue) )
     {
     setDefaultValuesASEP();
     document.Produit.submit();
     }
  }


// ===================================================================
// ===================================================================

// VALIDER LA PAGE "Local Briefing"

// ===================================================================
// ===================================================================

function testerLocalBriefing( langue )
{
  if (testerAerodrome( langue ))
    {
    // Check if user has selected any weather product
    if ( valider_selection_produits(langue) ) document.Produit.submit();
    }     
}


// ===================================================================
// ===================================================================

// VALIDER LA PAGE "Forecast & Observations" (METAR/TAF)

// ===================================================================
// ===================================================================

function testerMetarTaf( langue )
{
  var metar = '';

  metar = testerMetar( langue ); 

  if( metar == true )
    document.Produit.submit();
}


// -------------------------------------------------------------------
// VERIFIER QU'UN BOUTON EST CHOISI DANS UNE GROUPE DE CHOIX (tableau)
// -------------------------------------------------------------------

function testerSelectionChoix(obj)
{
   for (var i=0; i < obj.length; i++)  {
      if (obj[i].checked) return true;
   }
   return false;
}




// -------------------------------------------------------------------
// VERIFIER QUE LE CHECK BOX "Region" (tableau) CONTIENT UNE VALEUR.
// -------------------------------------------------------------------

function testerRegion(langue)
{
   if (testerSelectionChoix(document.Produit.Region)) return true;
   if( langue == 'anglais' ) alert('Please select a region.');  
   else alert('Veuillez choisir une région.');
   return false;
}


// -------------------------------------------------------------------
// VERIFIER QUE LE CHECK BOX  "FIR" CONTIENT UNE VALEUR.
// ------------------------------------------------------------------- 

function testerRegionFIR(langue)
{
   if (testerSelectionChoix(document.Produit.FIR)) return true;
   if( langue == 'anglais' ) alert('Please select a region.');  
   else alert('Veuillez choisir une région.');
   return false;
} 





// -------------------------------------------------------------------
// VERIFIER QUE LE CHECK BOX "sat" CONTIENT UNE VALEUR.
// ------------------------------------------------------------------- 

function testerImageSat(langue)
{
   if (testerSelectionChoix(document.Produit.sat)) return true;
   if( langue == 'anglais' ) alert('Please make a selection of product.');  
   else alert('Veuillez choisir un produit.');
   return false;
}



// -------------------------------------------------------------------
// VERIFIER QUE LE CHECK BOX "radar" CONTIENT UNE VALEUR.
// ------------------------------------------------------------------- 

function testerRegionRadar(langue)
{
   if (testerSelectionChoix(document.Produit.radar)) return true;
   if( langue == 'anglais' ) alert('Please select a region and the type of information.');  
   else alert('Veuillez choisir une région ainsi qu\'un type d\'information.');
   return false;
} 



// -------------------------------------------------------------------
// VERIFIER QUE LE CHECK BOX "type" (page de radar) CONTIENT UNE VALEUR.
// -------------------------------------------------------------------  

function testerTypeRadar(langue)
{
   if (testerSelectionChoix(document.Produit.type)) return true;
   if( langue == 'anglais' ) alert('Please select the type of information.');  
   else alert('Veuillez choisir le type d\'information.');
   return false;
} 



// -------------------------------------------------------------------
// VERIFIER QUE LE CHECK BOX "rwt_uprWindsCharts180" CONTIENT UNE VALEUR.
// -------------------------------------------------------------------  

function testerNiveauVolFD_FL180(langue)
{
   if (testerSelectionChoix(document.Produit.rwt_uprWindsCharts180)) return true;
   if( langue == 'anglais' ) alert('Please select a valid time with a flight level and a region.');  
   else alert('Veuillez choisir une heure de validité avec un niveau de vol ainsi qu\'une région.');
   return false;
} 



// -------------------------------------------------------------------
// VERIFIER QUE LE CHECK BOX "Region" CONTIENT UNE VALEUR.
// -------------------------------------------------------------------  

function testerRegionGFA(langue)
{
   if (testerSelectionChoix(document.Produit.checkbox)) return true;
   if( langue == 'anglais' ) alert('Please select one or many aerodromes.');  
   else alert('Veuillez choisir un ou plusieurs aérodromes.');
   return false;
} 



// -------------------------------------------------------------------
// VALIDER LA PAGE "Regional Area Briefing"
// -------------------------------------------------------------------  
function testerRegionalBriefing( langue )
{
  // Check if user has selected a region AND any weather product
  if ( testerRegion( langue ) && valider_selection_produits(langue) )
     document.Produit.submit();
}


// -------------------------------------------------------------------
// VALIDER L'ENTREE D'UNE REGION DANS LES PAGES SUIVANTES:
// airmet-sigmet 
// -------------------------------------------------------------------  

function testerChoixRegion( langue )
{
  if ( testerRegion( langue ) )
    document.Produit.submit();
}



// -------------------------------------------------------------------
// VALIDER L'ENTREE D'UNE REGION FIR DANS LA PAGE "pirep". 
// -------------------------------------------------------------------  

function testerRegionPirep( langue )
{
  if ( testerRegionFIR( langue ) )
    document.Produit.submit();
}



// -------------------------------------------------------------------
// VALIDER L'ENTREE D'UN TYPE D'IMAGE SATELLITE DANS LA page "sat". 
// -------------------------------------------------------------------  

function testerSatellite( langue )
{
  if ( testerImageSat( langue ) )
    document.Produit.submit();
}


// -------------------------------------------------------------------
// VALIDER L'ENTREE D'UNE REGION ET D'UN TYPE DE RADAR DANS LA PAGE "radar". 
// -------------------------------------------------------------------  

function testerRadar( langue )
{
  if ( testerRegionRadar( langue ) && testerTypeRadar ( langue ) )
     document.Produit.submit();
}




// -------------------------------------------------------------------
// VALIDER L'ENTREE D'AU MOINS UNE REGION DANS LA PAGE "gfacnxx-metar-taf".
// -------------------------------------------------------------------  

function testerGFA( langue )
{
  if ( testerRegionGFA( langue ) )
    document.Produit.submit();
}




// -------------------------------------------------------------------
// VALIDER L'ENTREE D'UN NIVEAU DE VOL (associe a une hre de validite) 
// ET D'UNE REGION DANS LA PAGE "fd-fl180". 
// -------------------------------------------------------------------  

function testerFD_FL180( langue )
{
  if ( testerNiveauVolFD_FL180 ( langue ) && testerRegion( langue ) )
    document.Produit.submit();
}




// -------------------------------------------------------------------
// VALIDER SI LA CHAINE CONTIENT LES CARACTERES SUIVANTS SEULEMENT
// -------------------------------------------------------------------  

function verifierSiCarValides(x)
{
  var valid="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890éÉèÈêÊàÀâÂçÇôÔùÙûÛîÎïÏëË-_.,() ";

  for (var i=0; i< x.length; i++) 
  {
    if (valid.indexOf(x.charAt(i)) < 0) 
      return false;
  }

  return true;
}




// -------------------------------------------------------------------
// VALIDER LE NOM DU BRIEFING DANS LES PAGES D'EDITION 
// (rab-edit, lab-edit, rb-edit, rab-map-edit). 
// -------------------------------------------------------------------  

function ValiderNomBriefing( nom, langue )
{
  var nom_valide = "";
  var msg_car_invalide = "Le nom du dossier météo contient des caractères invalides.";
  var msg_invalid_car = "The weather data folder name contains one or more invalid characters.";
  var msg_vide = "Vous devez entrer un nom de dossier météo.";
  var msg_empty = "You must enter a data folder name.";
  
  nom_valide = enleverEspacesEnTrop( nom ); // interieur
  nom_valide = stripSpacesBeforeAfter( nom_valide );      // avant et apres
  
  if( !verifierSiCarValides( nom_valide ) )
  {
    if( langue == "francais" )
    {
      alert( msg_car_invalide );
      return false;
    }
    else
    {
      alert( msg_invalid_car );
      return false;
    }
  }   
  if (empty (nom_valide))
  {
    if( langue == "francais" )
    {
      alert( msg_vide );
      return false;
    }
    else
    {
      alert( msg_empty );
      return false;
    }
  }
  
  document.Produit.NomBrief.value = nom_valide;
  return true;
}



// -------------------------------------------------------------------
// Traduciton de terme météo
// -------------------------------------------------------------------

function traduire (langue, type)

{

var descripteur = ''

if (langue == 'francais' )
{
   if ( type == 'depart' )
   {
      descripteur='Départ'
   }
   if ( type == 'enroute' )
   {
      descripteur='Points enroute'
   }
   if ( type == 'destination' )
   {
      descripteur='Destination'
   }
}
else
{
   if ( type == 'depart' )
   {
      descripteur='Departure'
   }
   if ( type == 'enroute' )
   {
      descripteur='Enroute Points'
   }
   if ( type == 'destination' )
   {
      descripteur='Destination'
   }
}
return descripteur
}



// -------------------------------------------------------------------
// VERIFIER S'IL Y A SEULEMENT DES CARACTERES NUMERIQUES
// -------------------------------------------------------------------

function verifierCaracteresNumeriques(x)
{
  var valid="0123456789";

  for (var i=0; i< x.length; i++) 
  {
    if (valid.indexOf(x.charAt(i)) < 0) 
	  return false;
  }

  return true;
}

