/// <summary>
/// Ensemble de fonctions javascript associes aux controleur VP
/// </summary>
var Page_ValidationVer = "1";                 // Version de la class de 
var Page_IsValid = true;                      // Indique si la page est validee
var Page_BlockSubmit = false;                 // Indique si le submit doit etre bloquee
var Page_InvalidControlToBeFocused = null;    // Indique le controle invalide devant prendre le focus
var Page_Loaded = false;
var Page_TimerOnBlur;                         // Timer declanche lors de certaines validations
var Page_EventOnBlur;                         // Utilise pour les validations apres declanchement d'un timer
var Page_EventControl;                         // Utilise pour les validations arpes declanchement d'un timer
var Page_DisplayType = "block";
var Page_IsPageValidation = false;

/// <summary>
/// Met a jour l'affichage l'affichage du controleur en fonction du style declare
/// </summary>
/// <param name="control">Controle de validation a mettre a jour
function ValidatorUpdateDisplay(val) {
    var wkVal = val;
    if (typeof(wkVal.control) != "undefined")
    {
        wkVal = val.control;
    }
    if (typeof(wkVal.display) == "string") {
        if (wkVal.display == "None") {
            return;
        }
        if (wkVal.display == "Dynamic") {
            wkVal.style.display = val.isvalid ? "none" : Page_DisplayType;
            return;
        }
    }
    if ((navigator.userAgent.indexOf("Mac") > -1) &&
        (navigator.userAgent.indexOf("MSIE") > -1)) {
        wkVal.style.display = Page_DisplayType;
    }
    wkVal.style.visibility = val.isvalid ? "hidden" : "visible";
}

/// <summary>
/// Met a jour la propriete indiquant si la page est valide
/// </summary>
function ValidatorUpdateIsValid() {
    Page_IsValid = AllValidatorsValid(Page_Validators);
}

/// <summary>
/// Indique si tous les validateurs en parametre sont positifs
/// </summary>
/// <param name="validators">Ensemble des validateurs a tester</param>
function AllValidatorsValid(validators) {
    if ((typeof(validators) != "undefined") && (validators != null)) {
        var i;
        for (i = 0; i < validators.length; i++) {
            if (!validators[i].isvalid) {
                return false;
            }
        }
    }
    return true;
}

/// <summary>
/// Met a jour un controle a tester afin que le controle s'effectue 
/// apres sa mise a jour
/// </summary>
/// <param name="controlID">Identifiant du controle a tester</param>
/// <param name="val">Validateur associe au controle</param>
function ValidatorHookupControlID(controlID, val) {
    if (typeof(controlID) != "string") {
        return;
    }
    var ctrl = document.getElementById(controlID);
    if ((typeof(ctrl) != "undefined") && (ctrl != null)) {
        ValidatorHookupControl(ctrl, val);
    }
    else {
        val.isvalid = true;
        val.enabled = false;
    }
}

/// <summary>
/// Met a jour un controle a tester afin que le controle s'effectue 
/// apres sa mise a jour
/// </summary>
/// <param name="control">Controle a tester</param>
/// <param name="val">Validateur associe au controle</param>
function ValidatorHookupControl(control, val) {

    if (typeof(val.ignoreevent) == 'string')
    {
        if (val.ignoreevent == 'True') 
        {       
            return;
        }
    }
    if (typeof(control.tagName) != "string") {
        return;  
    }
    if (control.tagName != "INPUT" && control.tagName != "TEXTAREA" && control.tagName != "SELECT") {
        var i;
        for (i = 0; i < control.childNodes.length; i++) {
            ValidatorHookupControl(control.childNodes[i], val);
        }
        return;
    }
    else {
        if (typeof(control.Validators) == "undefined") {
            control.Validators = new Array;
            var eventType;
            var prefix = "ValidatorOnChange(event)";
            /*
            ticket 8944 - fpietropoli - ajout de '  || control.type == "checkbox" ' pour prendre en compte les control checkbox
            */
            if (control.type == "radio" || control.type == "checkbox") {
                eventType = "onclick";
            } else if (val.timeoutonblur == "True"){
                ValidatorHookupEvent(control, "onfocus", "CancelTimer(event); ");
                prefix = "Page_EventOnBlur = event; Page_EventControl = GetEventControl(Page_EventOnBlur);"
                prefix = prefix + "Page_TimerOnBlur = setTimeout('ValidatorOnChange(Page_EventOnBlur, Page_EventControl)',500);"
                eventType = "onblur";
            } else {
                eventType = "onchange";
                if (typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
                    ValidatorHookupEvent(control, "onblur", "ValidatedControlOnBlur(event); ");
                }
            }
            ValidatorHookupEvent(control, eventType, prefix);
            if (control.type == "text" ||
                control.type == "password" ||
                control.type == "file") {
                ValidatorHookupEvent(control, "onkeypress", 
                    "if (!ValidatedTextBoxOnKeyPress(event)) { event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation(); return false; } ");
            }
        }
        control.Validators[control.Validators.length] = val;
    }
}

