
var Page_ValidationVer = "2.4.4.1";
var Page_IsValid = true;  
var Page_BlockSubmit = false;

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;
}

function ValidatorOnSubmit() {
	if (Page_ValidationActive) {
		return ValidatorCommonOnSubmit();
	}
}

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;
        }
    }
    if ((navigator.userAgent.indexOf("Mac") > -1) &&
        (navigator.userAgent.indexOf("MSIE") > -1)) {
        val.style.display = "inline";
    }
    val.style.visibility = val.isvalid ? "hidden" : "visible";
}

function ValidatorUpdateIsValid() {
	var i;
	for (i = 0; i < Page_Validators.length; i++) {
		if (!Page_Validators[i].isvalid) {
			Page_IsValid = false;
			Page_BlockSubmit = true;
			return;
		}
   }
   Page_IsValid = true;
}

function ValidatorHookupControl(control, val) {
    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;
            if (control.type == "radio") {
                eventType = "onclick";
            } 
            else 
            {
                eventType = "onchange";
                if (typeof(val.focusOnError) == "string" && val.focusOnError == "t") {
                    ValidatorHookupEvent(control, "onblur", "ValidatedControlOnBlur(event); ");
                }
            }
            ValidatorHookupEvent(control, eventType, "ValidatorOnChange(event); ");
            if (control.type == "text" || control.type == "password" || control.type == "file") {
                ValidatorHookupEvent(control, "onkeypress", "if (!ValidatedTextBoxOnKeyPress(event)) return false; ");
            }
        }
        control.Validators[control.Validators.length] = val;
    }
}

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 {
        func = new Function("event", functionPrefix + " " + ev);
    }
    eval("control." + eventType + " = func;");
}

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;
}

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;
    }
}

function ValidatorGetValue(ctrl) {
	if (ctrl == null || typeof(ctrl) == "undefined") return null;
	if (typeof(ctrl) == "string") ctrl = document.getElementById(ctrl);
	if (typeof(ctrl.value) == "string") return ctrl.value;

	if (typeof(ctrl.tagName) == "undefined" && typeof(ctrl.length) == "number") {
		var j;
		for (j=0; j < ctrl.length; j++) {
			var inner = ctrl[j];
			if (typeof(inner.value) == "string" && (inner.type != "radio" || inner.status == true)) {
				return inner.value;
			}
		}
	}
}

function Page_ClientValidate() {
	if (typeof(Page_Validators) == "undefined") {
		return true;
	}
	var i,ctrl;
	var focused = false;
	
	for (i = 0; i < Page_Validators.length; i++) {
		ValidatorValidate(Page_Validators[i]);
		if (!Page_Validators[i].isvalid) {
			if (!focused) {
				var ctrl = Page_Validators[i].controltovalidate;
				if (typeof(ctrl) != "undefined") {
					if (typeof(ctrl) == "string") {
						ctrl = document.getElementById(ctrl);
					}
					ctrl.focus();
					focused = true;
				}
			}
		}
	}
	
	ValidatorUpdateIsValid();   
	ValidationSummaryOnSubmit();
	Page_BlockSubmit = !Page_IsValid;
	
	return Page_IsValid;
}

function ValidatorCommonOnSubmit() {
    var result = !Page_BlockSubmit;
    if ((typeof(window.event) != "undefined") && (window.event != null)) {
        window.event.returnValue = result;
    }
    Page_BlockSubmit = false;
    return result;
}

function ValidatorOnChange(event) {
    if (!event) {
        event = window.event;
    }
    Page_InvalidControlToBeFocused = null;
    var targetedControl;
    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);
    }
    ValidatorUpdateIsValid();
}

function ValidatorValidate(val) {  
	val.isvalid = true;
	if (val.enabled != false) {
		if (typeof(val.evaluationfunction) == "function") {
			val.isvalid = val.evaluationfunction(val); 
		}
	}
	ValidatorUpdateDisplay(val);
}

function ValidatorOnLoad() {
	if (typeof(Page_Validators) == "undefined") {
		return;
	}
	InitializeValidators(Page_Validators);
	Page_ValidationActive = true;
}

