/*
 * Form validation:
 * http://www.webcheatsheet.com/javascript/form_validation.php
 */
function validateFormOnSubmit(theForm) {
var reason = "";

  reason += validateEmpty(theForm.fullname,'votre nom');
  reason += validateEmpty(theForm.company,'le nom de votre société');
  reason += validatePhone(theForm.phone);
  reason += validateEmail(theForm.email);
      
  if (reason != "") {
    alert("Certains champs doivent être corrigés :\n" + reason);
    return false;
  }

  return true;
}

function validateEmpty(fld,txt) {
    var error = "";
  
    if (fld.value.length == 0) {
        fld.style.background = '#FFEB94'; 
        error = "Veuillez saisir "+txt+".\n"
    } else {
        fld.style.background = '#ffffff';
    }
    return error;   
}

function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
} 

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
    
    if (fld.value == "") {
        fld.style.background = '#FFEB94';
        error = "Veuillez saisir une adresse email valide.\n";	// A valid email address is required.
    } else if (!emailFilter.test(tfld)) {
        fld.style.background = '#FFEB94';
        error = "Veuillez saisir une adresse email valide.\n";	// Please enter a valid email address.
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = '#FFEB94';
        error = "Veuillez saisir une adresse email valide.\n";	// The email address contains illegal characters
    } else {
        fld.style.background = '#ffffff';
    }
    return error;
}

function validatePhone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');     

   if (fld.value == "") {
        error = "Veuillez saisir un numéro de téléphone.\n";
        fld.style.background = '#FFEB94';
    } else if (isNaN(parseInt(stripped))) {
        error = "Le numéro de téléphone saisi contient des caractères invalides.\n";
        fld.style.background = '#FFEB94';
    } else {
        fld.style.background = '#ffffff';
    }
    return error;
}