/// <summary>
/// Ajoute a un evenement d'un controle le test de validation a effectuer
/// </summary>
/// <param name="control">Controle a tester</param>
/// <param name="eventType">Type d'evenhement a tester</param>
/// <param name="functionPrefix">Fonction de validation a appeler</param>
function ValidatorHookupEvent(control, eventType, functionPrefix) {
    var ev;
    eval("ev = control." + eventType + ";");
    
    if (typeof(ev) == "function") {
        ev = ev.toString();
        ev = ev.substring(ev.indexOf("{") + 1, ev.lastIndexOf("}"));
    }
    else {
        ev = "";
    }
    var func;
    
    if (navigator.appName.toLowerCase().indexOf('explorer') > -1) {
        func = new Function(functionPrefix + " " + ev);
    }
    else if ( navigator.appVersion.toLowerCase().indexOf('chrome') > -1){
        func = new Function("evt", functionPrefix + " " + ev);
    }
    else {
        func = new Function("event", functionPrefix + " " + ev);
    }
    eval("control." + eventType + " = func;");
}

/// <summary>
/// Retourne la valeur associee a un controle
/// </summary>
/// <param name="id">Identifiant du controle dont la valeur est desiree</param>
function ValidatorGetValue(id) {
    var control;
    control = document.getElementById(id);
    if (typeof(control.value) == "string") {
        return control.value;
    }
    return ValidatorGetValueRecursive(control);
}

/// <summary>
/// Retourne la valeur associee a un controle
/// </summary>
/// <param name="control">Controle dont la valeur est desiree</param>
function ValidatorGetValueRecursive(control)
{
    if (typeof(control.value) == "string" && (control.type != "radio" || control.checked == true)) {
        return control.value;
    }
    var i, val;
    for (i = 0; i<control.childNodes.length; i++) {
        val = ValidatorGetValueRecursive(control.childNodes[i]);
        if (val != "") return val;
    }
    return "";
}

/// <summary>
/// Indique si un groupe de validation invalide la page
/// </summary>
/// <param name="validationGroup">Groupe de validation a tester</param>
function Page_ClientValidate(validationGroup) {
    Page_IsPageValidation = true;
    Page_InvalidControlToBeFocused = null;
    if (typeof(Page_Validators) == "undefined") {
        return true;
    }
    var i;
    for (i = 0; i < Page_Validators.length; i++) {
        ValidatorValidate(Page_Validators[i], validationGroup, null);
    }
    ValidatorUpdateIsValid();
    ValidationSummaryOnSubmit(validationGroup);
    Page_IsPageValidation = false;
    Page_BlockSubmit = !Page_IsValid;
    return Page_IsValid;
}

/// <summary>
/// Block la validation de la page si cela doit etre effectue
/// </summary>
function ValidatorCommonOnSubmit() {
    var result = !Page_BlockSubmit;
    if ((typeof(window.event) != "undefined") && (window.event != null)) {
        window.event.returnValue = result;
    }
    Page_BlockSubmit = false;
    return result;
}

/// <summary>
/// Modifie l'etat enabled d'un validateur
/// </summary>
/// <param name="val">Validateur a mettre a jour</param>
/// <param name="enable">Indique si le validateur doit etre actif</param>
function ValidatorEnable(val, enable) {
    val.enabled = (enable != false);
    ValidatorValidate(val);
    ValidatorUpdateIsValid();
}

/// <summary>
/// Met a jour un validateur lorsque son controle valide est mis a jour
/// </summary>
/// <param name="event">Evenement declanchant la mise a jour</param>
function ValidatorOnChange(event, control) {
    if (!event) {
        event = window.event;
    }
    Page_InvalidControlToBeFocused = null;
    var targetedControl;
    if (control != null)
    {
        targetedControl = control;
    }
    else if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) {
        targetedControl = event.srcElement;
    }
    else {
        targetedControl = event.target;
    }
    var vals;
    if (typeof(targetedControl.Validators) != "undefined") {
        vals = targetedControl.Validators;
    }
    else {
        if (targetedControl.tagName.toLowerCase() == "label") {
            targetedControl = document.getElementById(targetedControl.htmlFor);
            vals = targetedControl.Validators;
        }
    }
    var i;
    for (i = 0; i < vals.length; i++) {
        ValidatorValidate(vals[i], null, event);
    }
    
    var validationGroup = "";
    if (typeof(targetedControl.validationGroup) == "string")
    {
        validationGroup = targetedControl.validationGroup;
    }
    UpdateSummary(validationGroup);
}

/// <summary>
/// Declanche la validation si la touche pressee est la touche entree
/// </summary>
/// <param name="event">Evenement declanchant la mise a jour</param>
function ValidatedTextBoxOnKeyPress(event) {
    if (event.keyCode == 13) {
        ValidatorOnChange(event);
        var vals;
        if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) {
            vals = event.srcElement.Validators;
        }
        else {
            vals = event.target.Validators;
        }
        return AllValidatorsValid(vals);
    }
    return true;
}

/// <summary>
/// Declanche la validation au sortir d'un controle
/// </summary>
/// <param name="event">Evenement declanchant la mise a jour</param>
function ValidatedControlOnBlur(event) {
    var control;
    if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) {
        control = event.srcElement;
    }
    else {
        control = event.target;
    }
    if ((typeof(control) != "undefined") && (control != null) && (Page_InvalidControlToBeFocused == control)) {
        control.focus();
        Page_InvalidControlToBeFocused = null;
    }
}

/// <summary>
/// Annule tous les timers des validateurs associes a un controle
/// </summary>
/// <param name="event">Evenement declanchant la mise a jour</param>
function CancelTimer(event) {
    clearTimeout(Page_TimerOnBlur);
}


