var Page_DomValidationVer = "2";
var Page_IsValid = true;  
var Page_BlockSubmit = false;
var Page_SrcElement = null;
var Page_OnChangeElement = null;
var g_NS6 = (!(document.all) && document.getElementById);


function ValidatorGetControlToValidate(val)
{
    var controlid = val.getAttribute("vld", 0);
    if (typeof(controlid) != "string")
        return null;
	return FindElement(controlid);
}

function ValidatorSetControlToValidate(val, controlid)
{
	if (controlid == null)
	{
		val.removeAttribute("vld", 0);
		return;
	}
	
	var control = FindElement(controlid);
	if (control)
	{
		control.valid = true;
		val.setAttribute("vld", controlid, 0);
	}
}

function ValidatorClearErrorAttributes(val)
{
	val.removeAttribute("ctl", 0);
	val.removeAttribute("alr", 0);
	val.removeAttribute("alrtag", 0);
	val.removeAttribute("msg", 0);
	val.removeAttribute("msgtag", 0);
}

function ValidatorSetErrorMessage(val, msg, msgtag)
{
	if (msg == null) val.removeAttribute("msg", 0);
	else val.setAttribute("msg", msg, 0);
	
	if (msgtag == null) val.removeAttribute("msgtag", 0);
	else val.setAttribute("msgtag", msgtag, 0);
}

function ValidatorSetErrorAlert(val, alr, alrtag)
{
	if (alr == null) val.removeAttribute("alr", 0);
	else val.setAttribute("alr", alr, 0);
	
	if (alrtag == null) val.removeAttribute("alrtag", 0);
	else val.setAttribute("alrtag", alrtag, 0);
}

function ValidatorSetErrorControl(val, controlid)
{
	if (controlid == null) {
		val.removeAttribute("ctl", 0);
		return;
	}
	
	var control = FindElement(controlid);
	if (control)
	{
		control.valid = true;
		val.setAttribute("ctl", controlid, 0);
	}
}

function ValidatorGetSubmitButton(val, idx)
{
    var btnids = val.getAttribute("btn", 0);
    if (typeof(btnids) != "string")
        return null;
    
    var list = btnids.split(",");
    if (idx > list.length - 1)
		idx = 0;
	
    return FindElement(list[idx]);
}

function ValidatorEnable(val)
{
	val.removeAttribute("dis", 0);
}

function ValidatorDisable(val)
{
	val.setAttribute("dis", "1", 0);
}

function ValidatorEnableForControl(ctlId)
{
	if (ctlId && ctlId.length > 0)
	{
		var control = FindElement(ctlId);
		if (control)
		{	
			var vals = control.Validators;
			if (vals && vals.length)
			{
				for (var i = 0; i < vals.length; i++)
					ValidatorEnable(vals[i]);
			}
			else
			{
				var fnc = control.getAttribute("fnc", 0);
				if (fnc) ValidatorEnable(control);
			}
		}
	}
}

function ValidatorDisableForControl(ctlId)
{
	if (ctlId && ctlId.length > 0)
	{
		var control = FindElement(ctlId);
		if (control)
		{	
			var vals = control.Validators;
			if (vals && vals.length > 0)
			{
				for (var i = 0; i < vals.length; i++)
					ValidatorDisable(vals[i]);
			}
			else
			{
				var fnc = control.getAttribute("fnc", 0);
				if (fnc) ValidatorDisable(control);
			}
		}
	}
}

function ValidatorSetFocus(val)
{
	var vlda = val.getAttribute("vld", 0);
	if (vlda && vlda.length > 0)
	{
		var vld = FindElement(vlda);
		if (vld && !vld.disabled)
		{
			vld.focus();
			if (vld.type == "text")
				vld.select();
		}
	}
}

function ValidatorShow(val, showit)
{
	if ((typeof(val.display) == "string") && (val.display == "Dynamic"))
		val.style.display = (showit) ? "inline" : "none"

	val.style.visibility = showit ? "visible" : "hidden";
    if (!showit)
	    val.innerHTML = "";
	
	if (showit && g_FocusOnError)
		ValidatorSetFocus(val);
	
	var controlid = val.getAttribute("ctl");
	if (controlid && controlid.length > 0)
	{
		var control = FindElement(controlid);
		if (control)
			control.style.visibility = showit ? "visible" : "hidden";
	}
}

