// JavaScript Document
// DomValidation.js.
//<script>
var Page_IMValidateVer = "2";
var Page_IsValid = true;  
var Page_BlockSubmit = false;

var isNav4 = false;
var isIE4 = false;
var isNN6 = false;

if (document.getElementById) isNN6=true;
else if (document.all) isIE4=true;
else if (document.layers) isNav4=true;  

function getobj(obj) {
  if (isNN6)
    newobj = eval("document.getElementById('" + obj + "')");
  else if (isIE4)
    newobj = eval("document.all." + obj);
  else if (isNav4)
    newobj = eval("document." + obj);
  return newobj
}

function ValidatorUpdateDisplay(val) {
    if (typeof(val.display) == "string") {    
        if (val.display == "None") {
            return;
        }
        if (val.display == "Dynamic") {
            val.style.display = val.isvalid ? "none" : "inline";
            return;
        }
    }
    val.style.visibility = val.isvalid ? "hidden" : "visible";
}

function ValidatorUpdateIsValid() {
    var i;
    for (i = 0; i < Page_Validators.length; i++) {
        if (!getobj(Page_Validators[i]).isvalid) {
            Page_IsValid = false;
            return;
        }
   }
   Page_IsValid = true;
}

function ValidatorHookupControl(control, val) {
  if (control != null) {
    if (typeof(control.Validators) == "undefined") {
        control.Validators = new Array;
        var ev = control.onchange;
        if (typeof(ev) == "undefined") {
          var func = new Function("ValidatorOnChange('" + control.id + "');");
          control.onchange = func;
        }
    }
    control.Validators[control.Validators.length] = val;
  }
}
function ValidatorGetValue(id, attr) {
    var control;
    if (attr==null)
      control = getobj(id.getAttribute("controltovalidate"));
    else
      control = getobj(id.getAttribute(attr));
    if (control!=null) {
    if (typeof(control.value) == "string") {
      var t = control.value;
      var m = id.getAttribute("modify");
      if (m!=null) {
        var f = m.split(",");
        for (i=0; i < f.length; i++) {
          if (f[i]=="upper")
            t=t.toUpperCase();
          if (f[i]=="lower")
            t=t.toLowerCase();
        }
        control.value=t;
      }
      return t;
    }
    if (typeof(control.tagName) == "undefined" && typeof(control.length) == "number") {
        var j;
        for (j=0; j < control.length; j++) {
            var inner = control[j];
            if (typeof(inner.value) == "string" && (inner.type != "radio" || inner.status == true)) {
                return inner.value;
            }
        }
    }
    }
    return "";
}

function Page_ClientValidate() {
    var i;
    if (typeof(Page_Validators)=="undefined")
      return true;
    for (i = 0; i < Page_Validators.length; i++) {
        ValidatorValidate(getobj(Page_Validators[i]));
    }
    ValidatorUpdateIsValid();    
    ValidationSummaryOnSubmit();
    Page_BlockSubmit = !Page_IsValid;
    return Page_IsValid;
}

function ValidatorCommonOnSubmit() {
    var returnValue =  !Page_BlockSubmit;
    Page_BlockSubmit = false;    
    return returnValue;
}

function ValidatorOnChange(controlID) {
    var cont = getobj(controlID);
    var vals = cont.Validators;
    var i;
    for (i = 0; i < vals.length; i++) {
        ValidatorValidate(vals[i]);
    }
    ValidatorUpdateIsValid();    
}

function ValidatorValidate(val) {    
    val.isvalid = true;
    if (typeof(val.evalfunc) == "function") {
        val.isvalid = val.evalfunc(val); 
    }
    ValidatorUpdateDisplay(val);
}