function InitializeValidators(validators) {
	if (typeof(validators) == "undefined") {
		return;
	}
	for (var i=0; i<validators.length; i++) {
		var ctrl = validators[i];
		if (typeof(ctrl.getAttribute("evaluationfunction")) == "string") {
			eval("ctrl.evaluationfunction = " + ctrl.getAttribute("evaluationfunction") + ";");
		}
		if (typeof(ctrl.getAttribute("isvalid")) == "string") {
			if (ctrl.getAttribute("isvalid") == "False") {
				ctrl.isvalid = false;								
				Page_IsValid = false;
			} 
			else {
				ctrl.isvalid = true;
			}
		} 
		else {
			ctrl.isvalid = true;
		}
		if (typeof(ctrl.getAttribute("controltovalidate")) == "string") {
			ctrl.controltovalidate = document.getElementById(ctrl.getAttribute("controltovalidate"));
			ValidatorHookupControl(ctrl.controltovalidate, ctrl);
		}
		if (typeof(ctrl.getAttribute("controltocompare")) == "string") {
			ctrl.controltocompare = document.getElementById(ctrl.getAttribute("controltocompare"));
		}
		if (typeof(ctrl.getAttribute("controlhookup")) == "string") {
			ctrl.controlhookup = document.getElementById(ctrl.getAttribute("controlhookup"));
			ValidatorHookupControl(ctrl.controlhookup, ctrl);
		}
		if (typeof(ctrl.display) != "string" && typeof(ctrl.getAttribute("display")) == "string") {
			ctrl.display = ctrl.getAttribute("display");
		}
		if (typeof(ctrl.getAttribute("enabled")) == "string") {
			ctrl.enabled = (ctrl.getAttribute("enabled") != "False");
		}
		if (typeof(ctrl.getAttribute("errormessage")) == "string" && typeof(ctrl.errormessage) == "undefined") {
			ctrl.errormessage = ctrl.getAttribute("errormessage");
		}
		if (typeof(ctrl.getAttribute("initialvalue")) == "string") {
			ctrl.initialvalue = ctrl.getAttribute("initialvalue");
		}
		if (typeof(ctrl.getAttribute("clientvalidationfunction")) == "string") {
			ctrl.clientvalidationfunction = ctrl.getAttribute("clientvalidationfunction");
		}
	}
}

function ValidatorTrim(s) {
	return s.replace(/^\s+|\s+$/g, "");
}

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; //DataTypeCheck means we are only making sure that operand1 is of type, no need to check operand2
	if ((op2 = ValidatorConvert(operand2, dataType, val)) == null) return true;
	if (op2 == "") 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 ValidatorConvert(op, dataType, val) {
	function GetFullYear(year) {
		return (year + parseInt(val.century)) - ((year < val.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 = /^\s*([-\+])?(\d+)?(\.(\d+))?\s*$/;
				
		if (op.match(exp) == null) return null;
		num = parseFloat(op);
		return (isNaN(num) ? null : num);
	}
	else if (dataType == "Currency") {
		exp = new RegExp("^\\s*([-\\+])?(((\\d+)\\" + val.groupchar + ")*)(\\d+)"
						+ ((val.digits > 0) ? "(\\" + val.decimalchar + "(\\d{1," + val.digits + "}))?" : "")
						+ "\\s*$");
		m = op.match(exp);
		if (m == null)
			return null;
		var intermed = m[2] + m[5] ;
		cleanInput = m[1] + intermed.replace(new RegExp("(\\" + val.groupchar + ")", "g"), "") + ((val.digits > 0) ? "." + m[7] : 0);
		num = parseFloat(cleanInput);
		return (isNaN(num) ? null : num);			
	}
	else if (dataType == "Date") {
		var date = new Date(op);
		if (isNaN(date)) return null;
		if (typeof(date) == "object") return date.valueOf();
		
		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;
		date = new Date(parseInt(year), parseInt(month), parseInt(day));
		return (typeof(date) == "object" && year == date.getFullYear() && month == date.getMonth() && day == date.getDate()) ? date.valueOf() : null;
	}
	else {
		return op.toString();
	}
}

function ValidationSummaryOnSubmit() {
    if (typeof(Page_ValidationSummaries) == "undefined")
        return;
    var summary, sums, s;
    for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
        summary = Page_ValidationSummaries[sums];
        summary.style.display = "none";
        if (!Page_IsValid) {
            var i;
            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>";
                        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.getAttribute("headertext")) == "string") {
                    s += summary.getAttribute("headertext") + headerSep;
                }
                s += first;
                for (i=0; i<Page_Validators.length; i++) {
                    if (!Page_Validators[i].isvalid && typeof(Page_Validators[i].getAttribute("errormessage")) == "string") {
                        s += pre + Page_Validators[i].getAttribute("errormessage") + post;
                    }
                }
                s += end;
                summary.innerHTML = s;
                window.scrollTo(0,0);
            }
            if (summary.getAttribute("showmessagebox") == "True") {
                s = "";
                if (typeof(summary.getAttribute("headertext")) == "string") {
                    s += summary.getAttribute("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.getAttribute("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);
            }
        }
    }
}

function CompareValidatorEvaluateIsValid(val) {
    var value = ValidatorGetValue(val.controltovalidate);
    if (ValidatorTrim(value).length == 0) return true;
    var compareTo = ValidatorGetValue(val.controltocompare);
    var operator = val.getAttribute("operator");
    if (operator == null) operator = "Equal";
    if (typeof(val.operator) == "string") operator = val.operator;
    return ValidatorCompare(value, compareTo, operator, val);
}

function CustomValidatorEvaluateIsValid(val) {
    var value = "";
    if (typeof(val.controltovalidate) == "string") {
        value = ValidatorGetValue(val.controltovalidate);
		if (value == "")
			return true;
    }
    var args = { Value:value, IsValid:true };
    if (typeof(val.clientvalidationfunction) == "string") {
        eval(val.clientvalidationfunction + "(val, args) ;");
    }
    return args.IsValid;
}