/// <summary>
/// Verifie qu'un controle est valide pour une regle de validation donnee
/// </summary>
/// <param name="val">Regle de validation a tester</param>
/// <param name="validationGroup">Groupe de validation en cours de verification</param>
/// <param name="event">Evenement ayant declanche le test</param>
function ValidatorValidate(val, validationGroup, event) {
    val.isvalid = true;
    if ((typeof(val.enabled) == "undefined" || val.enabled != false) && IsValidationGroupMatch(val, validationGroup)) {
        if (typeof(val.evaluationfunction) == "function") {
            val.isvalid = val.evaluationfunction(val);
            if (!val.isvalid && Page_InvalidControlToBeFocused == null &&
                typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
                ValidatorSetFocus(val, event);
            }
        }
    }
    ValidatorUpdateDisplay(val);
}

/// <summary>
/// Donne le focus a l'element concerne par le validateur
/// </summary>
/// <param name="val">Regle de validation concernee</param>
/// <param name="event">Evenement ayant declanche le test</param>
function ValidatorSetFocus(val, event) {
    var ctrl;
    if (typeof(val.controlhookup) == "string") {
        var eventCtrl;
        if ((typeof(event) != "undefined") && (event != null)) {
            if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) {
                eventCtrl = event.srcElement;
            }
            else {
                eventCtrl = event.target;
            }
        }
        if ((typeof(eventCtrl) != "undefined") && (eventCtrl != null) &&
            (typeof(eventCtrl.id) == "string") &&
            (eventCtrl.id == val.controlhookup)) {
            ctrl = eventCtrl;
        }
    }
    if ((typeof(ctrl) == "undefined") || (ctrl == null)) {
        ctrl = document.getElementById(val.controltovalidate);
    }
    if ((typeof(ctrl) != "undefined") && (ctrl != null) &&
        (ctrl.tagName.toLowerCase() != "table" || (typeof(event) == "undefined") || (event == null)) && 
        ((ctrl.tagName.toLowerCase() != "input") || (ctrl.type.toLowerCase() != "hidden")) &&
        (typeof(ctrl.disabled) == "undefined" || ctrl.disabled == null || ctrl.disabled == false) &&
        (typeof(ctrl.visible) == "undefined" || ctrl.visible == null || ctrl.visible != false) &&
        (IsInVisibleContainer(ctrl))) {
        if (ctrl.tagName.toLowerCase() == "table" &&
            (typeof(__nonMSDOMBrowser) == "undefined" || __nonMSDOMBrowser)) {
            var inputElements = ctrl.getElementsByTagName("input");
            var lastInputElement  = inputElements[inputElements.length -1];
            if (lastInputElement != null) {
                ctrl = lastInputElement;
            }
        }
        if (typeof(ctrl.focus) != "undefined" && ctrl.focus != null) {
            ctrl.focus();
            Page_InvalidControlToBeFocused = ctrl;
        }
    }
}

/// <summary>
/// Indique si le controle en parametre est visible
/// </summary>
/// <param name="ctrl">Controle a tester</param>
function IsInVisibleContainer(ctrl) {
    if (typeof(ctrl.style) != "undefined" &&
        ( ( typeof(ctrl.style.display) != "undefined" &&
            ctrl.style.display == "none") ||
          ( typeof(ctrl.style.visibility) != "undefined" &&
            ctrl.style.visibility == "hidden") ) ) {
        return false;
    }
    else if (typeof(ctrl.parentNode) != "undefined" &&
             ctrl.parentNode != null &&
             ctrl.parentNode != ctrl) {
        return IsInVisibleContainer(ctrl.parentNode);
    }
    return true;
}

/// <summary>
/// Indique si le controle fait partie des elements a tester 
//  pour un groupe de validation donne
/// </summary>
/// <param name="control">Controle a tester</param>
/// <param name="validationGroup">Groupe de validation a tester</param>
function IsValidationGroupMatch(control, validationGroup) {
    if ((typeof(validationGroup) == "undefined") || (validationGroup == null)) {
        return true;
    }
    var controlGroup = "";
    if (typeof(control.validationGroup) == "string") {
        controlGroup = control.validationGroup;
    }
    return (controlGroup == validationGroup);
}

/// <summary>
/// Au chargement de la page : 
///  Initialise les validateurs
///  Test la validite de la page
///  Determine si la page doit etre validee
/// </summary>
/// <param name="control">Controle a tester</param>
/// <param name="validationGroup">Groupe de validation a tester</param>
function ValidatorOnLoad() {
    if (Page_Loaded)
    {
        return;
    }
    if (typeof(Page_Validators) == "undefined")
        return;
    var i, val;
    for (i = 0; i < Page_Validators.length; i++) {
        val = Page_Validators[i];
        if (typeof(val.evaluationfunction) == "string") {
            eval("val.evaluationfunction = " + val.evaluationfunction + ";");
        }
        if (typeof(val.realcontroltovalidate) == "string") {
            val.controltovalidate = val.realcontroltovalidate;
        }
        if (typeof(val.isvalid) == "string") {
            if (val.isvalid == "False") {
                val.isvalid = false;
                Page_IsValid = false;
            }
            else {
                val.isvalid = true;
            }
        } else {
            val.isvalid = true;
        }
        if (typeof(val.enabled) == "string") {
            val.enabled = (val.enabled != "False");
        }
        if (typeof(val.controltovalidate) == "string") {
        {
            ValidatorHookupControlID(val.controltovalidate, val);
            var index1 = 0;
            var ctrl = eval("val.extendedcontrol" + index1.toString());
            while (typeof(ctrl) == "string")
            {
                ValidatorHookupControlID(ctrl, val);
                index1 = index1 + 1;
                ctrl = eval("val.extendedcontrol" + index1.toString());
            }
        }
        }
        if (typeof(val.controlhookup) == "string") {
            ValidatorHookupControlID(val.controlhookup, val);
        }
    }
    Page_ValidationActive = true;
    Page_Loaded = true;
}

