<!-- Fonctions de contrôle -->
var isValidationLoaded = false;

function showMessage(message) {
  alert(message);
  gField.focus();
  gField.select();
  return false;
}

// general purpose function to see if an input value has been
// entered at all
//
function isEmpty(inputVal) {
  inputStr = inputVal.toString()
  if ((inputStr == null) || (inputStr == "") || (inputStr.length == 0)) {
    return false
  }
  return true
}

// general purpose function to see if a suspected numeric input
// is a positive integer
//
function isPosInteger(inputVal) {
  inputStr = inputVal.toString()
  for (var i = 0; i < inputStr.length; i++) {
    var oneChar = inputStr.charAt(i)
    if (oneChar < "0" || oneChar > "9") {
      return false
    }
  }
  return true
}

// general purpose function to see if a suspected numeric input
// is a positive or negative integer
//
function isInteger(inputVal) {
  inputStr = inputVal.toString()
  for (var i = 0; i < inputStr.length; i++) {
    var oneChar = inputStr.charAt(i)
    if (i == 0 && oneChar == "-") {
      continue
    }
    if (oneChar < "0" || oneChar > "9") {
      return false
    }
  }
  return true
}

// general purpose function to see if a suspected numeric input
// is a positive or negative number
// 
function isNumber(inputVal) {
  oneDecimal = false
  inputStr = inputVal.toString()
  for (var i = 0; i < inputStr.length; i++) {
    var oneChar = inputStr.charAt(i)
    if (i == 0 && oneChar == "-") {
      continue
    }
    if (oneChar == "." && !oneDecimal) {
      oneDecimal = true
      continue
    }
    if (oneChar < "0" || oneChar > "9") {
      return false
    }
  }
  return true
}

//
// isNotEmpty
//
function isNotEmpty() {
  var inputStr = gField.value.toString();
  if (inputStr != "" && inputStr.length > 0) return true;
  return showMessage("Le champ '" + gFieldName + "' doit être rempli.");
}

//
// E-Mail validation
//
function isValidEmail() {
  var email = gField.value;
  if (email == null || email == "") return true;
  var atPos = email.indexOf('@');
  if (atPos < 0) return showMessage("Adresse e-mail non valide !");
  var username = email.substring(0,atPos).toLowerCase();
  var hostname = email.substring(atPos+1,email.length).toLowerCase();
  if (!validMailString(username)) return showMessage("Adresse e-mail non valide !");
  if (!validMailString(hostname)) return showMessage("Adresse e-mail non valide !");
  if (hostname.indexOf('.') < 0) return showMessage("Adresse e-mail non valide !");
  return true; 
}

function validMailString(inputStr) {
  for (var i = 0; i < inputStr.length; i++) {
    var oneChar = inputStr.charAt(i);
    if (oneChar < "a" || oneChar > "z") {
      if (oneChar < "0" || oneChar > "9") {
        if (oneChar != ".") {
          if (oneChar != "_") {
            if (oneChar != "-") {
              return false;
            }
          }
        }
      }        
    }
  }
  return true;
}

function returnOnlyNumbers(inputVal) {
  var inputStr = inputVal.toString();
  var outputStr = '';
  for (var i = 0; i < inputStr.length; i++) {
    var oneChar = inputStr.charAt(i);
    if (oneChar >= "0" && oneChar <= "9") {
      outputStr += oneChar;
    }
  }
  return outputStr;
}

function isValidCCExpDate() {
  var ccexp = '' + returnOnlyNumbers(gField.value);
	var expmonth = 0;
	var expyear = 0;
	var realmonth = 0;
	var realyear = 0;
	if (ccexp.length<3 || ccexp.length>6) return showMessage("Veuillez remplir correctement ce champ.");
	if (ccexp.length==3) {
    expmonth=ccexp.substring(0,1);
    expyear=ccexp.substring(1,3);
	}
	if (ccexp.length==4) {
    if (ccexp.substring(0,1)=="0") {
			expmonth=ccexp.substring(1,2);
			expyear=ccexp.substring(2,4);
		} else {
			expmonth=ccexp.substring(0,2);
			expyear=ccexp.substring(2,4);
		}
  }
	if (ccexp.length==5) {
		expmonth=ccexp.substring(0,1);
		expyear=ccexp.substring(1,5);
	}
	if (ccexp.length==6) {
		expmonth=ccexp.substring(0,2);
		expyear=ccexp.substring(2,6);
	}
	// make sure month is a valid value
	if (expmonth<1 || expmonth>12) return showMessage("Format de date non valide (Mois).");
    expmonth++; expmonth--;
    expyear++; expyear--;
  // convert years to a standard 4 digit format
	if (ccexp.length==3 || ccexp.length==4) {
    if (expyear > 90) {
      expyear=expyear+1900;
    } else {
      expyear=expyear+2000;
    }
  }    
	// check the date
	timeisit=new Date();
	realmonth=timeisit.getMonth();
	realmonth++;
	realyear=timeisit.getYear();
	if (realyear<2000) realyear=realyear+1900;
  // compare expiration values with current ones
  if (expyear==realyear) {
		if (expmonth<realmonth) return showMessage("Votre carte de crédit est arrivée à expiration.");
	}
  if (expyear<realyear) return showMessage("Votre carte de crédit est arrivée à expiration.");
  // make expmonth and expyear strings again so we can make a string
  //      to pass to a cgi to process authorization
  expmonth+=""; expyear+="";
  if (expmonth.length==1) expmonth="0"+expmonth;
  ccexp=expmonth.substring(0,expmonth.length);
  ccexp+=expyear.substring(0,4);
  gField.value = ccexp;
	return true;
}