function ValidatorEnterKeyHandler(evt, btnId)
{
	// If evt param is null, try event, otherwise use null.
	var evt  = (evt) ? evt : ((event) ? event : null);
	
	// Filter on the carriage return.
	if ((evt.which && evt.which == 13) || (evt.keyCode && ((evt.keyCode == 13) || (evt.keyCode == 3))))
	{
		var btn = FindElement(btnId);
		if (btn != null)
		{
			if (g_NS6)
			{
				Page_SrcElement = btn;
			}

			if (evt != null)
			{
				evt.cancelBubble = true;
				evt.returnValue = false;
			}
			
			if(typeof(g_BrowserName)!= "undefined" && typeof(g_BrowserMajorVersion) != "undefined")
			{
				if(g_BrowserName.toUpperCase() == "APPLEWEBKIT" && parseInt(g_BrowserMajorVersion) < 125)
				{
					eval(btn.onClick);
					return false;
				}
			}
			
			btn.click();
			return false;
		}
	}
	return true;
}

function ValidatorHookupControl(val, control, addonchange)
{
    if ((control != null) && (typeof(control.Validators) == "undefined"))
    {
        control.Validators = new Array;
        if (addonchange)
        {
			var func = new Function("ValidatorOnChange('" + control.id + "');");
			control.onchange = func;
		}
    }
    control.Validators[control.Validators.length] = val;
}

function ValidatorHookupControlById(val, controlid, addonchange)
{
	var control = FindElement(controlid);
	if (control != null)
		ValidatorHookupControl(val, control, addonchange);
}

