function Page_Validate() {
    var firstControlError = null;
    var firstDivError = null;
    var errors = new Array();

    if (this.messageConf != null) {
        var divs = document.getElementsByTagName('div');
        for (var i = 0; i < divs.length; i++) {
            var divClassName = divs[i].className;
            var errorClass = this.messageConf.errorClass;
            var isErrorElement = (divClassName.length > 0 && (divClassName == errorClass || new RegExp("(^|\\s)" + errorClass + "(\\s|$)").test(divClassName)));
            if (isErrorElement) {
                divs[i].innerHTML = "";
            }
        }
    }
    for (var i = 0; i < this.Page_Validators.length; i++) {
        var val = this.Page_Validators[i];
        if (val.active == false) {
            continue;
        }
        if (typeof(val.evaluationFunction) == "string") {
            eval("val.evaluationFunction = " + val.evaluationFunction + ";");
        }
        if (typeof(val.evaluationFunction) == "function") {
            val.isValid = val.evaluationFunction(val);
            if (!val.isValid) {
                errors.push(val.errorMessage);
                if (firstControlError == null) {
                    firstControlError = ValidatorGetControl(val.controlToValidate, val.idForm);
                }
            }
            if (this.messageConf != null) {
                var control = ValidatorGetControl(val.controlToValidate, val.idForm);
                if (control.length) {
                    control = control[0];
                }
                var parentControl = control.parentNode;
                var divFather = null;
                while (true) {
                    var elClassName = parentControl.className;
                    var divFatherClass = this.messageConf.divFatherClass;
                    var isDivFather = (elClassName.length > 0 && (elClassName == divFatherClass || new RegExp("(^|\\s)" + divFatherClass + "(\\s|$)").test(elClassName)));
                    if (!isDivFather) {
                        parentControl = parentControl.parentNode;
                    } else {
                        divFather = parentControl;
                        break;
                    }
                    if (parentControl.tagName.toLowerCase() == 'body') {
                        break;
                    }
                }
                var elementError = null;
                if (divFather != null) {
                    var elementErrorId = divFather.id + '_msgerror';
                    var elementError = document.getElementById(elementErrorId);
                    if (!elementError) {
                        elementError = document.createElement('div');
                        elementError.id = elementErrorId;
                        elementError.className = this.messageConf.errorClass;
                        elementError.style.display = 'none';
                        elementError.innerHTML = "";
                        var firstChild = divFather.firstChild;
                        divFather.insertBefore(elementError, firstChild);
                    }

                    if (!val.isValid) {
                        if (!elementError.innerHTML) {
                            elementError.innerHTML = val.errorMessage;
                        } else {
                            elementError.innerHTML += '<br />' + val.errorMessage;
                        }
                        if (firstDivError == null) {
                            firstDivError = elementError;
                        }
                    }
                    if (elementError.innerHTML) {
                        elementError.style.display = "block";
                    } else {
                        elementError.style.display = "none";
                    }

                }
            }
        }
    }

    if (this.showSummary && this.summary) {
        this.summary.style.display = "none";
    }
    if (errors.length > 0) {
        if (this.showSummary && this.summary) {
            this.summary.style.display = "block";
            var s = "";
            if (this.headerText != '') {
                s = this.headerText + "<br>";
            }
            s += "<ul>";
            for (var i = 0; i < errors.length; i++) {
                s += "<li>" + errors[i] + "</li>";
            }
            s += "</ul>";
            this.summary.innerHTML = s;
            //window.scrollTo(0,0);
            var summaryFocus = document.getElementById("ValidationSummaryFocus");
            if (summaryFocus && !this.setFocusOnError) {
                summaryFocus.focus();
            }
        }

        if (this.showMessageBox) {
            var s = '';
            if (this.headerText != '') {
                s = this.headerText + "\n";
            }
            for (var i = 0; i < errors.length; i++) {
                s += "  - " + errors[i] + "\n";
            }
            alert(s);
        }

        if (this.messageConf == null && this.setFocusOnError && firstControlError != null) {
            if (typeof(firstControlError.length) != "number") {
                firstControlError.focus();
            } else {
                firstControlError[0].focus();
            }
        }
        if (this.messageConf != null && this.setFocusOnError && firstDivError != null) {
            var posY = firstDivError.offsetTop;
            window.scrollTo(0, posY - 10);
        }

        return false;
    } else {
        return true;
    }
}

function AddValidator(validator) {
    validator.idForm = this.idForm;
    this.Page_Validators.push(validator);
}

function SetActiveValidators(control, active) {
    for (var i = 0; i < this.Page_Validators.length; i++) {
        var val = this.Page_Validators[i];
        if (val.controlToValidate == control) {
            val.active = active;
        }
    }
}

function Validation(idForm, showSummary, showMessageBox, headerText, setFocusOnError, messageConf) {
    this.summary = document.getElementById('ValidationSummary');
    this.showSummary = showSummary;
    this.showMessageBox = showMessageBox;
    this.headerText = headerText;
    this.Page_Validators = new Array();
    this.Page_Validate = Page_Validate;
    this.AddValidator = AddValidator;
    this.SetActiveValidators = SetActiveValidators;
    this.idForm = idForm;
    this.setFocusOnError = setFocusOnError;
    this.messageConf = messageConf;
    if (this.messageConf != null) {
        this.showSummary = false;
        this.showMessageBox = false;
    }

    var validationName = 'Page_Validation';
    if (idForm != '')
       validationName = validationName + '_' + idForm;
    var func = new Function("return "+validationName+".Page_Validate();");
    if (idForm != '')
        document.getElementById(idForm).onsubmit = func;
    else
        document.forms[0].onsubmit = func;
    /*var eForm;
    if (idForm != '')
        eForm = document.getElementById(idForm);
    else
        eForm = document.forms[0];

    if (eForm.addEventListener)
        eForm.addEventListener('submit', func, false);
    else
        eForm.attachEvent("onsubmit", func);*/
}