function ValidatorOnLoad() {
    if (typeof(Page_Validators) == "undefined")
        return;

    var i, val;
    for (i = 0; i < Page_Validators.length; i++) {
        val = getobj(Page_Validators[i]);
        val.erreur="";
        var evalFunction = val.getAttribute("evaluationfunction");
        if (typeof(evalFunction) == "string") {
            eval("val.evalfunc = " + evalFunction + ";");
        }
        var isValidAttribute = val.getAttribute("isvalid");
        if (typeof(isValidAttribute) == "string") {
            if (isValidAttribute == "False") {
                val.isvalid = false;                                
                Page_IsValid = false;
            } 
            else {
                val.isvalid = true;
            }
        } else {
            val.isvalid = true;
        }
        var controlToValidate = val.getAttribute("controltovalidate");
        if (typeof(controlToValidate) == "string") {
          if (val.getAttribute("disabledonchange")!="true") {
            ValidatorHookupControl(getobj(controlToValidate), val);
            var controlHookup = val.getAttribute("controlhookup");
            if (typeof(controlHookup) == "string") {
              ValidatorHookupControl(getobj(controlHookup), val);
            }
          }
        }        
    }
    Page_ValidationActive = true;
}

function ValidatorConvert(op, dataType, val) {
    function GetFullYear(year) {
        return (year + parseInt("2000")) - ((year < val.getAttribute("cutoffyear")) ? 0 : 100);
    }
    var num, cleanInput, m, exp;
    if (dataType == "Integer") {
        exp = /^\s*[-\+]?\d+\s*$/;
        if (op.match(exp) == null) 
            return null;
        num = parseInt(op, 10);
        return (isNaN(num) ? null : num);
    } else if(dataType == "Double") {
        exp = new RegExp("^\\s*([-\\+])?(\\d+)?(\\" + val.getAttribute("decimalchar") + "(\\d+))?\\s*$");
        m = op.match(exp);
        if (m == null)
            return null;
        cleanInput = m[1] + (m[2].length>0 ? m[2] : "0") + "." + m[4];
        num = parseFloat(cleanInput);
        return (isNaN(num) ? null : num);            
    } 
    else if (dataType == "Currency") {
        exp = new RegExp("^\\s*([-\\+])?(((\\d+)\\" + val.getAttribute("groupchar") + ")*)(\\d+)"
                        + ((val.getAttribute("digits") > 0) ? "(\\" + val.getAttribute("decimalchar") + "(\\d{1," + val.getAttribute("digits") + "}))?" : "")
                        + "\\s*$");
        m = op.match(exp);
        if (m == null)
            return null;
        var intermed = m[2] + m[5] ;
        cleanInput = (m[1]!=undefined?m[1]:"") + intermed.replace(new RegExp("(\\" + val.getAttribute("groupchar") + ")", "g"), "") + ((val.getAttribute("digits") > 0) ? "." + m[7] : 0);
        num = parseFloat(cleanInput);
        return (isNaN(num) ? null : num);            
    }
    else if (dataType == "Date") {
        var yearFirstExp = new RegExp("^\\s*((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})\\s*$");
        m = op.match(yearFirstExp);
        var day, month, year;
        if (m != null && (m[2].length == 4 || val.getAttribute("dateorder") == "ymd")) {
            day = m[6];
            month = m[5];
            year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10))
        }
        else {
            if (val.getAttribute("dateorder") == "ymd"){
                return null;		
            }						
            var yearLastExp = new RegExp("^\\s*(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))\\s*$");
            m = op.match(yearLastExp);
            if (m == null) {
                return null;
            }
            if (val.getAttribute("dateorder") == "mdy") {
                day = m[3];
                month = m[1];
            }
            else {
                day = m[1];
                month = m[3];
            }
            year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10))
        }
        month -= 1;
        var date = new Date(year, month, day);
        return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
    }
    else {
        return op.toString();
    }
}

