//Fonction de vérification de formulaire. Compatible à partir de IE4, NS4


//La fonction principale est getFormErrors(unform).
//Elle reçoit en paramètre un objet formulaire
//Il faut ajouter pour chacun des champs à vérifier :
//
// - L'attribut msgError contenant le message d'erreur en cas d'echec du test
//
// - Pour les textes devant avoir une certaine longueur, ajouter les proprietés 
//   maxlength (longueur maximale du texte), minlength (l'inverse)
//   ex:    form.nomchamps.maxlength = 10;
//          form.nomchamps.minlength = 5;
//
//
// - Spécifier les champs à contrôler en ajoutant l'attribut required = true
//   ex:    form.phone.required = true;
//
// - Enfin il existe trois types de vérification :
//	. chaine au format adresse email correct : email
//	. chaine numérique : numeric
//	. confimation de mot de passe (attention s'applique sur le champs de confirmation
//	  devant impérativement suivre le champs contenant le mot de passe : confirmation 
//
//Exemple :
//form.email.pattern = 'email';
//form.email.patternError = 'The email address entered is not valid.';
//
//form.validlength.required = true;
//form.validlength.requiredError = 'The 5-10 character string field must be filled in.';

function getFormErrors(form) 
{
   var errors = new Array();
   
   // loop thru all form elements
   for (var elementIndex = 0; elementIndex < form.elements.length; elementIndex++) 
   {
      var element = form.elements[elementIndex];

      // Traitement des input type texte, textarea et password
      if (element.type == "text" || element.type == "textarea" || element.type == "password") 
      {
         element.value = trimWhitespace(element.value) //Retire les espaces au début et fin de chaine
         
         // required element
         if (element.required  && element.value == '') 
         {
            errors[errors.length] = element.msgError;
         }
         
         // maximum length
         else if (element.maxlength && isValidLength(element.value, 0, element.maxlength) == false) 
         {
            errors[errors.length] = element.msgError;
         }
         
         // minimum length
         else if (element.minlength && isValidLength(element.value, element.minlength, Number.MAX_VALUE) == false) 
         {
            errors[errors.length] = element.msgError;
         }
         
         else if (element.pattern) 
         {
            if ( (element.pattern.toLowerCase() == 'email' && isValidEmail(element.value) == false) ||
                 (element.pattern.toLowerCase() == 'numeric' && isNumeric(element.value, true) == false ) ||
                 (element.pattern.toLowerCase() == 'confirmation' && sameString(element.value, form.elements[elementIndex-1].value) == false )
               )
            {
               errors[errors.length] = element.msgError;
            }
            
            
            if (element.pattern.toLowerCase() == 'url')
            {
            	element.value = rewriteURL(element.value);
            	if ( isURL(element.value) == false )
            	{
            		errors[errors.length] = element.msgError;
            	}
            }
         }
      }

      
      // file upload
      if (element.type == "file") {
         
         // required element
         if (element.required  && element.value == '') {
            errors[errors.length] = element.msgError;
         }
      }
      
      // select
      else if (element.type == "select-one" || element.type == "select-multiple" || element.type == "select") 
      {
         // required element
         if (element.required && element.selectedIndex == -1) 
         {
            errors[errors.length] = element.msgError;
         }
         
	 // disallow empty value selection
         else if (element.disallowEmptyValue && element.options[element.selectedIndex].value == '') 
         {

            errors[errors.length] = element.msgError;
         }

      }
      
      // radio buttons
      else if (element.type == "radio") 
      {
         var radiogroup = form.elements[element.name];
         if (radiogroup.required && radiogroup.length) 
         {
            var checkedRadioButton = -1;
            for (var radioIndex = 0; radioIndex < radiogroup.length; radioIndex++) 
            {
               if (radiogroup[radioIndex].checked == true)
               {
                  checkedRadioButton = radioIndex;
                  break;
               }
            }
            
            if (checkedRadioButton == -1) 
            {
               errors[errors.length] = form.elements[element.name].msgError;
            }
         }
         
         elementIndex = elementIndex + (radiogroup.length - 1);
         radiogroup = null;

      }
   }
   
	return errors;
}


// Check that the number of characters in a string is between a max and a min
function isValidLength(string, min, max) 
{
	if (string.length < min || string.length > max) return false;
	else return true;
}


// Check that an email address has the form something@something.something
// This is a stricter standard than RFC 821 (?) which allows addresses like postmaster@localhost
function isValidEmail(adress) 
{
        var myString = adress.match(/\b(^(\S+@).+(\..{2,})$)\b/gi);
	if (!myString) 
		return false;
	else
		return  true;
}

// Check that a string contains only numbers
function isNumeric(string, ignoreWhiteSpace) 
{
	if (string.search) 
	{
		if ((ignoreWhiteSpace && string.search(/[^\d\.,\s]/) != -1) || (!ignoreWhiteSpace && string.search(/^\d+([\.,]\d+)?$/) == -1)) return false;
	}
	return true;
}


// Remove all spaces from a string
function removeSpaces(string) {
	var newString = '';
	for (var i = 0; i < string.length; i++) {
		if (string.charAt(i) != ' ') newString += string.charAt(i);
	}
	return newString;
}


// Remove leading and trailing whitespace from a string
function trimWhitespace(string) {
	var newString  = '';
	var substring  = '';
	beginningFound = false;
	
	// copy characters over to a new string
	// retain whitespace characters if they are between other characters
	for (var i = 0; i < string.length; i++) {
		
		// copy non-whitespace characters
		if (string.charAt(i) != ' ' && string.charCodeAt(i) != 9) {
			
			// if the temporary string contains some whitespace characters, copy them first
			if (substring != '') {
				newString += substring;
				substring = '';
			}
			newString += string.charAt(i);
			if (beginningFound == false) beginningFound = true;
		}
		
		// hold whitespace characters in a temporary string if they follow a non-whitespace character
		else if (beginningFound == true) substring += string.charAt(i);
	}
	return newString;
}


// Remove characters that might cause security problems from a string 
function removeBadCharacters(string) 
{
	if (string.replace) 
	{
		string.replace(/[<>\"\'%;\)\(&\+]/, '');
	}
	return string;
}


// Remove characters that might cause security problems from a string 
function rewriteURL(string) 
{
	var newString;
	if ( string.search(/^http:\/\//) == -1 )
	{
		newString = 'http://'+string;
		return newString;
	}
	else
	{
		return string;
	}
}

function isURL(urlstring) 
{
	if ( urlstring.search(/^http:\/\/\S{2}\S*\.\S{2}\S*$/) == -1 )
	{
		return false;
	}
	else
	{
		return true;
	}
}




//Vérification des mots de passe
//Fonction vérifiant que les deux chaînes de caractère passées en paramètre sont identique
function sameString(String1,String2)
{
	if (String1 == String2)
		return true;
	else
		return false;
}

//Vérifie que la date est au bon format dans la langue spécifiée
function is_date(string,format)
{
	if(format == "fr" )
	{
		if (! string.match(/\d\d-\d\d-\d\d\d\d/gi) && ! string.match(/\d\d\/\d\d\/\d\d\d\d/gi) )
			return false;
		else
			return true;
	}
}