function RequiredFieldValidatorEvaluateIsValid(val) {
	var currVal = ValidatorGetValue(val.controltovalidate);
	var initValue = ValidatorTrim(val.initialvalue);
	return (ValidatorTrim(currVal) != initValue);
}

function RangeValidatorEvaluateIsValid(val) {
	var value;	
	var ctrl = val.getAttribute("controltovalidate");
	if (typeof(ctrl) == "string") {
		if (ctrl != "") ctrl = document.getElementById(ctrl);
		else return true;
	}
	if (typeof(ctrl) != "string") value = ValidatorGetValue(ctrl);
	if (value == "") return true;

	var minval = val.getAttribute("minimumvalue");
	var maxval = val.getAttribute("maximumvalue");
	
	var result;
	if (minval == null && maxval == null) result = true;
	else if (minval != null && maxval == null) result = parseFloat(value) >= parseFloat(minval);
	else if (minval == null && maxval != null) result = parseFloat(value) <= parseFloat(maxval);
	else result = parseFloat(value) >= parseFloat(minval) && parseFloat(value) <= parseFloat(maxval);
	return result;
}

function RegularExpressionValidatorEvaluateIsValid(val) {
	var value = ValidatorGetValue(val.controltovalidate);
	if (value == "") {
		return true;
	}
	var exp = val.getAttribute("validationexpression");
	var flags = val.getAttribute("flags");
	var rx = new RegExp(exp);
	if (flags) {
		rx = new RegExp(exp, flags);
	}
	var matches = rx.exec(value);
	return (matches != null && value == matches[0]);
}

function RequiredListValidatorEvaluateIsValid(val) {
	var ctrlID = val.getAttribute("controltovalidate");
	if (ctrlID == null) {
		return true;
	}
	
	var ctrlToValidate = typeof(ctrlID) == 'string' ? document.getElementById(ctrlID) : ctrlID;
	if (ctrlToValidate.tagName == "TABLE") {
		var elems = ctrlToValidate.getElementsByTagName("INPUT");
		for (var i=0; i<elems.length; i++) {
			if (elems[i].checked) {
				return true;
			}
		}
	}
	else if (ctrlToValidate.tagName == "SELECT") {
		var initValue = ValidatorTrim(val.initialvalue);
		return (ValidatorTrim(ctrlToValidate.value) != initValue);
	}
	return false;
}

function TextLengthValidatorEvaluateIsValid(val) {
	var value = ValidatorGetValue(val.controltovalidate);
	if (value == "") {
		return true;
	}
	var minlength = parseFloat(val.getAttribute('minimumlength'));
	var maxlength = parseFloat(val.getAttribute('maximumlength'));
	
	if (isNaN(minlength) && isNaN(maxlength)) result = true;
	else if (isNaN(minlength) && isNaN(maxlength) == false) result = value.length <= maxlength;
	else if (isNaN(minlength) == false && isNaN(maxlength)) result = value.length >= minlength;
	else result = value.length >= minlength && value.length <= maxlength;
	
	if (!result) {
		if (typeof(val.originalerrormessage) != "string") {
			val.originalerrormessage = val.errormessage;
		}
		val.errormessage = val.innerHTML = val.originalerrormessage + ". You have " + value.length + " chars";
	} 
	else {
		if (typeof(val.originalerrormessage) == "string") {
			val.errormessage = val.innerHTML = val.originalerrormessage;
			val.originalerrormessage = null;
		}
	}
	return result;
}

function DateValidatorEvaluateIsValid(val) {
	var value = ValidatorGetValue(val.controltovalidate);
	if (value == "") {
		return true;
	}
	var format = val.getAttribute('format');
	var maxlength = parseFloat(val.getAttribute('maximumlength'));
	
	if (isNaN(minlength) && isNaN(maxlength)) result = true;
	else if (isNaN(minlength) && isNaN(maxlength) == false) result = value.length <= maxlength;
	else if (isNaN(minlength) == false && isNaN(maxlength)) result = value.length >= minlength;
	else result = value.length >= minlength && value.length <= maxlength;
	
	if (!result) {
		if (typeof(val.originalerrormessage) != "string") {
			val.originalerrormessage = val.errormessage;
		}
		val.errormessage = val.innerHTML = val.originalerrormessage + ". You have " + value.length + " chars";
	} 
	else {
		if (typeof(val.originalerrormessage) == "string") {
			val.errormessage = val.innerHTML = val.originalerrormessage;
			val.originalerrormessage = null;
		}
	}
	return result;
}

function SectionValidateOnLoad(controlsToValidate) {
	if (typeof(controlsToValidate) == 'undefined') {
		return true;
	}
	InitializeValidators(controlsToValidate);
}

function SectionClientValidate(controlsToValidate) {
	for (var i=0; i<controlsToValidate.length; i++) {
		ValidatorValidate(controlsToValidate[i]);
	}
	return SectionValidatorUpdateIsValid(controlsToValidate);
}

function SectionValidatorUpdateIsValid(controlsToValidate) {
	for (var i=0; i<controlsToValidate.length; i++) {
		if (!controlsToValidate[i].isvalid) {
			return false;
		}
	}
	return true;
}