function ValidatorCompare(operand1, operand2, operator, val) {
    var dataType = val.getAttribute("type");
    var op1, op2;
    if ((op1 = ValidatorConvert(operand1, dataType, val)) == null)
        return false;    
    if (operator == "DataTypeCheck")
        return true;
    if ((op2 = ValidatorConvert(operand2, dataType, val)) == null)
        return true;
    switch (operator) {
        case "NotEqual":
            return (op1 != op2);
        case "GreaterThan":
            return (op1 > op2);
        case "GreaterThanEqual":
            return (op1 >= op2);
        case "LessThan":
            return (op1 < op2);
        case "LessThanEqual":
            return (op1 <= op2);
        default:
            return (op1 == op2);            
    }
}

function CompareValidatorEvaluateIsValid(val) {
    var sValue = ValidatorGetValue(val);
    if (ValidatorTrim(sValue).length == 0)
        return true;
    var compareTo = "";
    if (null == getobj(val.getAttribute("controltocompare"))) {
        if (typeof(val.getAttribute("valuetocompare")) == "string") {
            compareTo = val.getAttribute("valuetocompare");
        }
    }
    else {
        compareTo = ValidatorGetValue(val,"controltocompare");
    }
    return ValidatorCompare(sValue, compareTo, val.getAttribute("operator"), val);
}

function RegularExpressionValidatorEvaluateIsValid(val) {
    var value = ValidatorGetValue(val);
    if (ValidatorTrim(value).length == 0)
        return true;
    var rx = new RegExp(val.getAttribute("validationexpression"));
    var matches = rx.exec(value);
    return (matches != null && value == matches[0]);
}

function ValidatorTrim(s) {
    var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    return (m == null) ? "" : m[1];
}

function RequiredFieldValidatorEvaluateIsValid(val) {
    if (getobj(val.getAttribute("controltovalidate"))!=null)
      return (ValidatorTrim(ValidatorGetValue(val)) != ValidatorTrim(val.getAttribute("initialvalue")));
    else
      return true;
}

function LengthValidatorEvaluateIsValid(val) {
	var lengthmin = val.getAttribute("lengthmin");
	var lengthmax = val.getAttribute("lengthmax");
	var sValue = ValidatorGetValue(val);
        if (ValidatorTrim(sValue).length == 0)
          return true;
        return (sValue.length >= lengthmin && sValue.length <= lengthmax);
}

function DateValidatorEvaluateIsValid(val) {
	var format = val.getAttribute("datetimeformat").toUpperCase();
    formats = format.split("|");
	  formats2 = formats[1].split(formats[0]);
    var sDate = ValidatorGetValue(val);
    if (ValidatorTrim(sDate).length == 0)
        return true;
    var iDay, iMonth, iYear;
    var arrValues;
    var today = new Date();
    arrValues = sDate.split(formats[0]);
	for (i=0;i<3;i++) {
      if (formats2[i].charAt(0) == 'Y')
        iYear = arrValues[i]
	  else if (formats2[i].charAt(0) == 'M')
        iMonth = arrValues[i]
	  else if (formats2[i].charAt(0) == 'D')
        iDay = arrValues[i];
	}
    if ((iMonth == null) || (iYear == null)) return false;
    if ((iDay > 31) || (iMonth > 12) || 
        (iYear < 1900 || iYear > 9999)) 
      return false;
    var dummyDate = new Date(iYear, iMonth - 1, iDay);
    if ((dummyDate.getDate() != Math.round(iDay)) || 
      (dummyDate.getMonth() != Math.round(iMonth - 1)) || 
      (dummyDate.getFullYear() != Math.round(iYear))) 
         return false;
	return true;
}