//
// blz validation
//
function isValidBLZ() {
  var inputStr = gField.value
  if (isPosInteger(inputStr)) {
    if (inputStr.length == 8) return true;
  }
  return showMessage("Veuillez saisir une valeur à 8 chiffres."); 
}

//
// date field validation
//
function isDateFormat() {
  var inputStr = gField.value
  var delim1 = inputStr.indexOf(".")
  var delim2 = inputStr.lastIndexOf(".")
  if (delim1 != -1 && delim1 == delim2) {
    // there is only one delimiter in the string
    alert("Format de saisie incorrect.\n\nVeuillez saisir les dates dans le format suivant : JJ.MM.AAAA")
    gField.focus()
    gField.select()
    return false
  }
  if (delim1 != -1) {
    // there are delimiters; extract component values
    var dd = parseInt(inputStr.substring(0,delim1),10)
    var mm = parseInt(inputStr.substring(delim1 + 1,delim2),10)
    var yyyy = parseInt(inputStr.substring(delim2 + 1,inputStr.length),10)
  } else {
    // there are no delimiters; extract component values
    var dd = parseInt(inputStr.substring(0,2),10)
    var mm = parseInt(inputStr.substring(2,4),10)
    var yyyy = parseInt(inputStr.substring(4,inputStr.length),10)
  }
  if (isNaN(mm) || isNaN(dd) || isNaN(yyyy)) {
    // there is a non-numeric character in one of the component values
    alert("Format de saisie incorrect.\n\nVeuillez saisir les dates dans le format suivant : JJ.MM.AAAA")
    gField.focus()
    gField.select()
    return false
  }
  if (mm < 1 || mm > 12) {
    // month value is not 1 thru 12
    alert("Format de date non valide (Mois).\n\nVeuillez saisir une valeur comprise entre 01 (janvier) et 12 (décembre).")
    gField.focus()
    gField.select()
    return false
  }
  if (dd < 1 || dd > 31) {
    // date value is not 1 thru 31
    alert("Format de date non valide (Jour).\n\nVeuillez saisir une valeur comprise entre 01 et 31.")
    gField.focus()
    gField.select()
    return false
  }
  // validate year, allowing for checks between year ranges
  // passed as parameters from other validation functions
  if (yyyy < 100) {
    // entered value is two digits, which we allow for 1930-2029
    if (yyyy >= 30) {
      yyyy += 1900
    } else {
      yyyy += 2000
    }
  } else {
    var today = new Date()
    // default year range (now set to (this year - 100) and (this year + 25))
    var thisYear = today.getYear()
    if (thisYear < 100) {
      thisYear += 1900
    }
    var minYear = thisYear - 100
    var maxYear = thisYear + 25
    if (yyyy < minYear || yyyy > maxYear) {
      alert("Format de date non valide (Année).\n\nVeuillez saisir une valeur comprise entre " + minYear + " et " + maxYear + ".")
      gField.focus()
      gField.select()
      return false
    }
  }
  if (!checkMonthLength(mm,dd)) {
    gField.focus()
    gField.select()
    return false
  }
  if (mm == 2) {
    if (!checkLeapMonth(mm,dd,yyyy)) {
      gField.focus()
      gField.select()
      return false
    }
  }
  gField.value = monthDayFormat(dd) + "." + monthDayFormat(mm) + "." + yyyy
  return true
}

function monthDayFormat(number) {
  var str = ""
  if (number < 10) {
    str = "0" + number.toString()
  } else {
    str = number.toString()
  }
  return str  
}

// check the entered month for too high a value
function checkMonthLength(mm,dd) {
  var months = new Array("","janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre")
  if ((mm == 4 || mm == 6 || mm == 9 || mm == 11) && dd > 30) {
    alert(months[mm] + " ne compte que 30 jours.")
    return false
  } else if (dd > 31) {
    alert(months[mm] + " compte 31 jours.")
    return false
  }
  return true
}

// check the entered February date for too high a value
function checkLeapMonth(mm,dd,yyyy) {
  if (yyyy % 4 > 0 && dd > 28) {
    alert("Le mois de février " + yyyy + " ne compte que 28 jours.")
    return false
  } else if (dd > 29) {
    alert("Le mois de février " + yyyy + " ne compte que 29 jours.")
    return false
  }
  return true
}


//
// Begin validation dispatching mechanism
//

function dispatcher(validationFunc) {
  this.doValidate = validationFunc;
}
var dispatchLookup = new Array()
dispatchLookup["isNotEmpty"] = new dispatcher(isNotEmpty);
dispatchLookup["isValidEmail"] = new dispatcher(isValidEmail);
dispatchLookup["isValidCCExpDate"] = new dispatcher(isValidCCExpDate);
dispatchLookup["isValidBLZ"] = new dispatcher(isValidBLZ);
dispatchLookup["isDateFormat"] = new dispatcher(isDateFormat);

// main validation function called by form event handlers
function validate(frame, form, field, method, fielddesc) {
  gFrame = frame;
  gForm = form;
  gField = eval("window." + frame.name + ".document." + form.name + "." + field.name);
  gFieldName = fielddesc;
  var args = validate.arguments;
//  for (i = 3; i < args.length; i++) {
    if (!dispatchLookup[args[3]].doValidate()) {
      return false;
    }
//  }
  return true;
}

// *****************************************************
// the following codeline must be the last one !!!
// *****************************************************
isValidationLoaded = true;