/// <summary>
/// Convertit un type de donnee au format string
/// </summary>
/// <param name="op">Valeur a convertire</param>
/// <param name="dataType">Type de la donnee op</param>
/// <param name="val">Validateur ayant besoin de cette donnee</param>
function ValidatorConvert(op, dataType, val) {
    function GetFullYear(year) {
        var twoDigitCutoffYear = val.cutoffyear % 100;
        var cutoffYearCentury = val.cutoffyear - twoDigitCutoffYear;
        return ((year > twoDigitCutoffYear) ? (cutoffYearCentury - 100 + year) : (cutoffYearCentury + year));
    }
    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.decimalchar + "?(\\d*)\\s*$");
        m = op.match(exp);
        if (m == null)
            return null;
        if (m[2].length == 0 && m[3].length == 0)
            return null;
        cleanInput = (m[1] != null ? m[1] : "") + (m[2].length>0 ? m[2] : "0") + (m[3].length>0 ? "." + m[3] : "");
        num = parseFloat(cleanInput);
        return (isNaN(num) ? null : num);
    }
    else if (dataType == "Currency") {
        var hasDigits = (val.digits > 0);
        var beginGroupSize, subsequentGroupSize;
        var groupSizeNum = parseInt(val.groupsize, 10);
        if (!isNaN(groupSizeNum) && groupSizeNum > 0) {
            beginGroupSize = "{1," + groupSizeNum + "}";
            subsequentGroupSize = "{" + groupSizeNum + "}";
        }
        else {
            beginGroupSize = subsequentGroupSize = "+";
        }
        exp = new RegExp("^\\s*([-\\+])?((\\d" + beginGroupSize + "(\\" + val.groupchar + "\\d" + subsequentGroupSize + ")+)|\\d*)"
                        + (hasDigits ? "\\" + val.decimalchar + "?(\\d{0," + val.digits + "})" : "")
                        + "\\s*$");
        m = op.match(exp);
        if (m == null)
            return null;
        if (m[2].length == 0 && hasDigits && m[5].length == 0)
            return null;
        cleanInput = (m[1] != null ? m[1] : "") + m[2].replace(new RegExp("(\\" + val.groupchar + ")", "g"), "") + ((hasDigits && m[5].length > 0) ? "." + m[5] : "");
        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.dateorder == "ymd")) {
            day = m[6];
            month = m[5];
            year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10))
        }
        else {
            if (val.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.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);
        if (year < 100) {
            date.setFullYear(year);
        }
        return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
    }
    else {
        return op.toString();
    }
}