function TimeValidatorEvaluateIsValid(val) {
	var format = val.getAttribute("datetimeformat").toUpperCase();
    formats = format.split("|");
	  formats2 = formats[1].split(formats[0]);
    var sTime = ValidatorGetValue(val);
    if (ValidatorTrim(sTime).length == 0)
        return true;
    var iHours, iMinutes, iSeconds;
    var arrValues;
    var today = new Date();
    arrValues = sTime.split(formats[0]);
	for (i=0;i<formats2.length;i++) {
      if (formats2[i].charAt(0) == 'H')
        iHours = arrValues[i]
	  else if (formats2[i].charAt(0) == 'M')
        iMinutes = arrValues[i]
	  else if (formats2[i].charAt(0) == 'S')
        iSeconds = arrValues[i];
	}
    if ((iHours == null) || (iMinutes == null)) return false;
    if ((iHours > 23) || (iMinutes > 59) || 
        (iSeconds > 59)) {
      return false;
    }
    if (iSeconds==null) iSeconds=0;
    var dummyDate = new Date(2000,1,1,iHours, iMinutes, iSeconds, 0);
    if ((dummyDate.getHours() != Math.round(iHours)) || 
      (dummyDate.getMinutes() != Math.round(iMinutes)) || 
      (dummyDate.getSeconds() != Math.round(iSeconds))) {
         return false;
      }
	return true;
}

function UploadTextBoxValidatorEvaluateIsValid(val) {
  var sUTB = val.getAttribute("controltovalidate");
  if (document.forms[0][sUTB+'Statut'] != null)
    if (document.forms[0][sUTB+'Statut'].value == 1)
      return true;
    else if (document.forms[0][sUTB+'Statut'].value == 2)
      if (getobj(sUTB+'__ctl11') != null)
      	if (getobj(sUTB+'__ctl11').value != "")
	  return true;
  return false;  
}

function CheckBoxListValidatorEvaluateIsValid(val) {
	  var sCBList = val.getAttribute("controltovalidate");
	  var i = 0;
	  while ( getobj(sCBList+'_'+i) != null ) {
	  		if (getobj(sCBList+'_'+i).checked){
				return true
			}
	  		i++;
	  }
	  return false;  
}

function CheckBoxValidatorEvaluateIsValid(val) {
	  var sCB = getobj(val.getAttribute("controltovalidate"));
	  if (sCB.checked){
	     return true
	  }
	  return false;  
}

function RadioButtonListValidatorEvaluateIsValid(val) {
	  var sRBList = val.getAttribute("controltovalidate");
	  var i = 0;
	  while ( getobj(sRBList+'_'+i) != null ) {
	  		if (getobj(sRBList+'_'+i).checked){
				return true
			}
	  		i++;
	  }
	  return false;  
}

function DropDownListValidatorEvaluateIsValid(val) {
	var f = getobj(val.getAttribute("controltovalidate"));
	return f.selectedIndex > 0;
}
function CreditCardValidatorEvaluateIsValid(val) {
	var sValue = ValidatorGetValue(val);
        if (ValidatorTrim(sValue).length == 0)
          return true;
        var control;
        control = getobj(val.getAttribute("controlcardtype"));
        var sType = control.options[control.selectedIndex].text;
        var t = checkCreditCard(sValue,sType)
        if (t != -1) {
          val.erreur=ccErrors[t];
          return false;
        } else
          return true;
}
function NumberValidatorEvaluateIsValid(val) {
	var sValue = ValidatorGetValue(val);
        if (ValidatorTrim(sValue).length == 0)
          return true;
        return ValidatorCompare(sValue, "", "DataTypeCheck", val) 
          && ValidatorCompare(sValue, val.getAttribute("minvalue"), "GreaterThanEqual", val) 
          && ValidatorCompare(sValue, val.getAttribute("maxvalue"), "LessThanEqual", val);
}

function Liste_Selectionner(val) {
  var f = getobj(val.getAttribute("controltovalidate"));
  for (i=0; i<f.length; i++)
    f.options[i].selected = true;
	return true;
}