function ValidatorTrim(s) {
    var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    return (m == null) ? "" : m[1];
}

function ValidatorGetControl(id, idForm) {
    var control;
    if (idForm != '') {
        eval('control = document.'+idForm+'.'+id);
    } else {
        control = document.getElementById(id);
    }
    return control;
}

function ValidatorGetValue(id, idForm) {
    var control = ValidatorGetControl(id, idForm);
    if (typeof(control.value) == "string") {
        return control.value;
    }
    if (typeof(control.tagName) == "undefined" && typeof(control.length) == "number") {
        var j;
        if (control[0].type == "radio" || control[0].type == "checkbox") {
            for (j = 0; j < control.length; j++) {
                var inner = control[j];
                if (inner.checked) {
                    return inner.value;
                }
            }
        } else {
            for (j = 0; j < control.length; j++) {
                var inner = control[j];
                if (ValidatorTrim(inner.value) == '') {
                    return '';
                }
            }
            return '1';
        }
    }
    return '';
}

function RequiredFieldValidatorIsValid(val) {
    return ValidatorTrim(ValidatorGetValue(val.controlToValidate, val.idForm)) != "";
}

function RequiredFieldValidator(controlToValidate, errorMessage) {
    this.active = true;
    this.idForm = "";
    this.evaluationFunction = 'RequiredFieldValidatorIsValid';
    this.isValid = false;
    this.controlToValidate = controlToValidate;
    this.errorMessage = errorMessage;
}

function RegularExpressionValidatorIsValid(val) {
    var value = ValidatorGetValue(val.controlToValidate, val.idForm);
    if (ValidatorTrim(value).length == 0)
        return true;
    var regExpr = new RegExp(val.regExpr);
    var matches = regExpr.exec(value);
    return (matches != null && value == matches[0]);
}

function RegularExpressionValidator(controlToValidate, errorMessage, regExpr) {
    this.active = true;
    this.idForm = "";
    this.evaluationFunction = 'RegularExpressionValidatorIsValid';
    this.isValid = false;
    this.controlToValidate = controlToValidate;
    this.errorMessage = errorMessage;
    this.regExpr = regExpr;
}

function RangeValidatorIsValid(val) {
    var value = ValidatorGetValue(val.controlToValidate, val.idForm);
    if (ValidatorTrim(value).length == 0)
        return true;
    return (ValidatorCompare(value, val.minValue, "GreaterThanEqual", val) &&
            ValidatorCompare(value, val.maxValue, "LessThanEqual", val));
}

function RangeValidator(controlToValidate, errorMessage, minValue, maxValue, dataType) {
    this.active = true;
    this.idForm = "";
    this.evaluationFunction = 'RangeValidatorIsValid';
    this.isValid = false;
    this.controlToValidate = controlToValidate;
    this.errorMessage = errorMessage;
    this.minValue = minValue;
    this.maxValue = maxValue;
    this.dataType = dataType;
}

function CompareValidator(controlToValidate, errorMessage, controlToCompare, operator, dataType) {
    this.active = true;
    this.idForm = "";
    this.evaluationFunction = 'CompareValidatorIsValid';
    this.isValid = false;
    this.controlToValidate = controlToValidate;
    this.errorMessage = errorMessage;
    this.controlToCompare = controlToCompare;
    this.operator = operator;
    this.dataType = dataType;
}

function ValidatorConvert(op, dataType, val) {
    var num;
    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 == "Date") {
        var dateExp = new RegExp("^\\s*(\\d{4}|\\d{2})([-/]|\\. ?)(\\d{1,2})\\2(\\d{4}|\\d{2})\\s*$");
        m = op.match(dateExp);
        var day, month, year;
        if (m == null) {
            return null;
        }
        day = m[1];
        month = m[3];
        year = m[4];

        month -= 1;
        year = (year < 100) ? year + 1900 : year;
        var date = new Date(year, month, day, 1);
        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.dataType;
    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 CompareValidatorIsValid(val) {
    var value = ValidatorGetValue(val.controlToValidate, val.idForm);
    if (ValidatorTrim(value).length == 0)
        return true;
    var compareTo = "";
    if (null == document.getElementById(val.controlToCompare)) {
        //if (typeof(val.valueToCompare) == "string") {
        //    compareTo = val.valueToCompare;
        //}
    }
    else {
        compareTo = ValidatorGetValue(val.controlToCompare, val.idForm);
    }
    return ValidatorCompare(value, compareTo, val.operator, val);
}

function CustomValidator(controlToValidate, errorMessage, clientValidationFunction) {
    this.active = true;
    this.idForm = "";
    this.evaluationFunction = 'CustomValidatorIsValid';
    this.isValid = false;
    this.controlToValidate = controlToValidate;
    this.errorMessage = errorMessage;
    this.clientValidationFunction = clientValidationFunction;
}

function CustomValidatorIsValid(val) {
    var value = "";
    if (val.controlToValidate != "") {
        if (typeof(val.controlToValidate) == "string") {
            value = ValidatorGetValue(val.controlToValidate, val.idForm);
            if (ValidatorTrim(value).length == 0)
                return true;
        }
    }
    var args = { Value:value, IsValid:true };
    if (val.clientValidationFunction != "") {
        if (typeof(val.clientValidationFunction) == "string") {
            eval(val.clientValidationFunction + "(val, args) ;");
        }
    }
    return args.IsValid;
}