function ValidatorGetValue(val)
{
    var control = ValidatorGetControlToValidate(val);
    if (typeof(control.value) == "string")
        return control.value;

    if ((typeof(control.tagName) == "undefined") && (typeof(control.length) == "number"))
    {
        for (var 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 ValidatorCommonOnSubmit()
{
    var returnValue = !Page_BlockSubmit;
    Page_BlockSubmit = false;    
    return returnValue;
}

function ValidatorDoPostBack(controlID)
{
	var theform = document.forms[0];
	if (theform.__EVENTTARGET && theform.__EVENTARGUMENT)
	{
		theform.__EVENTTARGET.value = controlID.split("$").join(":");
		theform.__EVENTARGUMENT.value = "";
	}
	theform.submit();
}

function ValidatorOnChange(controlID)
{
    var cont = FindElement(controlID);
    var vals = cont.Validators;
    
    if (vals && vals.length > 0)
    {
		// We need to set the srcElement to the appropriate submit button ID
		// so that the validators don't get filtered out in ValidatorValidateOne
		Page_SrcElement = ValidatorGetSubmitButton(vals[0], 0);
		Page_OnChangeElement = cont;

		ValidatorValidateFromList(vals);
		
		// Reset srcElement and update vars
		Page_SrcElement = null;
		Page_OnChangeElement = null;
	    Page_BlockSubmit = !Page_IsValid;
	}

}

function ValidatorValidateFromList(vals)
{
    Page_IsValid = true;
    for (var i = 0; i < vals.length; i++)
    {
        var val = vals[i];
	    var control = ValidatorGetControlToValidate(val);
        if (control != null)
            control.valid = true;
				
        ValidatorShow(val, false);
    }
    
    for (var i = 0; i < vals.length; i++)
    {
        ValidatorValidateOne(vals[i]);
    }
}

function ValidatorValidateOne(val)
{
    val.isvalid = true;
    
    if (typeof(val.evalfunc) == "function")
    {
		// Check if disabled prop is set
		var disable = val.getAttribute("dis", 0);
		if (disable && disable.length > 0)
			return;
				
		// Call validator func only if Page_SrcElement is one of the validator's submit buttons
		var btnids = val.getAttribute("btn", 0);
		if (typeof(btnids) == "string")
		{
			var list = btnids.split(",");
			for (var n = 0; n < list.length; n++)
			{
				if ((Page_SrcElement != null) && (Page_SrcElement.id == list[n]))
				{
					val.isvalid = val.evalfunc(val);
					break;
				}
			}
			
			ValidatorUpdateDisplay(val);
		}
    }
}

function ValidatorUpdateDisplay(val)
{
    if (typeof(val.display) == "string")
    {    
        if (val.display == "None")
            return;
    }    

	if (!val.isvalid)
	{	
        var control = ValidatorGetControlToValidate(val);
        if (control)
        {
			// If we've already decided the control's not valid, nothing else to do
            if (!control.valid) return;
            control.valid = false;
        }

		// If we're showing multiple messages, or the page is still valid, continue
        if (!g_OneInline || !g_OneAlert || Page_IsValid) 
            ValidatorShow(val, true);

		// If we're showing multiple messages, or the page is still valid, continue
        if (!g_OneInline || Page_IsValid) 
        {
		    var msg = val.getAttribute("msg", 0);
		    if (msg && msg.length > 0)
		    {
			    val.innerHTML = msg;
            }
            else
            {
		        var msgTag = val.getAttribute("msgtag", 0);
		        if (msgTag && msgTag.length > 0)
			        val.innerHTML = g_GixJSArrayElements[msgTag];
		    }
	    }

		// If we're showing multiple alerts, or the page is still valid, continue
        if (!g_OneAlert || Page_IsValid)
        {
		    var alertText = val.getAttribute("alr", 0);
		    if (alertText && alertText.length > 0)
		    {
			    alert(alertText);
		    }
		    else
		    {
			    var alertTextTag = val.getAttribute("alrtag", 0);
			    if (alertTextTag && alertTextTag.length > 0)
			    {
				    alertText = g_GixJSArrayElements[alertTextTag];
				    alert(alertText);
			    }
		    }
		}
        Page_IsValid = false;
	}
}

function ValidatorOnLoad()
{	
    if (typeof(Page_Validators) == "undefined")
        return;
	
    // Convert the validators from names to elements
    for (var i = 0; i < Page_Validators.length; i++)
        Page_Validators[i] = FindElement(Page_Validators[i]); 

    for (var i = 0; i < Page_Validators.length; i++)
    {
        var val = Page_Validators[i];
        
        // Skip validators that are not enabled
        var valEnabled = val.getAttribute("enabled", 0);
        if ((typeof(valEnabled) == "string") && (valEnabled == "False"))
		{
			continue;
        }

        var evalFunction = val.getAttribute("fnc", 0);
        if (typeof(evalFunction) == "string")
        {
            eval("val.evalfunc = " + evalFunction + ";");
        }
        
        var isValidAttribute = val.getAttribute("isvalid", 0);
        val.isvalid = true;
        if (typeof(isValidAttribute) == "string")
        {
            if (isValidAttribute == "False")
            {
                val.isvalid = false;
            }
        }

        var control = ValidatorGetControlToValidate(val);
        if (control != null)
        {
            ValidatorHookupControl(val, control, false);
        }
        
        if (!val.isvalid)
        {
			if (control.valid == null)
				control.valid = true; // This will be set to false in ValidatorUpdateDisplay
			
			ValidatorUpdateDisplay(val);
        }      
    }
    Page_ValidationActive = true;
}

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

function ValidatorRegExpFunc(val)
{	
    var value = ValidatorTrim(ValidatorGetValue(val));
    if (value == "")
        return true;
    
    // Check for the &# combination
    var expression = "&#";
    var rx = new RegExp(expression)
    var matches = rx.exec(value);
    if ((matches != null) && (expression == matches[0])) { return false; }

    expression = val.getAttribute("valexp", 0);    
    
    // get the expression from the global array if expression reference is being used
	if (expression == null || expression.length == 0)
	{
		expression = val.getAttribute("expref", 0);
		if (expression != null && expression.length > 0)
			expression = g_GixJSArrayElements[expression];
	}
	          
    rx = new RegExp(expression);
    matches = rx.exec(value); 
    return ((matches != null) && (value == matches[0]));
}

function ValidatorReqFieldFunc(val)
{
	// Check value
	var value = ValidatorTrim(ValidatorGetValue(val));
	var empty = ValidatorTrim(val.getAttribute("ini", 0));	
	if (value == empty) return false;
	
	// Check field lengths
	var min = val.getAttribute("minval", 0) - 0;
	if ((min > 0) && (value.length < min))
		return false;
	
	var max = val.getAttribute("maxval", 0) - 0;
	if ((max > 0) && (value.length > max))
		return false;
		
	return true;
}

function ValidatorTextLengthFunc(val)
{
	// Check value
	var value = ValidatorTrim(ValidatorGetValue(val));
	var empty = ValidatorTrim(val.getAttribute("ini", 0));	
	if (value == empty) return true;
	
	// Check field lengths
	var min = val.getAttribute("minval", 0) - 0;
	if ((min > 0) && (value.length < min))
		return false;
	
	var max = val.getAttribute("maxval", 0) - 0;
	if ((max > 0) && (value.length > max))
		return false;
		
	return true;
}

function ValidatorCheckboxFunc(val)
{
    var value = val.getAttribute("vlds", 0);
    if (value == "")
        return true;
    
    var list = value.split(",");
    var found = false;
    for (var i = 0; i < list.length; i++)
    {
		var control = FindElement(list[i]);
		if (control && control.checked)
		{
			found = true;
			break;
		}
    }
    return found;
}

function ValidatorReqListboxFunc(val)
{
	var valid = false;
	var control = ValidatorGetControlToValidate(val);
	if (control != null)
	{
		var unselected = val.getAttribute("ini", 0) + "";
		for (var i = 0; i < control.length; i++)
		{
			if (control.options[i].selected && (control.options[i].value != unselected))
			{
				valid = true;
				break;
			}
		}
	}
	
	return valid;
}

function ValidatorRangeFunc(val)
{	
    var value = ValidatorGetValue(val);
    if (value == "")
        return false;    
    
    var minValue = val.getAttribute("minval", 0);    
    var maxValue = val.getAttribute("maxval", 0);    

    var rx = new RegExp("^\\d+$");
    var matches = rx.exec(value);
    value = value-0; // make into integer
    return (matches != null && value >= minValue && value <= maxValue);
}

function ValidatorMatchFieldFunc(val)
{
	var matchId = val.getAttribute("match")
    if (matchId && matchId.length > 0) {
		var match = FindElement(matchId);
		if (match) {
			return (ValidatorTrim(ValidatorGetValue(val)) == ValidatorTrim(match.value));
		}
	}
	return true;
}

function ValidatorNoOpFunc(val)
{
	return true;
}

///////////////////////////

function ValidatorSwitchEnable(val, grpname)
{
	var vlds = val.getAttribute(grpname, 0);
    if (vlds == null || vlds.length <= 0) return;
	
    var ids = vlds.split(",");
    for (var i = 0; i < ids.length; i++)
    {
		ValidatorEnableForControl(ids[i]);
	}
}

function ValidatorSwitchDisable(val, grpname)
{
	var vlds = val.getAttribute(grpname, 0);
    if ((typeof(vlds) == "undefined") || (vlds == null) || vlds.length <= 0) return;
	
    var ids = vlds.split(",");
    for (var i = 0; i < ids.length; i++)
    {
		ValidatorDisableForControl(ids[i]);
	}
}

function ValidatorSwitchFunc(val)
{
	ValidatorSwitchDisable(val, "vlds0");
	ValidatorSwitchDisable(val, "vlds1");
	ValidatorSwitchDisable(val, "vlds2");

    var controlID = val.getAttribute("swisrc", 0);
	if (typeof(controlID) != "string")
		return true;
	
	var ids = controlID.split(",");
	if (ids.length <= 0)
		return true;
	
	var first = FindElement(ids[0]);
	if ((typeof(first) != "object") || (typeof(first.type) != "string"))
		return true;
		
	var group = -1;
	switch (first.type)
	{
		case "select-one":
		case "select-multiple":		group = GetSwitchGroupFromList(val, ids[0]); break;
		case "radio":				group = GetSwitchGroupFromRadios(val, ids); break;
		case "text":
		case "textarea":			group = GetSwitchGroupFromText(val, ids); break;
		case "checkbox":			group = GetSwitchGroupFromCheckBox(val, ids[0]); break;
		default:					alert("New source control type : " + first.type); break;
	}
	
	if (group >= 0)
	{
		ValidatorSwitchEnable(val, "vlds" + group);
	}
	
	return true;
}

function GetSwitchGroup(val, selValue)
{
	var val0 = val.getAttribute("val0", 0);
	if (typeof(val0) != "string")
		return (selValue.length > 0) ? 1 : 0;
	
	var vals0 = val0.split(",");
	if (vals0.length <= 0)
		return (listval.length > 0) ? 1 : 0;

	for (var i = 0; i < vals0.length; i++)
	{
		if (selValue == vals0[i])
			return 0;
	}
	
	return 1;
}

function GetSwitchGroupFromList(val, id)
{
	var list = FindElement(id);
	if (list == null)
		return -1;
	
	var listval = list.value;
	if (typeof(listval) != "string")
		return -1;
	
	return GetSwitchGroup(val, listval);
}

function GetSwitchGroupFromRadios(val, ids)
{
	for (var i = 0; i < ids.length; i++)
	{
		var radio = FindElement(ids[i]);
		if (radio == null)
			continue;
		
		if (radio.checked)
			return i;
	}
	
	return -1;
}

function GetSwitchGroupFromText(val, id)
{
	var text = FindElement(id);
	if (text == null)
		return -1;
	
	var textval = text.value;
	if (typeof(textval) != "string")
		return -1;
	
	return GetSwitchGroup(val, textval);
}

function GetSwitchGroupFromCheckBox(val, id)
{
	var checkbox = FindElement(id);
	if (checkbox == null)
		return -1;
		
	return (checkbox.checked) ? 1 : 0;
}

///////////////////////////

function ValidateFromElement(controlID)
{
	Page_SrcElement = FindElement(controlID);
	return Page_ClientValidate();
}

function Page_ClientValidate()
{
    if (typeof(Page_Validators) == "undefined")
        return true;
	
	if ((typeof(Page_SrcElement) == "undefined") || (Page_SrcElement == null))
	{
		if ((typeof(event) == "undefined") || (event == null))
			return true;
			
		Page_SrcElement = event.srcElement;
	}
	
    ValidatorValidateFromList(Page_Validators);
    Page_BlockSubmit = !Page_IsValid;
    Page_SrcElement = null;
    
    return Page_IsValid;
}