function ValidationSummaryOnSubmit() {
    if (typeof(Page_ValidationSummaries) == "undefined") 
        return;
    var summary, sums, s;
    for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
        summary = getobj(Page_ValidationSummaries[sums]);
        summary.style.display = "none";
        if (!Page_IsValid) {
            if (summary.getAttribute("showsummary") != "False") {
                summary.style.display = "";
                if (typeof(summary.getAttribute("displaymode")) != "string") {
                    summary.displaymode = "BulletList";
                }
                switch (summary.getAttribute("displaymode")) {
                    case "List":
                        headerSep = "<br>";
                        first = "";
                        pre = "";
                        post = "<br>";
                        fin = "";
                        break;
                    case "BulletList":
                    default: 
                        headerSep = "";
                        first = "<ul>";
                        pre = "<li>";
                        post = "</li>";
                        fin = "</ul>";
                        break;
                    case "SingleParagraph":
                        headerSep = " ";
                        first = "";
                        pre = "";
                        post = " ";
                        fin = "<br>";
                        break;
                }
                s = "";
                if (typeof(summary.getAttribute("headertext")) == "string") {
                    s += summary.getAttribute("headertext") + headerSep;
                }
                s += first;
                for (i=0; i<Page_Validators.length; i++) {
                    if (!getobj(Page_Validators[i]).isvalid && typeof(getobj(Page_Validators[i]).getAttribute("errormessage")) == "string") {
                        s += pre + getobj(Page_Validators[i]).getAttribute("errormessage") + getobj(Page_Validators[i]).erreur + post;
                    }
                }   
                s += fin;
                summary.innerHTML = s; 
                window.scrollTo(0,0);
            }
            if (summary.getAttribute("showmessagebox") == "True") {
                s = "";
                if (typeof(summary.getAttribute("headertext")) == "string") {
                    s += summary.getAttribute("headertext") + "\n";
                }
                for (i=0; i<Page_Validators.length; i++) {
                    if (!getobj(Page_Validators[i]).isvalid && typeof(getobj(Page_Validators[i]).getAttribute("errormessage")) == "string") {
                        switch (summary.getAttribute("displaymode")) {
                            case "List":
                                s += getobj(Page_Validators[i]).getAttribute("errormessage") + getobj(Page_Validators[i]).erreur + "\n";
                                break;
                            case "BulletList":
                            default: 
                                s += "  - " + getobj(Page_Validators[i]).getAttribute("errormessage") + getobj(Page_Validators[i]).erreur + "\n";
                                break;
                            case "SingleParagraph":
                                s += getobj(Page_Validators[i]).getAttribute("errormessage") + getobj(Page_Validators[i]).erreur + " ";
                                break;
                        }
                    }
                }
                alert(s.replace("<BR>","\n"));
            }
        }
    }
}

/*============================================================================*/

/*

This routine checks the credit card number. The following checks are made:

1. A number has been provided
2. The number is a right length for the card
3. The number has an appropriate prefix for the card
4. The number has a valid modulus 10 number check digit if required

If the validation fails an error is reported.

The structure of credit card formats was gleaned from
    http://www.blackmarket-press.net/info/plastic/check_digit.htm 
where the details of other cards may also be found.

Parameters:
            cardnumber           number on the card
            cardname             name of card as defined in the card list below

Author:     John Gardner
Date:       1st November 2003

*/

/*
   If a credit card number is invalid, an error reason is loaded into the 
   global ccErrorNo variable. This can be be used to index into the global error  
   string array to report the reason to the user if required:
   
   e.g. if (!checkCreditCard (number, name) alert (ccErrors(ccErrorNo);
*/

function checkCreditCard (cardnumber, cardname) {

     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     return 0; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     return -1; 
  }
  
  // Check that the number is numeric, although we do permit a space to occur  
  // every four digits. 
  var cardNo = cardnumber
  var cardexp = /^([0-9]{4})\s?([0-9]{4})\s?([0-9]{4})\s?([0-9]{1,4})$/;
  if (!cardexp.exec(cardNo))  {
     return 1; 
  }
    
  // Now remove any spaces from the credit card number
  cardexp.exec(cardNo);
  cardNo = RegExp.$1 + RegExp.$2 + RegExp.$3 + RegExp.$4;
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     return 2; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     return 0; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) {
     return 3; 
  };   
  
  // The credit card is in the required format.
  return -1;
}