/// <summary>
/// Compare deux donnees entre elles
/// </summary>
/// <param name="operand1">Premiere donnee a comparer</param>
/// <param name="operand2">Deuxieme donnee a comparer</param>
/// <param name="operator">Test de comparaison a effectuer</param>
/// <param name="val">Validateur ayant besoin de cette donnee</param>
function ValidatorCompare(operand1, operand2, operator, val) {
    var dataType = val.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 ValidatorTrim(s) {
    var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    return (m == null) ? "" : m[1];
}

/// <summary>
/// Met a jour les resumes de validation pour un groupe donne
/// </summary>
/// <param name="validationGroup">Groupe de validation declanchant la mise a jour</param>
function ValidationSummaryOnSubmit(validationGroup) {
    
    if (typeof(Page_ValidationSummaries) == "undefined")
        return;
    
    var summary, sums, s;
    var showDetail = true;
    for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {      
        summary = Page_ValidationSummaries[sums];
        summary.style.display = "none";
        if (!Page_IsValid && IsValidationGroupMatch(summary, validationGroup)) {
            var i;
            if (summary.showsummary != "False") {
                summary.style.display = "";
                if (typeof(summary.displaymode) != "string") {
                    summary.displaymode = "BulletList";
                }

                switch (summary.displaymode) {
                    case "HeaderOnly":
                        showDetail = false;
                        headerSep = "<br>";
                        first = "";
                        pre = "";
                        post = "<br>";
                        end = "";
                        break;
                    case "List":
                        headerSep = "<br>";
                        first = "";
                        pre = "";
                        post = "<br>";
                        end = "";
                        break;
                    case "BulletList":
                    default:
                        headerSep = "";
                        first = "<ul>";
                        pre = "<li>";
                        post = "</li>";
                        end = "</ul>";
                        break;
                    case "SingleParagraph":
                        headerSep = " ";
                        first = "";
                        pre = "";
                        post = " ";
                        end = "<br>";
                        break;
                }
                s = "";

                if (typeof(summary.headertext) == "string") {
                    s += summary.headertext + headerSep;
                }
                
                s += first;
                if (showDetail)
                {
                    for (i=0; i<Page_Validators.length; i++) {
                        if (!Page_Validators[i].isvalid && typeof(Page_Validators[i].errormessage) == "string") {
                            s += pre + Page_Validators[i].errormessage + post;
                        }
                    }
                }
                s += end;

                summary.innerHTML = s;
                if (summary.autorefresh != "True")
                {
                    window.scrollTo(0,0);
                }
            }
            if (summary.showmessagebox == "True") {
                s = "";
                if (typeof(summary.headertext) == "string") {
                    s += summary.headertext + "\r\n";
                }
                var lastValIndex = Page_Validators.length - 1;
                for (i=0; i<=lastValIndex; i++) {
                    if (!Page_Validators[i].isvalid && typeof(Page_Validators[i].errormessage) == "string") {
                        switch (summary.displaymode) {
                            case "List":
                                s += Page_Validators[i].errormessage;
                                if (i < lastValIndex) {
                                    s += "\r\n";
                                }
                                break;
                            case "BulletList":
                            default:
                                s += "- " + Page_Validators[i].errormessage;
                                if (i < lastValIndex) {
                                    s += "\r\n";
                                }
                                break;
                            case "SingleParagraph":
                                s += Page_Validators[i].errormessage + " ";
                                break;
                        }
                    }
                }
                alert(s);
            }
        }
    }
}

/******************************************************************/

/// <summary>
/// Lance le rafraichissement des resumes de controles d'un groupe de validation
/// si un de ces derniers a ete determiner comme se rafraichissant automatiquement
/// </summary>
/// <param name="validationGroup">Groupe de validation a rafraichir</param>
function UpdateSummary(validationGroup)
{

    if (typeof(Page_ValidationSummaries) == "undefined")
        return;
      
    var summary, sums;
    var showDetail = true;
    for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {      
        summary = Page_ValidationSummaries[sums];
        if (summary.autorefresh == "True")
        {
            ValidatorUpdateIsValid();
            ValidationSummaryOnSubmit(validationGroup);
            return;
        }
    }    
}

/// <summary>
/// Ajoute un style css a un controle si ce dernier
/// ne le possede pas deja
/// </summary>
/// <param name="control">Controle auquel modifier le style</param>
/// <param name="style">Style a retirer</param>
function AddCssStyle(control, style)
{
    if (control.className.indexOf(style) >= 0)   
        return;
    control.className += " " + style;
}

/// <summary>
/// Retire un style css a un controle
/// </summary>
/// <param name="control">Controle auquel modifier le style</param>
/// <param name="style">Style a retirer</param>
function RemoveCssStyle(control, style)
{
    control.className = control.className.replace(style,'');
}

/// <summary>
/// Mise a jour du style des composants lies a un validateur
/// </summary>
/// <param name="val">Validateur effectuant le test</param>
/// <param name="valid">Indique si le (les) champ(s) teste(s) est (sont) valide(s)</param>
function ApplyValidationStyles(val, valid)
{
    //Mise a jour du style du label
    var labelStyle = "";
    if (typeof(Page_DefaultLabelErrorCssClass) == "string")
    {
        labelStyle = Page_DefaultLabelErrorCssClass;
    }
    if (typeof(val.labelerrorcssclass) == "string")
    {
        labelStyle = val.labelerrorcssclass;
    }
    if ((typeof(val.labelcontrol) == "string") && (labelStyle != ""))
    {
        var label = document.getElementById(val.labelcontrol);
        if (label != null)
        {
            if (!valid)
            {
                AddCssStyle(label, labelStyle);
            }
            else
            {
                RemoveCssStyle(label, labelStyle);
            }
        }
    }

    //Mise a jour du style du contole teste
    var controlStyle = "";
    if (typeof(Page_DefaultControlErrorCssClass) == "string")
    {
        controlStyle = Page_DefaultControlErrorCssClass;
    }
    if (typeof(val.controlerrorcssclass) == "string")
    {
        controlStyle = val.controlerrorcssclass;
    }    
    if (controlStyle != "")    
    {
        var ctrl = document.getElementById(val.controltovalidate);
        if (ctrl != null)
        {
        if (typeof(ctrl) != "undefined")
        {
            if (!valid)
            {
                AddCssStyle(ctrl, controlStyle);
            }
            else
            {
                RemoveCssStyle(ctrl, controlStyle);
            }
        }
        // Mise a jour des controles etendus
        var index1 = 0;
        ctrl = eval("val.extendedcontrol" + index1.toString());
        while (typeof(ctrl) == "string")
        {
            ctrl = document.getElementById(ctrl);
            if (!valid)
            {
                AddCssStyle(ctrl,controlStyle);
            }
            else
            {
                RemoveCssStyle(ctrl, controlStyle);
            }            
            index1 = index1 + 1;
            ctrl = eval("val.extendedcontrol" + index1.toString());
        }
        }
    }    
}

/// <summary>
/// Fonction utilisee par tous les validateurs
/// afin de determiner si la longueur du texte controle 
/// correspond bien aux valeurs specifiees
/// </summary>
/// <param name="val">Validateur effectuant le test</param>
function VpTextLengthEvaluateIsValid(val)
{
   
    // On test la taille minimale si ce test est requis
    if (typeof(val.minlength) == "string")
    {
        var text = ValidatorTrim(ValidatorGetValue(val.controltovalidate));
        if (text.length < val.minlength)
        {
            if (typeof(val.minlengtherrormessage) == "string")
            {
                VpSetErrorMessage(val, val.minlengtherrormessage);
                
            }
            return false;
        }
    }
    
    // On test la taille maximale si ce test est requis
    if (typeof(val.maxlength) == "string")
    {
        var text = ValidatorTrim(ValidatorGetValue(val.controltovalidate));
        if (text.length > val.maxlength)
        {
            if (typeof(val.maxlengtherrormessage) == "string")
            {
                VpSetErrorMessage(val, val.maxlengtherrormessage);
            }
            return false;
        }
    }
    
    return true;
}

/// <summary>
/// Fonction utilisee pour les RequiredFieldValidators
/// Indique si la valeur a controler est correcte
/// </summary>
/// <param name="val">Validateur effectuant le test</param>
function VpRequiredFieldValidatorEvaluateIsValid(val) {
    VpInitDefaultMessage(val);

    var initialValue = "";
    if (typeof(val.initialvalue) == "string")
    {
        initialValue = val.initialvalue;
    }
    var result = (ValidatorTrim(ValidatorGetValue(val.controltovalidate)) != ValidatorTrim(initialValue));
    
    // Si le test est valide alors on verifie la taille du champ
    if (result)
    {
        result = VpTextLengthEvaluateIsValid(val);
    }
    
    ApplyValidationStyles(val, result);
    return result;
}

/// <summary>
/// Fonction utilisee pour les EMailValidators
/// Indique si la valeur a controler est un email valide
/// </summary>
/// <param name="val">Validateur effectuant le test</param>
function VpEMailValidatorEvaluateIsValid(val) {

    VpInitDefaultMessage(val);

    var value = ValidatorGetValue(val.controltovalidate);
    var result = true;
    
    // Test du mail obligatoire
    if (!(val.mandatory == "False"))
    {
        if (value == "")
        {
            if (typeof(val.mandatoryerrormessage) == "string")
            {
                VpSetErrorMessage(val, val.mandatoryerrormessage);
            }
            result = false;
        }
    }
    
    // Test du format du mail
    if (result && (value != ""))
    {
        var rx = new RegExp(val.emailregexp);
        var matches = rx.exec(value);
        result = (matches != null && value == matches[0]);
      
        if (!result)
        {
            if (typeof(val.formaterrormessage) == "string")
            {
                VpSetErrorMessage(val, val.formaterrormessage);
            }
        }
    }

    // Si le test est valide alors on verifie la taille du champ
    if (result)
    {
        result = VpTextLengthEvaluateIsValid(val);
    }
    
    
    ApplyValidationStyles(val, result);
    return result;    
}


/// <summary>
/// Fonction utilisee pour les BlankValidators
/// Indique si la valeur a controler est correcte
/// </summary>
/// <param name="val">Validateur effectuant le test</param>
function VpBlankValidatorEvaluateIsValid(val) 
{
    VpInitDefaultMessage(val);
    var result = true;
    if (typeof(val.raiseerror) == "string")
    {
        result = (val.raiseerror.toLowerCase() == "true");
    }
    else if (typeof(val.hiddenfield) == "string")
    {
        result = ((document.getElementById(val.hiddenfield).value.toLowerCase()) == 'true');
    }
    ApplyValidationStyles(val, result);

    return result;
}

/// <summary>
/// Fonction utilisee pour les CompareValidators
/// Indique si la valeur a controler est correcte
/// </summary>
/// <param name="val">Validateur effectuant le test</param>
function CompareValidatorEvaluateIsValid(val) {
    VpInitDefaultMessage(val);
    var value = ValidatorGetValue(val.controltovalidate);
    if ((ValidatorTrim(value).length == 0) && !Page_IsPageValidation)
    {
        ApplyValidationStyles(val, true);
        return true;
    }
    var compareTo = "";
    if ((typeof(val.controltocompare) != "string") ||
        (typeof(document.getElementById(val.controltocompare)) == "undefined") ||
        (null == document.getElementById(val.controltocompare))) {
        if (typeof(val.valuetocompare) == "string") {
            compareTo = val.valuetocompare;
        }
    }
    else {
        compareTo = ValidatorGetValue(val.controltocompare);
    }
    var operator = "Equal";
    if (typeof(val.operator) == "string") {
        operator = val.operator;
    }
    var result = ValidatorCompare(value, compareTo, operator, val);
    
    ApplyValidationStyles(val, result);

    return result;    
}

/// <summary>
/// Fonction utilisee pour les RegularExpressionValidators
/// Indique si la valeur a controler est correcte
/// </summary>
/// <param name="val">Validateur effectuant le test</param>
function VpRegularExpressionValidatorEvaluateIsValid(val) {
    VpInitDefaultMessage(val);
    var value = ValidatorGetValue(val.controltovalidate);
    var result = true;
    // Si la chaine est vide alors elle est valide
    if (ValidatorTrim(value).length == 0)
    {
        if (val.mandatory == "True")
        {
            result = false;
            if (typeof(val.mandatoryerrormessage) == "string")
            {
                VpSetErrorMessage(val, val.mandatoryerrormessage);
            }
        }
        ApplyValidationStyles(val, result);
        return result;
    }

    // On traite les caracteres a ignorer
    if (typeof(val.ignorecharacters) == "string")
    {
        var reg=new RegExp(val.ignorecharacters) 
        while (value.search(reg) > -1)
        {
          value = value.replace(reg, "");
        }
    }
    
    var rx = new RegExp(val.validationexpression);
    var matches = rx.exec(value);
    result = (matches != null && value == matches[0]);

    // Si le test est valide on test les eventuelles expressions regulaires supplementaires
    var i = 0;
    while (result && (typeof(eval("val.additionalregex" + i)) == "string") ) 
    {
        rx = new RegExp(eval("val.additionalregex" + i));
        matches = rx.exec(value);
        result = (matches != null && value == matches[0]);    
        if (!result)
        {
            if (typeof(eval("val.additionalmessage" + i)) == "string")
            {
                VpSetErrorMessage(val, eval("val.additionalmessage" + i));
            }
        }
        i = i + 1;
    }

    // Si le test est valide alors on verifie la taille du champ
    if (result)
    {
        result = VpTextLengthEvaluateIsValid(val);
    }
    
    ApplyValidationStyles(val, result);
    return result;    
    
}

/// <summary>
/// Fonction utilisee pour les DropDownDateValidators
/// Indique si la valeur a controler est correcte
/// </summary>
/// <param name="val">Validateur effectuant le test</param>
function VpDropDownDateValidatorEvaluateIsValid(val) {
  
    VpInitDefaultMessage(val);
    var result = true;
    
    // recuperation des valeurs par defaut des combos
    var initialDay = "0";     // Valeur d'un jour non selectionne
    var initialMonth = "0";   // Valeur d'un mois non selectionne
    var initialYear = "0";    // Valeur d'une annee non selectionnee
    if (typeof (val.initialdayvalue) == "string")
    {
        initialDay = val.initialdayvalue;
    }
    if (typeof (val.initialmonthvalue) == "string")
    {
        initialMonth = val.initialmonthvalue;
    }
    if (typeof (val.initialyearvalue) == "string")
    {
        initialYear = val.initialyearvalue;
    }
    
    // Recuperation des valeurs des combos
    var day = ValidatorGetValue(val.controltovalidate);
    var month = ValidatorGetValue(val.extendedcontrol0);
    var year = ValidatorGetValue(val.extendedcontrol1);
       
    // On verifie que tous les champs on ete saisis
    if ((day == initialDay) || (month == initialMonth) ||(year == initialYear))
    {
        if (val.mandatory != "False")
        {
            result = false;
            VpSetErrorMessage(val, val.mandatorydateerrormessage);
        }
        else
        {
            result = true;
        }
    }    
    else
    {
        year = parseInt(year);
        month = parseInt(month) - 1;
        day = parseInt(day);
        // On verifie que la date est valide
        var testDate = new Date(year, month, day);

        if ( (testDate.getDate() != day) || (testDate.getMonth() != month) || (testDate.getFullYear() != year))
        {
            result = false;
            VpSetErrorMessage(val, val.invaliddateerrormessage);
        }
        
        // Test de la date min 
        if(result)
        {
            if (typeof(val.mindate) == "string")
            {
                var tmpDate = val.mindate.split("/");
                var dateMin = new Date(tmpDate[0], tmpDate[1] - 1, tmpDate[2]);
                if (dateMin > testDate)
                {
                    result = false;
                    VpSetErrorMessage(val, val.mindateerrormessage);
                }
            }
        }
        
        // Test de la date max 
        if(result)
        {
            if (typeof(val.maxdate) == "string")
            {
                var tmpDate2 = val.maxdate.split("/");
                var dateMax = new Date(tmpDate2[0], tmpDate2[1] - 1, tmpDate2[2]);
                if (dateMax < testDate)
                {
                    result = false;
                    VpSetErrorMessage(val, val.maxdateerrormessage);
                }
            }
        }        
        
    }
            
    ApplyValidationStyles(val, result);
    return result;    
    
}

/// <summary>
/// Fonction utilisee pour les CustomValidators
/// Indique si la valeur a controler est correcte
/// </summary>
/// <param name="val">Validateur effectuant le test</param>
function VpCustomValidatorEvaluateIsValid(val) {

    VpInitDefaultMessage(val);
    var value = "";
    if (typeof(val.controltovalidate) == "string") {
        value = ValidatorGetValue(val.controltovalidate);
    }

    var args = { Value:value, IsValid:true };
    if ((val.validateemptytext == "True") || (ValidatorTrim(value).length > 0) || (typeof(controltovalidate) == "undefined")) {

        if (typeof(val.clientvalidationfunction) == "string") {
            eval(val.clientvalidationfunction + "(val, args) ;");
        }
    }
    var result = args.IsValid;
    // Si le test est valide alors on verifie la taille du champ
    if (result)
    {
        result = VpTextLengthEvaluateIsValid(val);
    }    
    
    ApplyValidationStyles(val, result);
    return result;
}


/// <summary>
/// Fonction utilisee pour les LengthValidators
/// Indique si la valeur a controler est correcte
/// </summary>
/// <param name="val">Validateur effectuant le test</param>
function VpLengthValidatorEvaluateIsValid(val) {
    VpInitDefaultMessage(val);
    var result = VpTextLengthEvaluateIsValid(val); 
    ApplyValidationStyles(val, result);
    return result;
}

/// <summary>
/// Fonction utilisee pour les CheckBoxValidators
/// Indique si la valeur a controler est correcte
/// </summary>
/// <param name="val">Validateur effectuant le test</param>
function VpCheckBoxValidatorEvaluateIsValid(val) {
    VpInitDefaultMessage(val);
    var checkConstraint = true;
    if (val.checkstate == "False")
    {
        checkConstraint = false;
    }
    var result = (document.getElementById(val.controltovalidate).checked == checkConstraint);
    if (typeof(val.controlerrorcssclass) != "string")
    {
        val.controlerrorcssclass = "";
    }    
    ApplyValidationStyles(val, result);
    return result;
}

/// <summary>
/// Initialise la valeur par defaut des messages d'erreur
/// </summary>
/// <param name="val">Validateur effectuant le test</param>
function VpInitDefaultMessage(val)
{
    // On retablit le message d'erreur par defaut
    if (typeof(val.defaulterrormessage) == "undefined")
    {
        val.defaulterrormessage = val.errormessage;
    }
    else
    {
        val.errormessage = val.defaulterrormessage;
    }
    if ((typeof(val.hastext) == "undefined") || (val.hastext == "False"))
    {
        val.innerHTML = val.defaulterrormessage;
    }    
}


/// <summary>
/// Met a jour un validateur lorsque son controle valide est mis a jour
/// </summary>
/// <param name="event">Evenement declanchant la mise a jour</param>
function ValidatorOnChangeCtrl(control) {
    Page_InvalidControlToBeFocused = null;
    var targetedControl = control;
    var vals;
    if (typeof(targetedControl.Validators) != "undefined") {
        vals = targetedControl.Validators;
    }
    else {
        if (targetedControl.tagName.toLowerCase() == "label") {
            targetedControl = document.getElementById(targetedControl.htmlFor);
            vals = targetedControl.Validators;
        }
    }
    var i;
    for (i = 0; i < vals.length; i++) {
        ValidatorValidate(vals[i], null, event);
    }
    
    var validationGroup = "";
    if (typeof(targetedControl.validationGroup) == "string")
    {
        validationGroup = targetedControl.validationGroup;
    }
    UpdateSummary(validationGroup);
}

/// <summary>
/// S'assure que le validateur sera declanche apres modification
/// du (des) controle(s) a valider
/// </summary>
function HookupValControls(val, validate)
{
    if (typeof(val.controltovalidate) == "string") 
    {
        ValidatorHookupControlID(val.controltovalidate, val);
        var index1 = 0;
        var ctrl = eval("val.extendedcontrol" + index1.toString());
        while (typeof(ctrl) == "string")
        {
            ValidatorHookupControlID(ctrl, val);
            index1 = index1 + 1;
            ctrl = eval("val.extendedcontrol" + index1.toString());
        }
        ctrl = document.getElementById(val.controltovalidate);
        if (validate)
        {
            ValidatorOnChangeCtrl(ctrl);
        }
    }
}

/// <summary>
/// Applique le message d'erreur au validateur
/// </summary>
function VpSetErrorMessage(val, errorMessage)
{
    var wkVal = val;
    if (typeof(wkVal.control) != "undefined")
    {
        wkVal = val.control;
    }

    if (typeof(val.defaulterrormessage) == "undefined")
    {
        val.defaulterrormessage = val.errormessage;
    }
    val.errormessage = errorMessage;
    if ((typeof(val.hastext) == "undefined") || (val.hastext == "False"))
    {
        wkVal.innerHTML = val.errormessage;
    }
}

function GetEventControl(event)
{
    if ((typeof(event.srcElement) != "undefined") && (event.srcElement != null)) {
        return event.srcElement;
    }
    else {
        return event.target;
    }
}


function ValidateTextDropDown(val, args)
{
    // On retablie le message par defaut
    if (typeof(val.defaultmessage) == "string")
    {
        val.errormessage = val.defaultmessage;
    }
    
    // On cherche la combobox associee
    var cbo = document.getElementById(val.extendedcontrol0);
    
    if (cbo != null)
    {
        
        // Si la combo est inactive 
        if ((cbo.disabled) && (typeof(val.extendederrormessage) == "string"))
        {
            val.defaultmessage = val.errormessage;
            val.errormessage = val.extendederrormessage;
            val.innerHTML = val.errormessage;
            args.IsValid = false;
            return;
        }
        // Si un valeur a ete selectionnee
        else if ((cbo.value != "0") && (cbo.value != ""))
        {
            args.IsValid = true;
            return;
        }
    }

    val.innerHTML = val.errormessage;
    args.IsValid = (args.Value != "");
}

function ValidateDropDown(val, args)
{
    // On retablie le message par defaut
    if (typeof(val.defaultmessage) == "string")
    {
        val.errormessage = val.defaultmessage;
    }
    
    // On cherche la combobox associee
    var cbo = document.getElementById(val.extendedcontrol0);
    
    if (cbo != null)
    {
        
        // Si la combo est inactive 
        if ((cbo.disabled) && (typeof(val.extendederrormessage) == "string"))
        {
            val.defaultmessage = val.errormessage;
            val.errormessage = val.extendederrormessage;
            val.innerHTML = val.errormessage;
            args.IsValid = false;
            return;
        }
    }
    
    args.IsValid = true;

}
