
var m_oXmlForm = null;
var m_strActiveLookupFieldId = "";
var m_strActiveLookupButtonFieldName = "";
var m_dbMinYear = 1753; //Minimum year for MSSQL server date fields
//var m_bInsideInput = false;
var _suppressFieldValidationForKeyDown = false;

//-----------------------------------------
// UserLookup object definition STARTS

function GetUserFullName(oUser)
{
	var ReturnName = "";
	if(null != oUser)
	{
		var NamePart;
		NamePart = oUser.getAttribute("FirstName");
		if(null != NamePart && "" != NamePart)
			ReturnName = NamePart;
		NamePart = oUser.getAttribute("MiddleName");
		if(null != NamePart && "" != NamePart)
		{
			if(null != ReturnName && "" != ReturnName)
				ReturnName = ReturnName + " " + NamePart;
			else
				ReturnName = NamePart;
		}
		NamePart = oUser.getAttribute("LastName");
		if(null != NamePart && "" != NamePart)
		{
			if(null != ReturnName && "" != ReturnName)
				ReturnName = ReturnName + " " + NamePart;
			else
				ReturnName = NamePart;
		}
	}
	return ReturnName;
}

function UserLookupGetFocusInput()
{
	if(null != this.HiddenUserId && this.HiddenUserId.value != null && this.HiddenUserId.value != "")
	{
		//Control is bound to a user
		return this.ClearButton;
	}
	else if(null != this.SearchButton && this.SearchButton.className.indexOf("Hidden") < 0)
	{
		//Either the field is empty or multiple were returned from search.
		return this.TextInput;
	}
	else if(null != this.CurrentButton && this.CurrentButton.className.indexOf("Hidden") < 0)
	{
		//Empty user field with no search button should be a current user field
		return this.CurrentButton;
	}
	else
	{
		return null;
	}
}

function UserLookupSetValue(oUser)
{
	var bHasCurrent = false;
	var bHasSearch = false;
	if(null != this.FieldID)
	{
		var oField = m_oXmlForm.selectSingleNode("/root/Form/Field[@ID = '" + this.FieldID + "'] | /root/Form/Field/Form/Field[@ID = '" + this.FieldID + "']");
		var strUITypeName = oField.getAttribute("UITypeName");
		bHasCurrent = ("CurrentUser" == strUITypeName.substr(0,11));
		bHasSearch = (strUITypeName.substr(0,11) == "User search" || strUITypeName.indexOf("with info") > 0 );
	}

	if(null != oUser)
	{
		var FullName = GetUserFullName(oUser);
		if(null != this.TextInput)
		{
			this.TextInput.value = FullName;
			this.TextInput.disabled = true;
		}
		if(null != this.HiddenUserFullName)
			this.HiddenUserFullName.value = FullName;
		if(null != this.HiddenUserId)
			this.HiddenUserId.value = oUser.getAttribute("ID");
		if(null != this.HiddenUserName)
			this.HiddenUserName.value = oUser.getAttribute("UserName");
		if(null != this.SearchButton && this.SearchButton.className.indexOf("Hidden") < 0)
			this.SearchButton.className = this.SearchButton.className + " Hidden";
		if(null != this.CurrentButton && this.CurrentButton.className.indexOf("Hidden") < 0)
			this.CurrentButton.className = this.CurrentButton.className + " Hidden";
		if(null != this.ClearButton)
			this.ClearButton.className = this.ClearButton.className.replace(/Hidden/g, "");
		if(null != this.InfoButton)
			this.InfoButton.className = this.InfoButton.className.replace(/Hidden/g, "");
	}
	else //user field is being cleared
	{
		if(null != this.TextInput)
		{
			this.TextInput.value = "";
			if(bHasSearch)
			{
				this.TextInput.disabled = false;
			}
		}
		if(null != this.HiddenUserFullName)
			this.HiddenUserFullName.value = "";
		if(null != this.HiddenUserId)
			this.HiddenUserId.value = "";
		if(null != this.HiddenUserName)
			this.HiddenUserName.value = "";
		if(null != this.SearchButton && bHasSearch)
			this.SearchButton.className = this.SearchButton.className.replace(/Hidden/g, "");
		if(null != this.CurrentButton && bHasCurrent)
			this.CurrentButton.className = this.CurrentButton.className.replace(/Hidden/g, "");
		if(null != this.ClearButton && this.ClearButton.className.indexOf("Hidden") < 0)
			this.ClearButton.className = this.ClearButton.className + " Hidden";
		if(null != this.InfoButton && this.InfoButton.className.indexOf("Hidden") < 0)
			this.InfoButton.className = this.InfoButton.className + " Hidden";
		if(null != this.InfoTable)
		{
			if(this.InfoTable.className.indexOf("Hidden") < 0)
			{
				this.InfoTable.className = this.InfoTable.className + " Hidden";
			}
			//So that table with info on previously selected user will not be found and displayed later.
			this.InfoTable.id = this.InfoTable.id + "_Invalid"; 
		}
	}
}

function UserLookupSetValueRule(oField, oParam)
{
	var oUser = oField.selectSingleNode("U[@ID = '" + oParam.getAttribute("Param") + "']");
	this.setValue(oUser);
}

function UserLookupSetFocus()
{
	if("" != this.HiddenUserId.value) //User field is not empty
		this.ClearButton.focus();
	else
	{
		var oField = m_oXmlForm.selectSingleNode("/root/Form/Field[@ID = '" + this.FieldID + "'] | /root/Form/Field/Form/Field[@ID = '" + this.FieldID + "']");
		var strUITypeName = oField.getAttribute("UITypeName");
		bHasSearch = (strUITypeName.substr(0,11) == "User search" || strUITypeName.indexOf("with info") > 0 );
		if(null != this.TextInput && bHasSearch)
			this.TextInput.focus();
		else if(null != this.CurrentButton)
			this.CurrentButton.focus();
	}
}

function UserLookupGetValueID()
{
	return this.HiddenUserId.value;
}

function UserLookupSetReadOnly(bReadOnly)
{
	// Making the User field ReadOnly will currently not hide the buttons.
	var bHideButtons = false;
	var strVisibilityValue;
	var strSearchButtonStyleUsed  = "UserSearchButton"; 
	var strCurrentButtonStyleUsed = "UserCurrentButton";
	var strClearButtonStyleUsed   = "UserClearButton";
	
	if(bHideButtons && bReadOnly)
		VisibilityValue = "hidden";
	else
		VisibilityValue = "visible";

	if(bReadOnly)
	{
		strSearchButtonStyleUsed  = strSearchButtonStyleUsed  + "Disabled"; 
		strCurrentButtonStyleUsed = strCurrentButtonStyleUsed + "Disabled";
		strClearButtonStyleUsed   = strClearButtonStyleUsed   + "Disabled";
	}
	
	if(null != this.TextInput)
	{
		this.TextInput.disabled = bReadOnly;
	}
	if(null != this.SearchButton)
	{
		this.SearchButton.disabled = bReadOnly;		
		this.SearchButton.parentNode.className = strSearchButtonStyleUsed;
		this.SearchButton.style.visibility = VisibilityValue;
	}
	if(null != this.CurrentButton)
	{
		this.CurrentButton.disabled = bReadOnly;		
		this.CurrentButton.parentNode.className = strCurrentButtonStyleUsed;
		this.CurrentButton.style.visibility = VisibilityValue;
	}
	if(null != this.ClearButton)
	{
		this.ClearButton.disabled = bReadOnly;		
		this.ClearButton.parentNode.className = strClearButtonStyleUsed;
		this.ClearButton.style.visibility = VisibilityValue;
	}
}

function UserLookupObject(oControl)
{
	if(null != oControl)
	{
		var iIndex = 10;
		var varParentElement = oControl.parentNode;
		while(null != varParentElement && iIndex-- > 0)
		{	
			var strClassName = varParentElement.className;
			
			if(varParentElement.FieldID != null)
			{
				this.FieldID = varParentElement.FieldID;
				if(null != strClassName && (strClassName == "FormControl" || strClassName.indexOf("FormControl ") >= 0))
				{
					// Go 2 higher to encapsulate the label as well when this is a regular form control
					if(varParentElement.parentNode != null && varParentElement.parentNode.parentNode != null)
						this.Master = varParentElement.parentNode.parentNode;
					else
						this.Master = varParentElement;
				}
				else
				{
					//Sub-document control
					this.Master = varParentElement;
				}					
//				alert("this.FieldID: " + this.FieldID + "\nthis.Master: " + this.Master.outerHTML);
				break;
			}

/*
			if(null != strClassName && (strClassName == "FormControl" || strClassName.indexOf("FormControl ") >= 0))
			{
				if(varParentElement.FieldID != null)
				{
					this.FieldID = varParentElement.FieldID;
					// Go 2 higher to encapsulate also the label
					if(varParentElement.parentNode != null && varParentElement.parentNode.parentNode != null)
						this.Master = varParentElement.parentNode.parentNode;
					else
						this.Master = varParentElement;
					break;
				}
			}
*/
			varParentElement = varParentElement.parentNode;
		}
	}
	if(this.Master != null)
	{
		var nodeList = this.Master.getElementsByTagName("input");
	    for (var i = 0; i < nodeList.length; i++) 
	    {
		    var nodeCurrent = nodeList[i];
	        var startIndex = nodeCurrent.id.lastIndexOf("_")+1;
	        var nodeIdentifier = nodeCurrent.id.substr(startIndex, nodeCurrent.id.length - startIndex);
	        switch(nodeIdentifier)
	        {
				case "txtSearch":
					this.TextInput = nodeCurrent;
					break;
				case "bSearch":
					this.SearchButton = nodeCurrent;
					break;
				case "bCurrent":
					this.CurrentButton = nodeCurrent;
					break;
				case "bClear":
					this.ClearButton = nodeCurrent;
					break;
				case "bInfo":
					this.InfoButton = nodeCurrent;
					break;
				case "tblInfo":
					this.InfoTable = nodeCurrent;
					break;
				case "txtUserId":
					this.HiddenUserId = nodeCurrent;
					break;
				case "txtUserName":
					this.HiddenUserName = nodeCurrent;
					break;
				case "txtUserFullName":
					this.HiddenUserFullName = nodeCurrent;
	        }
		}
		nodeList = this.Master.getElementsByTagName("Label");
		if(nodeList[0] != null)
			this.Label = nodeList[0];
		nodeList = this.Master.getElementsByTagName("table");
	    for (var i = 0; i < nodeList.length; i++) 
	    {
		    var nodeCurrent = nodeList[i];
	        var startIndex = nodeCurrent.id.lastIndexOf("_")+1;
	        var nodeIdentifier = nodeCurrent.id.substr(startIndex, nodeCurrent.id.length - startIndex);
	        switch(nodeIdentifier)
	        {
				case "tblInfo":
					//alert("Table found: " + nodeIdentifier);
					this.InfoTable = nodeCurrent;
					break;
			}
		}
	}
	this.setReadOnly = UserLookupSetReadOnly;
	this.setValue = UserLookupSetValue;
	this.setValueRule = UserLookupSetValueRule;
	this.setFocus = UserLookupSetFocus;
	this.getFocusInput = UserLookupGetFocusInput;
	this.getValueID = UserLookupGetValueID;
}

function GetUserObject(oControl)
{
	var oControlObject = new UserLookupObject(oControl);	
	if(null == oControlObject.HiddenUserId)
	{
//		alert("GetUserObject returns NULL");
		return null
	}
	else
	{
//		alert("GetUserObject returns valid object");
		return oControlObject;
	}
}

// UserLookup object definition ENDS
//-----------------------------------------

function OnBizViewLoad()
{
	SetFocusHandlers();
	LoadNavigation();
	LoadValidation();
}

function LoadValidation()
{
	try
	{
		//Execute the rules one by one based on behaviour
		if(null == m_oXmlForm)
		{
			var moz  	= (document.implementation && document.implementation.createDocument) ? true:false; //firefox
			var ie		= (window.ActiveXObject && document.all) ? true:false; //IE
			
			var oFormXmlElement = document.getElementById(m_strBaseControlName + "_FormXml");
			if(null != oFormXmlElement)
			{
				//Decode XML. Curly braces {} need to be converted to <>
				var strFormXml = oFormXmlElement.value.replace(/{/g, "<").replace(/}/g, ">");
				//alert(strFormXml);

				// For Gecko Browsers
				if (moz)
				{
					// Don't support FireFox at all is the best choice right now
					// Standard client side validation scripts are not included and won't work in FireFox
					// It is therefore pointless to try to use it
					return;
					Array.prototype.expr = "";				
					XMLDocument.prototype.setProperty  = function(x,y){};
					XMLDocument.prototype.selectNodes = function(sExpr, contextNode)
					{
						var oResult = this.evaluate(sExpr, (contextNode?contextNode:this), 
											this.createNSResolver(this.documentElement),
											XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
						var nodeList = new Array(oResult.snapshotLength);
						nodeList.expr = sExpr;
						for(i=0;i<nodeList.length;i++)
							nodeList[i] = oResult.snapshotItem(i);
						return nodeList;
					};
					Element.prototype.selectNodes = function(sExpr)
					{
						var doc = this.ownerDocument;
						if(doc.selectNodes)
							return doc.selectNodes(sExpr, this);
						else
							throw new Error(-1, "selectNodes error");
					};
					XMLDocument.prototype.selectSingleNode = function(sExpr, contextNode)
					{
						var ctx = contextNode?contextNode:null;
						sExpr += "[1]";
						var nodeList = this.selectNodes(sExpr, ctx);
						if(nodeList.length > 0)
							return nodeList[0];
						else 
							return null;
					};
					Element.prototype.selectSingleNode = function(sExpr)
					{
						var doc = this.ownerDocument;
						if(doc.selectSingleNode)
							return doc.selectSingleNode(sExpr, this);
						else
							throw new Error(-1, "selectSingleNode error");
					};
					//alert("Loading: " + m_strFormXml + "\n" + m_strBaseControlName + "_xmlForm");
					m_oXmlForm = (new DOMParser()).parseFromString(strFormXml, 'text/xml');
					
				}
				// For IE/Win
				else if (ie)
				{
					m_oXmlForm = new ActiveXObject("MSXML2.DOMDocument");
					m_oXmlForm.async = false;
					m_oXmlForm.loadXML(strFormXml);
					m_oXmlForm.setProperty("SelectionLanguage", "XPath");
				}
			}
		}
		if(null != m_oXmlForm)
		{	
			//Xml exists and is ready to use
			//Execute all the default value rules first and then the value change rules
			var oRuleXs = m_oXmlForm.selectNodes("/root/Form/ValueRules/Rule[@BehaviourSystemName = 'DefaultValue']");
			ExecuteValueRules(oRuleXs, 'DefaultValue', 1, false);
			oRuleXs = m_oXmlForm.selectNodes("/root/Form/ValueRules/Rule[@BehaviourSystemName = 'ValueChange']");
			ExecuteValueRules(oRuleXs, 'ValueChange', 1, false);
			oRuleXs = m_oXmlForm.selectNodes("/root/Form/BehaviourRules/Rule");
			ExecuteBehaviourRules(oRuleXs);		
		}
		FixCheckBoxValidatorHookup();
	}
	catch(e)
	{
		alert("Error executing on load validation: " + e.description);
	}
}

function SetFocusHandlers()
{
	var sfEls = document.getElementsByTagName("INPUT");
	for (var i=0; i<sfEls.length; i++) 
	{
		if(typeof(sfEls[i].parentElement.FieldID) != "undefined" || sfEls[i].type == "radio" || sfEls[i].type == "checkbox")
		{
			sfEls[i].onkeydown = function()
			{
				OnDefaultButtonKeyDown();
			}
		}
		sfEls[i].onfocus=function() 
		{
//			if(this.type == "text") m_bInsideInput = true;
			this.className+=" sffocus";
		}
		sfEls[i].onblur=function() 
		{
//			if(this.type == "text") m_bInsideInput = false;
			this.className=this.className.replace(new RegExp(" sffocus\\b"), "");
		}
	}
	var sfEls = document.getElementsByTagName("TEXTAREA");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onfocus=function() {
			this.className+=" sffocus";
		}
		sfEls[i].onblur=function() {
			this.className=this.className.replace(new RegExp(" sffocus\\b"), "");
		}
	}
}

function LoadNavigation()
{
	//alert("Starting OnLoadNavigation()");
	var oNavigationElement = document.getElementById(m_strBaseControlName + "_NavigationData");
	if(null != oNavigationElement)
	{
		//alert("LoadNavigation: " + oNavigationElement.value);
		var infoString = oNavigationElement.value;
		if(null != infoString && infoString.length > 0)
		{
			var infoArray = infoString.split(";");
			var scrollX = infoArray[0];
			var scrollY = infoArray[1];
			var focusId = infoArray[2];
			window.scrollTo(scrollX, scrollY);
			var oControl = document.getElementById(focusId);	
			if(null != oControl)
			{
				// This control may now be disabled (e.g. input field in UserControl)
				var oControlObject = null;
				if(window.BizViewExtensionGetObject) // Check for extension input (originally ServiceLookup)
				{
					oControlObject = BizViewExtensionGetObject(oControl);
				}		
				if(null == oControlObject) // Check for User input
				{
					oControlObject = GetUserObject(oControl);
				}
				
				if(null != oControlObject && null != oControlObject.getFocusInput())
				{
					oControl = oControlObject.getFocusInput();
				}
				try
				{
					//alert("LoadNavigation: setting focus to " + oControl.outerHTML);
					if(null != oControl)
					{
						oControl.focus();
					}
				}
				catch(e)
				{
					// Non-critical error, no need to show a message box
					//alert("Unable to set focus to " + oControl.id);
				}
			}
		}
	}
}

//var countAlert = 0;
function OnBizViewFormSubmit()
{
//    if(countAlert < 3)
//    {
//        alert("OnBizViewFormSubmit, " + m_strActiveLookupButtonFieldName + "\n" + countAlert);
//        countAlert++;
//    }
	OpenDisabledFieldsForServer();
	UpdateFormXmlForServer();
	SaveNavigation();
	if(m_strActiveLookupFieldId != "")
	{
    	theForm.__EVENTTARGET.value = m_strActiveLookupButtonFieldName;
//alert("Preventing postback");
		// Žaš er veriš aš submitta lookup control, žurfum aš returna false til aš 
		// koma ķ veg fyrir standard postback. Gerum postback hér įn client side validation

//		window.setTimeout("DoBizViewSubmit();", 10 );
//		return false;
	}
	return true;
}

function DoBizViewSubmit()
{
	__doPostBack(m_strActiveLookupButtonFieldName, '');
}

function SaveNavigation()
{
	// Save navigation information to hidden field so it can be loaded back after postback
	var oNavigationElement = document.getElementById(m_strBaseControlName + "_NavigationData");
	if(null != oNavigationElement)
	{
		var scrollX;
		var scrollY;
		if(document.documentElement.scrollTop)
		{
			scrollY = document.documentElement.scrollTop; //IE
			scrollX = document.documentElement.scrollLeft; //IE
		}
		else
		{
			scrollY = document.body.scrollTop; //Standard
			scrollX = document.body.scrollLeft; //Standard
		}

		var focusId = "";
		if(m_strActiveLookupFieldId != "")
		{	//This should store an id of the input of a custom field to give focus to after postback
			focusId = m_strActiveLookupFieldId;
		}
		else // If OnLookupKeyDown did not set m_strActiveLookupFieldId then user is clicking the button
		{
			if(null != document && null != document.activeElement)
			{
				focusId = document.activeElement.id; //This is IE specific
				var oControl = document.getElementById(focusId);
				//Check that this is a user or custom control and set focusid to the appropriate field if so
				if(null != oControl)
				{
					var oControlObject = null;
					if(window.BizViewExtensionGetObject)
					{
						oControlObject = BizViewExtensionGetObject(oControl);
					}		
					if(null == oControlObject)
					{
						oControlObject = GetUserObject(oControl);
					}
					if(null != oControlObject && null != oControlObject.getFocusInput())
					{						
						//Not certain that this control will be focusable after postback
						//Will check for this when loading navigation!
						focusId = oControlObject.getFocusInput().id;
					}
				}
			}
		}
		oNavigationElement.value = scrollX + ";" + scrollY + ";" + focusId;
		//alert("SaveNavigation: " + oNavigationElement.value);
	}
}

function FixCheckBoxValidatorHookup() 
{
	try
	{
		var strControlId = "";
		var aInput = document.body.getElementsByTagName("INPUT");
		for(var i = 0; i < aInput.length; i++)
		{
			var oInput = aInput[i];
			if(null != oInput && oInput.type == "checkbox")
			{
				//Determine if this is a check box that is connected to a validator
				//Find the parent form element
				var iIndex = 15;
				strControlId = "";
				var varParentElement = oInput.parentNode;
				while(null != varParentElement && iIndex-- > 0)
				{	
					var strClassName = varParentElement.className;
					if(strControlId == "" && varParentElement.tagName == "TABLE")
					{
						//Checkboxes are always in a table that has the control id
						strControlId = varParentElement.id;
					}
					if(strClassName == "FormElement" || strClassName.indexOf("FormElement ") >= 0)
					{
						//Found it
						var aSpan = varParentElement.getElementsByTagName("SPAN");
						for(var j = 0; j < aSpan.length; j++)
						{
							if(strControlId != "" && aSpan[j].controltovalidate == strControlId)
							{
								if(typeof(ValidatorOnChange) != "undefined")
								{
									aInput[i].onclick = ValidatorOnChange;
								}
							}
						}
						iIndex = -1; //Quit looping
					}
					varParentElement = varParentElement.parentNode;
				}
			}
			else if(null != oInput && oInput.type == "radio")
			{
				var ev = oInput.onclick;
				if (typeof(ev) == "function" ) 
				{            
					ev = ev.toString();
					ev = ev.substring(ev.indexOf("{") + 1, ev.lastIndexOf("}"));
				}
				else 
				{
					ev = "";
				}
				var func = new Function("SaveNavigation(); " + ev);			
				oInput.onclick = func;
			}
		}
//		alert("disabling " + document.all("_ctl1_Search_m_txtSearch").outerHTML);
//		document.all("_ctl1_Search_m_txtSearch").disabled = true;
//		document.all("_ctl1_Search_m_btnSearch").disabled = true; 
	}
	catch(e)
	{
		alert("Error hooking up up executing on load validation: " + e.description);
	}
}

function ExecuteBehaviourRules(oRuleXs)
{
	try
	{
//		alert("ExecuteBehaviourRules, count: " + oRuleXs.length);
		var oRuleX = null;
		for(var i = 0; i < oRuleXs.length; i++)
		{
			oRuleX = oRuleXs[i];
//			alert("ExecuteBehaviourRules, oRuleX.xml: " + oRuleX.xml);
			var oFieldSource = m_oXmlForm.selectSingleNode("/root/Form/Field[@ID = '" + oRuleX.getAttribute("SourceFieldID") + "']");
			var oFieldAffected = m_oXmlForm.selectSingleNode("/root/Form/Field[@ID = '" + oRuleX.getAttribute("AffectedFieldID") + "']");
			if(oFieldAffected.getAttribute("DisableWritePermission") != "1" || oRuleX.getAttribute("BehaviourSystemName") == "ShowHide")
			{
				var oRule = m_oXmlForm.selectSingleNode("/root/Form/Rule[@ID = '" + oRuleX.getAttribute("ID") + "']");
//				alert("ExecuteBehaviourRules.  oRule.xml: " + oRule.xml);
				var bRuleOn = IsRuleOn(oFieldSource, oFieldAffected, oRule);
				var bRuleExecuted = false;
//				alert("oRule.xml: " + oRule.xml + "\nbRuleOn: " + bRuleOn);
				if(bRuleOn)
				{
					if(oRule.getAttribute("BehaviourSystemName") == "Mandatory" || oRule.getAttribute("BehaviourSystemName") == "ReadOnly")
					{
						//Mutually exclusive rules
						if(null == oFieldAffected.getAttribute("ExclusivePriority") || oFieldAffected.getAttribute("ExclusivePriority") * 1 < oRule.getAttribute("Priority") * 1)
						{
							if(null != oFieldAffected.getAttribute("ExclusiveType"))
							{
								//There is an exclusive rule already applied to this field, undo that rule before the new one is applied
								RevokeExclusiveRule(oFieldAffected);
							}
							ApplyExclusiveRule(oFieldAffected, oRule);
							bRuleExecuted = true;
						}
					}
					else if(oRule.getAttribute("BehaviourSystemName") == "ShowHide")
					{
						if(null == oFieldAffected.getAttribute("ShowHidePriority") || oFieldAffected.getAttribute("ShowHidePriority") * 1 <= oRule.getAttribute("Priority") * 1)
						{
							if(null != oFieldAffected.getAttribute("ShowHidePriority"))
							{
								RevokeShowHideRule(oFieldAffected);
							}
							ApplyShowHideRule(oFieldAffected, oRule);
							bRuleExecuted = true;
						}
					}
					else if(oRule.getAttribute("BehaviourSystemName") == "Informational")
					{
						if(null == oFieldAffected.getAttribute("InformationalPriority") || oFieldAffected.getAttribute("InformationalPriority") * 1 <= oRule.getAttribute("Priority") * 1)
						{
							if(null != oFieldAffected.getAttribute("InformationalPriority"))
							{
								RevokeInformationalRule(oFieldAffected);
							}
							ApplyInformationalRule(oFieldAffected, oRule);
							bRuleExecuted = true;
						}
					}
				}
				else
				{
					if(oRule.getAttribute("BehaviourSystemName") == "Mandatory" || oRule.getAttribute("BehaviourSystemName") == "ReadOnly")
					{
						//Mutually exclusive rule that is off
						//If this rule is applied to the field it needs to be removed
						//It is guaranteed that no rule with higher priority applies to this field otherwise it would already
						// have been handled
						if(null != oFieldAffected.getAttribute("ExclusiveRuleID") && oFieldAffected.getAttribute("ExclusiveRuleID") == oRule.getAttribute("ID"))
						{
							RevokeExclusiveRule(oFieldAffected);
							// An exclusive rule with the same priority might have to be applied
							// It may have appeared before this in oRuleXs, and was not applied because
							// this current rule was already applied.
							ExecuteBehaviourRules(oRuleXs);
							bRuleExecuted = true;
						}					
					}
					else if(oRule.getAttribute("BehaviourSystemName") == "ShowHide")
					{
						if(null != oFieldAffected.getAttribute("ShowHideRuleID") && oFieldAffected.getAttribute("ShowHideRuleID") == oRule.getAttribute("ID"))
						{
							RevokeShowHideRule(oFieldAffected);
							bRuleExecuted = true;
						}					
					}
					else if(oRule.getAttribute("BehaviourSystemName") == "Informational")
					{
						if(null != oFieldAffected.getAttribute("InformationalRuleID") && oFieldAffected.getAttribute("InformationalRuleID") == oRule.getAttribute("ID"))
						{
							RevokeInformationalRule(oFieldAffected);
							bRuleExecuted = true;
						}					
					}
				}
				//if a rule was executed or revoked
				if(bRuleExecuted)
				{
					//Run all rules that have lower or the same priority and not the same rule on the field that is affected
					var oNewRuleXs = m_oXmlForm.selectNodes("/root/Form/BehaviourRules/Rule[@AffectedFieldID = '" + oRuleX.getAttribute("AffectedFieldID") + "' and @ID != '" + oRuleX.getAttribute("ID") + "' and @Priority < '" + oRuleX.getAttribute("Priority") + "' and @BehaviourSystemName = '" + oRule.getAttribute("BehaviourSystemName") + "']");
//					alert("oRule.getAttribute('BehaviourSystemName'): " + oRule.getAttribute("BehaviourSystemName") + "\n" + oNewRuleXs.length );
					ExecuteBehaviourRules(oNewRuleXs);
				}
			}
		}
	}
	catch(e)
	{	
		throw new Error(-1, "\nError executing behaviour rules: " + e.description);
	}
}

function ExecuteValueRules(oRuleXs, strRuleType, iLevel, bExecuteBehaviourRules)
{
//	alert("ExecuteValueRules, oRuleXs.length: " + oRuleXs.length);
//	alert("ExecuteValueRules, Level: " + iLevel + ", oRuleXs.length: " + oRuleXs.length);
	try
	{
		var oRuleX = null;
		for(var i = 0; i < oRuleXs.length; i++)
		{
			oRuleX = oRuleXs[i];
//			alert("ExecuteValueRules, oRuleX.xml: " + oRuleX.xml + "\noRuleXs.length: " + oRuleXs.length + "\ni: " + i);
			var oFieldSource = m_oXmlForm.selectSingleNode("/root/Form/Field[@ID = '" + oRuleX.getAttribute("SourceFieldID") + "']");
			var oFieldAffected = m_oXmlForm.selectSingleNode("/root/Form/Field[@ID = '" + oRuleX.getAttribute("AffectedFieldID") + "']");
			if(oFieldAffected.getAttribute("DisableWritePermission") != "1") //Do not touch read only fields
			{
				var oRule = m_oXmlForm.selectSingleNode("/root/Form/Rule[@ID = '" + oRuleX.getAttribute("ID") + "']");
//				alert("ExecuteValueRules.  oRule.xml: " + oRule.xml);
				var bRuleOn = IsRuleOn(oFieldSource, oFieldAffected, oRule);			
				if(bRuleOn)
				{
//					alert("Rule is ON, oRuleX.xml: " + oRuleX.xml + "\noFieldAffected.xml: " + oFieldAffected.xml);
					if(null == oFieldAffected.getAttribute(strRuleType + "Priority") || oFieldAffected.getAttribute(strRuleType + "Priority") * 1 <= oRule.getAttribute("Priority") * 1)
					{					
						//If dealing with a default value rule the rule is not executed if the user has changed the value before
						if(null == oFieldAffected.getAttribute("UserHasChanged") || (strRuleType == "DefaultValue" && oFieldAffected.getAttribute("UserHasChanged") != "yes") || strRuleType == "ValueChange")
						{
							if(strRuleType == "ValueChange")
							{
								oFieldAffected.setAttribute("UserHasChanged", "yes"); //As if the user has changed this
							}	
							//Change the value							
							ApplyValueRule(oFieldAffected, oRule, bExecuteBehaviourRules);
							oFieldAffected.setAttribute(strRuleType + "Priority", oRule.getAttribute("Priority"));
							oFieldAffected.setAttribute(strRuleType + "ActiveRuleID", oRule.getAttribute("ID")); //HKB testing
							var oChildXs = oRuleX.selectNodes("ChildRules/Rule[@BehaviourSystemName = '" + strRuleType + "']");							
//							alert("About to execute rules, count: " + oChildXs.length + "\noRuleX.xml: " + oRuleX.xml + "\nLevel: " + iLevel + "\nRuleOn: " + bRuleOn);
							ExecuteValueRules(oChildXs, strRuleType, iLevel + 1, bExecuteBehaviourRules);
						}
					}
				}
				else
				{
//					alert("Rule is OFF, oRuleX.xml: " + oRuleX.xml + "\noFieldAffected.xml: " + oFieldAffected.xml);
					//The current rule is not ON, if a different rule has already been run on this particular affected field
					// then that change needs to be reconsidered
					if(null != oFieldAffected.getAttribute(strRuleType + "Priority"))
					{
						//A rule of this type has been run before on the affected field
						//If the priority of the rule being evaluated is higher than the rule already run on the field
						//then remove the value and rerun the rules
						var bRunAffectedRules = false;
						if(strRuleType == "DefaultValue" && (null == oFieldAffected.getAttribute("UserHasChanged") || oFieldAffected.getAttribute("UserHasChanged") != "yes"))
						{
							//Working with default values and the field has not been changed by the user, remove the value from the field
							//Rerunning the rules that affect this field will put the value back if it supposed to go back - HKB: NO!!!
							//ChangeFieldValue(oFieldAffected, "", bExecuteBehaviourRules);

//							if(oFieldAffected.getAttribute(strRuleType + "Priority") * 1 <= oRuleX.getAttribute("Priority") * 1)
//							//Only rules with lower or equal priority as this one will be rerun.
//							//So we can't clear the field if a rule with higher priority did set the value.
//							//This didn't work as it requires running affected rules with same priority 
//							//which cause endless recursion!!!!
//							//Problem with this is that another rule with the same priority may not run, but only a rule with lower priority
							if(oFieldAffected.getAttribute(strRuleType + "ActiveRuleID") == oRuleX.getAttribute("ID"))
							{
								//Clearing only the field if it was this rule that set the field value.
								ClearFieldValue(oFieldAffected, bExecuteBehaviourRules);
								//Remove that evidence and rerun all value rules on the field in priority order
								oFieldAffected.removeAttribute(strRuleType + "Priority");
								oFieldAffected.removeAttribute(strRuleType + "ActiveRuleID");
								bRunAffectedRules = true;
							}
							//bRunAffectedRules = true;
						}
						else if(strRuleType == "DefaultValue")
						{
							//Working with default values and the field has been changed, no need to continue, this is the end of the line
							bRunAffectedRules = false;
						}
						else if(strRuleType == "ValueChange")
						{
							//Working with value change rules, A value change rule has been executed on the affected field
							//Run other rules with lower priority than this one that might now want to change the field value.
							if(oFieldAffected.getAttribute(strRuleType + "ActiveRuleID") == oRuleX.getAttribute("ID"))
							{
								oFieldAffected.removeAttribute(strRuleType + "Priority");
								oFieldAffected.removeAttribute(strRuleType + "ActiveRuleID");
							
								bRunAffectedRules = true;
							}
						}
						if(bRunAffectedRules)
						{
							//Remove that evidence and rerun all value rules on the field in priority order
							//oFieldAffected.removeAttribute(strRuleType + "Priority");
							//oFieldAffected.removeAttribute(strRuleType + "ActiveRuleID");
							//var oChildXs = m_oXmlForm.selectNodes("/root/Form/ValueRules/Rule[@BehaviourSystemName = '" + strRuleType + "' and @AffectedFieldID = '" + oFieldAffected.getAttribute("ID") + "' and @ID != '" + oRuleX.getAttribute("ID") + "']");
							var oChildXs = m_oXmlForm.selectNodes("/root/Form/ValueRules/Rule[@BehaviourSystemName = '" + strRuleType + "' and @AffectedFieldID = '" + oFieldAffected.getAttribute("ID") + "' and @ID != '" + oRuleX.getAttribute("ID") + "' and @Priority < '" + oRuleX.getAttribute("Priority") + "']");
							//alert("About to execute rules, count: " + oChildXs.length + "\noRuleX.xml: " + oRuleX.xml + "\nLevel: " + iLevel + "\nRuleOn: " + bRuleOn);
							ExecuteValueRules(oChildXs, strRuleType, iLevel + 1, bExecuteBehaviourRules);
						}
					}				
				}
			}
		}
	}
	catch(e)
	{
		throw new Error(-1, "\nError executing value rules: " + e.description);
	}
}

function IsRuleOn(oFieldSource, oFieldAffected, oRule)
{
/*
	if(oRule.getAttribute("Name") == "SkilyrtEfEkkiNetfang")
	{
		alert("IsRuleOn: oRule.xml: " + oRule.xml);
	}
*/
	try
	{
		var bRuleOn = false;
		if(typeof(oFieldSource) == "undefined" || null == oFieldSource) //If there is no source field, then this rule is on
		{
			bRuleOn = true;
		}
		else
		{
			//Dates are handled differently
			var strSourceFieldValue = oRule.getAttribute("SourceFieldValue");
			var strValue = null;
			if(null == strSourceFieldValue)
			{
				strSourceFieldValue = "";
			}
			if(oFieldSource.getAttribute("DataTypeName") == "DateTime" || oFieldSource.getAttribute("DataTypeName") == "Date" || oFieldSource.getAttribute("DataTypeName") == "Time")
			{
				strValue = GetDateControlValue(oFieldSource);			
				if(null != strValue)
				{
					var dtSource = XmlDateToDate(strSourceFieldValue);
					strSourceFieldValue = dtSource.toString();
				}
			}
			else
			{
				strValue = GetHtmlControlValue(oFieldSource);
			}
			// SPECIAL HANDLING FOR USER FIELD SHOULD BE REQUIRED HERE (although this works for rules with condition of type field <> empty)
			if(strValue != null)
			{
	//				alert("Checking if rule is on:\nSourceValueOperator: " + oRule.getAttribute("SourceValueOperator") + "\nValue: " + strValue + "\nstrSourceFieldValue: " + strSourceFieldValue);
				switch(oRule.getAttribute("SourceValueOperator"))
				{
					case '<>':
						if(oFieldSource.getAttribute("DataTypeName") == "MultiSelectionList")
						{
							bRuleOn = (strValue.indexOf(strSourceFieldValue) == -1);
						}
						else
						{
							bRuleOn = (strValue != strSourceFieldValue);
						}
						break;
					case '==':
						if(oFieldSource.getAttribute("DataTypeName") == "MultiSelectionList")
						{
							bRuleOn = (strValue.indexOf(strSourceFieldValue) > -1);
						}
						else
						{
							bRuleOn = (strValue == strSourceFieldValue);
						}
						break;
					default:
						bRuleOn = false;
				}
			}		
		}
	}
	catch(e)
	{
		alert("Exception(IsRuleOn): " + e.description);
	}
//	alert("Checking if rule is on, result: " + bRuleOn);
	return bRuleOn;
}

function RevokeExclusiveRule(oFieldAffected)
{
	var strExclusiveType = oFieldAffected.getAttribute("ExclusiveType");
	oFieldAffected.removeAttribute("ExclusiveType");
	oFieldAffected.removeAttribute("ExclusivePriority");
	oFieldAffected.removeAttribute("ExclusiveValue");
	oFieldAffected.removeAttribute("ExclusiveRuleID");
	
	if(strExclusiveType == "Mandatory")
	{
		RevokeMandatoryRule(oFieldAffected);
	}
	else if(strExclusiveType == "ReadOnly")
	{
		RevokeReadOnlyRule(oFieldAffected);
	}
}

function RevokeShowHideRule(oFieldAffected)
{
	/*
	This function correctly assumes that revoking a ShowHide rule does always mean the field 
	will be shown after revoking. This behavior is correct because the default state of
	a field	is being shown. 
	Applying a Show rule has no effect on a field (unless a lower priority Hide rule
	is being run over) so revoking it should not have any effect either (unless the lower
	priority rule will take over again).
	*/

	oFieldAffected.removeAttribute("ShowHidePriority");
	oFieldAffected.removeAttribute("ShowHideValue");
	oFieldAffected.removeAttribute("ShowHideRuleID");
/*
	var oLabelDiv = null;
	if(oFieldAffected.getAttribute("DataTypeName") == "User")
	{
		var oControl = document.getElementById(oFieldAffected.getAttribute("ClientID"));
		var oControlObject = GetUserObject(oControl);
		if(null != oControlObject)
		{
			oLabelDiv = oControlObject.Label;
		}
	}
	if(null == oLabelDiv)
	{
		oLabelDiv = document.getElementById(oFieldAffected.getAttribute("ClientID")+ "Label");
	}
	if(null != oLabelDiv)
	{
		//Find the parent row that holds the label and the control
		var iIndex = 10;
		var varParentElement = oLabelDiv.parentNode;
		while(null != varParentElement && iIndex-- > 0)
		{	
			var strClassName = varParentElement.className;
			if(strClassName == "FormElement" || strClassName.indexOf("FormElement ") >= 0)
			{
				varParentElement.className = varParentElement.className.replace(/Hidden/g, "");
				varParentElement.removeAttribute("IsHidden");
				alert("RevokeShowHideRule\n" + oLabelDiv.innerHTML + "\nvarParentElement: " + varParentElement.outerHTML);
				ShowHideFormSection(varParentElement);
				return;
			}
			varParentElement = varParentElement.parentNode;
		}
	}
*/
}

function RevokeInformationalRule(oFieldAffected)
{
	oFieldAffected.removeAttribute("InformationalPriority");
	oFieldAffected.removeAttribute("InformationalValue");
	oFieldAffected.removeAttribute("InformationalRuleID");
	
	var oControl = document.getElementById(oFieldAffected.getAttribute("ClientID"));
	if(null != oControl)
	{
		var oControlDiv = oControl.parentNode;
		var varImg = oControlDiv.all.tags("IMG");
		if(null != varImg && varImg.length == 1)
		{
			varImg = varImg[0];
			varImg.parentNode.removeChild(varImg);
		}
	}
}

function RevokeMandatoryRule(oFieldAffected)
{
	/*
	The same applies to this function as the comments in functions
	RevokeReadOnlyRule and RevokeShowHideRule
	*/
	
	var oLabelDiv = null;
	if(oFieldAffected.getAttribute("DataTypeName") == "User")
	{
		var oControl = document.getElementById(oFieldAffected.getAttribute("ClientID"));
		var oControlObject = GetUserObject(oControl);
		if(null != oControlObject)
		{
			oLabelDiv = oControlObject.Label;
		}
	}
	if(null == oLabelDiv)
	{
		oLabelDiv = document.getElementById(oFieldAffected.getAttribute("ClientID")+ "Label");
	}
	if(null != oLabelDiv)
	{
		var strLabel = oLabelDiv.innerText;
		if(strLabel.lastIndexOf("*") + 1 == strLabel.length)
		{
			oLabelDiv.innerText = strLabel.substring(0, strLabel.length - 2);
		}
	}
}

function RevokeReadOnlyRule(oFieldAffected)
{
	/*
	This function correctly assumes that revoking a ReadOnly rule does always mean the field 
	will be enabled after revoking. This behavior is correct because the default state of
	a field	is being enabled.
	Applying a ReadOnly-Off rule has no effect on a field (unless a lower priority ReadOnly-On
	is being run over) so revoking it should not have any effect either (unless the lower
	priority rule will take over again).
	*/
	
	var oControl = document.getElementById(oFieldAffected.getAttribute("ClientID"));
	if(null == oControl && oField.getAttribute("DataTypeName") == "Date")
	{
	    oControl = igdrp_getComboById(oField.getAttribute("ClientID")); 
	}
	if(null != oControl)
	{
		var oControlObject = null;
		if(window.BizViewExtensionGetObject)
		{
			oControlObject = BizViewExtensionGetObject(oControl);
		}		
		if(null != oControlObject)
		{
			//Nota objectiš
			oControlObject.setReadOnly(false);
		}
		else
		{
			if(oFieldAffected.getAttribute("DataTypeName") == "DateTime" || oFieldAffected.getAttribute("DataTypeName") == "Time")
			{
				var oControlObject = igedit_getById('x' + oFieldAffected.getAttribute("ClientID"));
				if(null != oControlObject)
				{
					oControlObject.setEnabled(true);
					//oControlObject.setReadOnly(false);
				}
			}
			else if(oFieldAffected.getAttribute("DataTypeName") == "Date")
			{
				var oControlObject = oControl;
				if(null != oControlObject)
				{
					oControlObject.setEnabled(true);
					//oControlObject.setReadOnly(false);
				}
			}
			else if(oFieldAffected.getAttribute("DataTypeName") == "User")
			{
				//var oControlObject = new UserLookupObject(oControl);
				var oControlObject = GetUserObject(oControl);
				if(null != oControlObject)
				{
					oControlObject.setReadOnly(false);
				}
			}
			else
			{
				//Readonly does not seem to work on radio buttons
				oControl.disabled = false;
				//oControl.readonly = false;
			}
		}
	}
}

function ApplyExclusiveRule(oFieldAffected, oRule)
{
	var oParam = oRule.selectSingleNode("Param");
	if(null != oParam)
	{
		oFieldAffected.setAttribute("ExclusivePriority", oRule.getAttribute("Priority"));
		oFieldAffected.setAttribute("ExclusiveType", oRule.getAttribute("BehaviourSystemName"));
		oFieldAffected.setAttribute("ExclusiveValue", oParam.getAttribute("Param"));
		oFieldAffected.setAttribute("ExclusiveRuleID", oRule.getAttribute("ID"));

		if(oRule.getAttribute("BehaviourSystemName") == "Mandatory")
		{
			ApplyMandatoryRule(oFieldAffected, oRule);
		}
		else if(oRule.getAttribute("BehaviourSystemName") == "ReadOnly")
		{
			ApplyReadOnlyRule(oFieldAffected, oRule);
		}
	}
}

function ApplyShowHideRule(oFieldAffected, oRule)
{
	var oParam = oRule.selectSingleNode("Param");
	if(null != oParam)
	{
		var strValue = oParam.getAttribute("Param");
		oFieldAffected.setAttribute("ShowHidePriority", oRule.getAttribute("Priority"));
		oFieldAffected.setAttribute("ShowHideValue", strValue);
		oFieldAffected.setAttribute("ShowHideRuleID", oRule.getAttribute("ID"));

		var oLabelDiv = null;
		if(oFieldAffected.getAttribute("DataTypeName") == "User")
		{
			var oControl = document.getElementById(oFieldAffected.getAttribute("ClientID"));
			var oControlObject = GetUserObject(oControl);
			if(null != oControlObject)
			{
				oLabelDiv = oControlObject.Label;
			}
		}
		else if(oFieldAffected.getAttribute("DataTypeName") == "MultiDocument")
		{
			//Id of the label is corrupt and not according to standard for multidocuments
			oLabelDiv = document.getElementById(oFieldAffected.getAttribute("ClientID"));
		}
		if(null == oLabelDiv)
		{
			oLabelDiv = document.getElementById(oFieldAffected.getAttribute("ClientID")+ "Label");
		}
		if(null != oLabelDiv)
		{
			var iIndex = 10;
			var varParentElement = oLabelDiv.parentNode;
			while(null != varParentElement && iIndex-- > 0)
			{	
				var strClassName = varParentElement.className;
				if(varParentElement.tagName == "DIV" && (strClassName == "FormElement" || strClassName.indexOf("FormElement ") >= 0))
				{					
					varParentElement.className = varParentElement.className.replace(/Hidden/g, "");
					if(strValue == "0")
					{
//						alert("ApplyShowHideRule\n" + oLabelDiv.innerHTML + "\nShow");
						//Show the field
						varParentElement.className = varParentElement.className.replace(/Hidden/g, "");
						varParentElement.removeAttribute("IsHidden");
					}
					else
					{
//						alert("ApplyShowHideRule\n" + oLabelDiv.innerHTML + "\nHide");
						//Hide the field
						varParentElement.className = varParentElement.className + " Hidden";
						varParentElement.setAttribute("IsHidden", "yes");
					}
					//After showing or hiding a form element we need to check if the form section should be shown/hidden as well
					ShowHideFormSection(varParentElement);
					return;
				}
				varParentElement = varParentElement.parentNode;
			}
		}
	}
}

function ShowHideFormSection(oFormElement)
{
	var bShow = false; //Start with false, if we find any form element that is shown this changes to true
	var bShowSectionRow = false;
	
	//Either the FormElement is directly under the FormSection or in a table that is directly under FormSection
	//Find the FormSection and then go recursively to all FormElement and check if they should be shown
	var oFormSection = null;
	var iIndex = 10;
	var varParentElement = oFormElement.parentNode;
	while(null != varParentElement && iIndex-- > 0)
	{	
		var strClassName = varParentElement.className;
		if(strClassName == "FormSection" || strClassName.indexOf("FormSection ") >= 0)
		{
			oFormSection = varParentElement;
			iIndex = -1; //Stop looping
		}
		varParentElement = varParentElement.parentNode;
	}
	//alert(oFormSection.outerHTML);
	if(null != oFormSection)
	{
		//Go down the formsection/formsectionrow/formelement hierarchy and check whether to show or hide	
		for(var i = 0; i < oFormSection.childNodes.length && false == bShow; i++)
		{
			var oFormSectionChild = oFormSection.childNodes[i];
			bShow = ProcessFormSectionChild(oFormSectionChild);
		}
//		var oH4 = oFormSection.getElementsByTagName("H4"); //Only hiding the header, hiding the whole section 
		// results in scrambled look for the fields inside the section on page load
//		if(oH4.length > 0)
//		{
			if(bShow == true)
			{
				oFormSection.className = oFormSection.className.replace(/Hidden/g, "");
			}
			else
			{	
				oFormSection.className = oFormSection.className + " Hidden";
			}
			
			//Check if all the sections are hidden, if so show/hide the row
			oFormRow = oFormSection.parentNode;
			var strClassName = oFormRow.className;
			if(strClassName == "FormRow" || strClassName.indexOf("FormRow ") >= 0)
			{
				var showRow = false;
				for(var j = 0;j < oFormRow.childNodes.length;j++)
				{
					var strClassName = oFormRow.childNodes[j].className;
					if(strClassName == "FormSection" || strClassName.indexOf("FormSection ") >= 0)
					{
						if(strClassName.indexOf("Hidden") < 0)
						{
							showRow = true;
						}
					}
				}
				if(showRow == true)
				{
					oFormRow.className = oFormRow.className.replace(/Hidden/g, "");
				}
				else // if (oFormSection.className.indexOf("Hidden") < 0)
				{	
					oFormRow.className = oFormRow.className + " Hidden";
				}
			}
//		}
	}
}

function ProcessFormSectionChild(oChild)
{
	var bShow = false;
	if(null != oChild.className  && oChild.tagName == "DIV" && (oChild.className == "FormElement" || oChild.className.indexOf("FormElement ") >= 0))
	{
		//This is a form element
		if(typeof(oChild.IsHidden) == "undefined")
		{
			//alert(oChild.outerHTML);
			bShow = true; //Find one that needs to be shown means show the section
		}
	}
	else
	{
		//Go deeper to find a form element
		for(var i = 0; i < oChild.childNodes.length && false == bShow; i++)
		{
			var oChildChild = oChild.childNodes[i];
			bShow = ProcessFormSectionChild(oChildChild);
		}
	}
	return bShow;	
}

function ApplyInformationalRule(oFieldAffected, oRule)
{
	var oParam = oRule.selectSingleNode("Param");
	if(null != oParam)
	{
		var strValue = oParam.getAttribute("Param");
		oFieldAffected.setAttribute("InformationalPriority", oRule.getAttribute("Priority"));
		oFieldAffected.setAttribute("InformationalValue", strValue);
		oFieldAffected.setAttribute("InformationalRuleID", oRule.getAttribute("ID"));

		var oControl = document.getElementById(oFieldAffected.getAttribute("ClientID"));
		if(null != oControl)
		{
			var varImg = document.createElement("IMG");
			varImg.src = "Themes/Default/images/node.gif";
			varImg.title = strValue;
			if(oControl.insertAdjacentElement)
			{
				oControl.insertAdjacentElement("afterEnd", varImg);
			}
			else
			{
				oControl.appendChild(varImg);
			}
		}
	}
}

function ApplyMandatoryRule(oFieldAffected, oRule)
{
	var oLabelDiv = null;
	if(oFieldAffected.getAttribute("DataTypeName") == "User")
	{
		var oControl = document.getElementById(oFieldAffected.getAttribute("ClientID"));
		var oControlObject = GetUserObject(oControl);
		if(null != oControlObject)
		{
			oLabelDiv = oControlObject.Label;
		}
	}
	if(null == oLabelDiv)
	{
		oLabelDiv = document.getElementById(oFieldAffected.getAttribute("ClientID")+ "Label");
	}
	if(null != oLabelDiv)
	{
		if("0" == oRule.selectSingleNode("Param").getAttribute("Param"))
		{
			//Do not make the field mandatory, do nothing
		}
		else
		{
			//Make the field mandatory
			oLabelDiv.innerText = oLabelDiv.innerText + " *";
		}
	}
}

function ApplyReadOnlyRule(oFieldAffected, oRule)
{
	var oControl = document.getElementById(oFieldAffected.getAttribute("ClientID"));
	if(null == oControl && oField.getAttribute("DataTypeName") == "Date")
	{
	    oControl = igdrp_getComboById(oField.getAttribute("ClientID")); 
	}
	if(null != oControl)
	{
		var bEnable = ("0" != oRule.selectSingleNode("Param").getAttribute("Param"));
		var oControlObject = null;
		if(window.BizViewExtensionGetObject)
		{
			oControlObject = BizViewExtensionGetObject(oControl);
		}		
		if(null != oControlObject)
		{
			oControlObject.setReadOnly(bEnable);
		}
		else
		{
			if(oFieldAffected.getAttribute("DataTypeName") == "DateTime" || oFieldAffected.getAttribute("DataTypeName") == "Time")
			{
				var oControlObject = igedit_getById('x' + oFieldAffected.getAttribute("ClientID"));
				if(null != oControlObject)
				{
					oControlObject.setEnabled(!bEnable);
					//oControlObject.setReadOnly(bEnable);
				}
			}
			else if(oFieldAffected.getAttribute("DataTypeName") == "Date")
			{
				var oControlObject = oControl;
				if(null != oControlObject)
				{
					oControlObject.setEnabled(!bEnable);
					//oControlObject.setReadOnly(bEnable);
				}
			}
			else if(oFieldAffected.getAttribute("DataTypeName") == "User")
			{
				var oControlObject = GetUserObject(oControl);
				if(null != oControlObject)
				{
					oControlObject.setReadOnly(bEnable);
				}
			}
			else
			{
				//Readonly does not seem to work on radio buttons
				oControl.disabled = bEnable;
//				oControl.readonly = bEnable;
			}
		}
	}
}

function ApplyValueRule(oField, oRule, bExecuteBehaviourRules)
{
	try
	{
		var oControl = document.getElementById(oField.getAttribute("ClientID"));
		if(null == oControl && oField.getAttribute("DataTypeName") == "Date")
		{
		    oControl = igdrp_getComboById(oField.getAttribute("ClientID")); 
		}
		//alert("ApplyValueRule(" + oField.xml + ", " + oRule.xml + ", " + bExecuteBehaviourRules + ")\ncontrol: " + oField.getAttribute("ClientID"));
		var oParam = oRule.selectSingleNode("Param");
		if(null != oControl && null != oParam)
		{
			var oControlObject = null;
			if(window.BizViewExtensionGetObject)
			{
				oControlObject = BizViewExtensionGetObject(oControl);
			}
			if(null != oControlObject)
			{
				//Nota objectiš
				oControlObject.setValueRule(oField, oParam);
			}
			else
			{
				if(oField.getAttribute("DataTypeName") == "DateTime" || oField.getAttribute("DataTypeName") == "Time")
				{	
					oControlObject = igedit_getById('x' + oField.getAttribute("ClientID"));
					if(null != oControlObject)
					{
						var strParam = oParam.getAttribute("Param");
						var dtValue = "";
						if(null != strParam)
						{
							dtValue = XmlDateToDate(oParam.getAttribute("Param"));
						}
						oControlObject.setDate(dtValue);
					}
				}
				else if(oField.getAttribute("DataTypeName") == "Date")
				{				   
					oControlObject = oControl;
					if(null != oControlObject)
					{
						var strParam = oParam.getAttribute("Param");
						var dtValue = "";
						if(null != strParam)
						{
							dtValue = XmlDateToDate(oParam.getAttribute("Param"));
						}
						oControlObject.setValue(dtValue);
					}
				}
				else if(oField.getAttribute("DataTypeName") == "User")
				{
					oControlObject = GetUserObject(oControl);
					if(null != oControlObject)
					{
						oControlObject.setValueRule(oField, oParam);
					}
				}
				else
				{
					if(oControl.tagName == "TABLE")
					{
						//Dealing with a list of inputs in a table, check box or radio buttons										
	//					alert("oParam.getAttribute('Param') == " + oParam.getAttribute("Param"));
						var oL = oField.selectSingleNode("List/L[@ID = '" + oParam.getAttribute("Param") + "']");
						if(null != oL)
						{
							var oInputs = oControl.getElementsByTagName("INPUT");
							for(var i = 0; i < oInputs.length; i++)
							{
								if(oL.getAttribute("N") == oInputs[i].parentNode.innerText)
								{
									//For checkboxes and radio buttons only the text is available client side
									oInputs[i].checked = true;
									//oInputs[i].selected = true;
								}
							}
						}
						else if(null == oParam.getAttribute("Param") || oParam.getAttribute("Param") == "")
						{
							//Clearing all values
							var oInputs = oControl.getElementsByTagName("INPUT");
							for(var i = 0; i < oInputs.length; i++)
							{
								oInputs[i].checked = false;
								//oInputs[i].selected = false;
							}
						}
					}
					else if(oControl.tagName == "SPAN")
					{
						oControl.innerHTML = oParam.getAttribute("Param");
					}
					else if(oControl.tagName == "SELECT")
					{
						var newValue = oParam.getAttribute("Param");
						if(null == newValue)
						{
							// Clearing a combo value.
							// The first item of a combo should have a dummy item to
							// represent a blank value with a text like "[Select value]"
							oControl.selectedIndex = 0;
						}
						else
						{
							oControl.value = newValue;
						}
					}
					else
					{
						oControl.value = oParam.getAttribute("Param");
					}
				}
			}
			if(bExecuteBehaviourRules)
			{
				oRuleXs = m_oXmlForm.selectNodes("/root/Form/BehaviourRules/Rule[@SourceFieldID = '" + oField.getAttribute("ID") + "']");
				ExecuteBehaviourRules(oRuleXs);
			}
		}
	}
	catch(e)
	{
		alert("Exception(ApplyValueRule): " + e.description);
	}
}

/*
function ChangeFieldValue(oField, strValue, bExecuteBehaviourRules)
{
	var oControlObject = null;
	if(window.BizViewExtensionGetObject)
	{
		oControlObject = BizViewExtensionGetObject(oControl);
	}		
	if(null != oControlObject)
	{
		//Nota objectiš
		oControlObject.setValue(strValue);
	}
	else
	{
		if(oField.getAttribute("DataTypeName") == "DateTime" || oField.getAttribute("DataTypeName") == "Date" || oField.getAttribute("DataTypeName") == "Time")
		{
			var oControlObject = igedit_getById('x' + oField.getAttribute("ClientID"));
			if(null != oControlObject)
			{
				oControlObject.setDate(strValue);
			}
		}
		else
		{
			var oControl = document.getElementById(oField.getAttribute("ClientID"));
			if(null != oControl)
			{
				oControl.value = strValue;
			}
		}
	}
	if(bExecuteBehaviourRules)
	{
		oRuleXs = m_oXmlForm.selectNodes("/root/Form/BehaviourRules/Rule[@SourceFieldID = '" + oField.getAttribute("ID") + "']");
		ExecuteBehaviourRules(oRuleXs);
	}
}
*/

function ClearFieldValue(oField, bExecuteBehaviourRules)
{
	try 
	{
		var oControl = document.getElementById(oField.getAttribute("ClientID"));
		if(null == oControl && oField.getAttribute("DataTypeName") == "Date")
		{
		    oControl = igdrp_getComboById(oField.getAttribute("ClientID")); 
		}
		if(null != oControl)
		{
			var oControlObject = null;
			if(window.BizViewExtensionGetObject)
			{
				oControlObject = BizViewExtensionGetObject(oControl);
			}		
			if(null != oControlObject)
			{
				oControlObject.setValue(null);
			}
			else
			{
				if(oField.getAttribute("DataTypeName") == "DateTime" || oField.getAttribute("DataTypeName") == "Time")
				{
					oControlObject = igedit_getById('x' + oField.getAttribute("ClientID"));
					if(null != oControlObject)
					{
						oControlObject.setDate("");
					}
				}
				else if(oField.getAttribute("DataTypeName") == "Date" )
				{
					oControlObject = oControl;
					if(null != oControlObject)
					{
						oControlObject.setValue("");
					}
				}
				else if(oField.getAttribute("DataTypeName") == "User")
				{
					oControlObject = GetUserObject(oControl);
					if(null != oControlObject)
					{
						oControlObject.setValue(null);
					}
				}
				else
				{
					oControl.value = "";
				}
			}
			if(bExecuteBehaviourRules)
			{
				oRuleXs = m_oXmlForm.selectNodes("/root/Form/BehaviourRules/Rule[@SourceFieldID = '" + oField.getAttribute("ID") + "']");
				ExecuteBehaviourRules(oRuleXs);
			}
		}
	}
	catch(e)
	{
		alert("Exception(ClearFieldValue): " + e.description);
	}
}

function GetDateControlValue(oField)
{
	var varValue = null; //Null means, nothing to check, "" means the empty value
	if(typeof(GetDateControlValueExtended) != "undefined")
	{
		//There is a custom value function
		varValue = GetDateControlValueExtended(oField);
	}
	if(null == varValue)
	{
		var oControlObject = null;
		if(oField.getAttribute("DataTypeName") == "Date")
		{
		    oControlObject = igdrp_getComboById(oField.getAttribute("ClientID")); 
		    if(null != oControlObject)
		    {
			    var dtValue = oControlObject.getValue();
			    if(null != dtValue)
			    {
				    varValue = dtValue.toString();
			    }
		    }
		}
		else
		{
    		oControlObject = igedit_getById('x' + oField.getAttribute("ClientID")); //oFieldSource.getAttribute("ClientID"), null);
		    if(null != oControlObject)
		    {
			    var dtValue = oControlObject.getDate();
			    if(null != dtValue)
			    {
				    varValue = dtValue.toString();
			    }
		    }
		}
		
		
	}
	return varValue;
}

function GetHtmlControlValue(oField)
{	
//    alert("GetHtmlControlValue()\n" + oField.xml);
	var varValue = null; //Null means, nothing to check, "" means the empty value
	if(typeof(GetHtmlControlValueExtended) != "undefined")
	{
		//There is a custom value function
		varValue = GetHtmlControlValueExtended(oField);
	}
	if(null == varValue)
	{
		switch(oField.getAttribute("DataTypeName"))
		{
			case "User":
				var oControl = document.getElementById(oField.getAttribute("ClientID"));
				var oControlObject = GetUserObject(oControl);

				if(null != oControlObject)
				{
					//alert("About to get id from user control");
					//alert(oField.xml);
					varValue = oControlObject.getValueID();
					//alert("Value id from user control was: " + varValue);
				}
				else
				{
					//User lookup is implemented with a combo box, check for that scenario
					varValue = oControl.value;
				}
				break;
			default:
				var oControl = document.getElementById(oField.getAttribute("ClientID"));
				if(null != oControl)
				{
					if(oControl.tagName == "TABLE")
					{
			//			alert("oControl: " + oControl.outerHTML);
						var oInputs = oControl.getElementsByTagName("INPUT");
						for(var i = 0; i < oInputs.length; i++)
						{
							var varSingleValue = null;
							if(oInputs[i].checked) // || oInputs[i].selected)
							{
								//For checkboxes and radio buttons only the text is available client side
								var strText = oInputs[i].parentNode.innerText;
								var oL = oField.selectSingleNode("List/L[@N = '" + strText + "']");
								if(null != oL)
								{
									varSingleValue = oL.getAttribute("ID");
			//						alert("TABLE element, value: " + varValue + "\nText: " + strText);
								}
								if(varValue == null)
								{
									varValue = varSingleValue;
								}
								else
								{
									varValue = varValue + ", " + varSingleValue;
								}
							}
						}
						if(null != varValue && "" != varValue) // && varValue.indexOf(", ") == varValue.length - 2)
						{
//							varValue = varValue.substring(0, varValue.length - 2);
//							alert(varValue);
						}
						if(null == varValue && oInputs.length > 0)
						{
							//There were values, but none of them selected
							varValue = "";
						}
					}
					else
					{
						varValue = oControl.value;
					}
				}
				break;			
		}
	}
	return varValue;
}

function MasterValidator(val)
{
    var ret = true;
    ret = RunFieldValidation(val.FieldID);
	return ret;
}

function RunFieldValidation(iFieldID)
{
	if(null != m_oXmlForm)
	{
		//Xml exists and is ready to use
		//Run all value modification rules that depend on this field
		if(typeof(iFieldID) != "undefined" && iFieldID != -1)
		{
			var oField = m_oXmlForm.selectSingleNode("/root/Form/Field[@ID = '" + iFieldID + "']");
			if(null != oField && oField.getAttribute("DataTypeName") != "MultiDocument")
			{				
				if(FieldHasValue(oField))
				{
					//This is conditional as it is not meant to happen to untouched fields when saving a document
					oField.setAttribute("UserHasChanged", "yes");
				}
				var oRuleXs = m_oXmlForm.selectNodes("/root/Form/ValueRules/Rule[@BehaviourSystemName = 'DefaultValue' and @SourceFieldID = '" + iFieldID + "']");
				ExecuteValueRules(oRuleXs, 'DefaultValue', 1, true);
				oRuleXs = m_oXmlForm.selectNodes("/root/Form/ValueRules/Rule[@BehaviourSystemName = 'ValueChange' and @SourceFieldID = '" + iFieldID + "']");
				ExecuteValueRules(oRuleXs, 'ValueChange', 1, true);
				oRuleXs = m_oXmlForm.selectNodes("/root/Form/BehaviourRules/Rule[@SourceFieldID = '" + iFieldID + "']");
				ExecuteBehaviourRules(oRuleXs);
			}
		}
	}
	return true;
}

function FieldHasValue(oField)
{
	try
	{
		var FieldValue = null;
		var oControl = document.getElementById(oField.getAttribute("ClientID"));
	    if(null == oControl && oField.getAttribute("DataTypeName") == "Date")
	    {
	        oControl = igdrp_getComboById(oField.getAttribute("ClientID")); 
	    }
		if(null != oControl)
		{
			var oControlObject = null;
			if(window.BizViewExtensionGetObject)
			{
				oControlObject = BizViewExtensionGetObject(oControl);
			}
			if(null != oControlObject)
			{
				FieldValue = oControlObject.getValue();
			}
			else
			{
				if(oField.getAttribute("DataTypeName") == "DateTime" || oField.getAttribute("DataTypeName") == "Time")
				{	
					oControlObject = igedit_getById('x' + oField.getAttribute("ClientID"));
					if(null != oControlObject)
					{
						FieldValue = oControlObject.getDate();
					}
				}
				else if(oField.getAttribute("DataTypeName") == "Date")
				{
					oControlObject = oControl;
					if(null != oControlObject)
					{
						FieldValue = oControlObject.getValue();
					}
				}
				else if(oField.getAttribute("DataTypeName") == "User")
				{
					oControlObject = GetUserObject(oControl);
					if(null != oControlObject)
					{
						FieldValue = oControlObject.getValueID();
					}
				}
				else
				{
					if(oControl.tagName == "TABLE")
					{
						//Dealing with a list of inputs in a table, check box or radio buttons										
						var oInputs = oControl.getElementsByTagName("INPUT");
						for(var i = 0; i < oInputs.length; i++)
						{
							if(null == FieldValue && oInputs[i].checked)
							{
								FieldValue = oInputs[i].parentNode.innerText;
							}
						}
					}
					else if(oControl.tagName == "SPAN")
					{
						FieldValue = oControl.innerHTML;
					}
					else if(oControl.tagName == "SELECT")
					{
						//First item in a combo is a substitute for empty value
						if(0 != oControl.selectedIndex)
						{
							FieldValue = oControl.value;
						}
					}
					else
					{
						FieldValue = oControl.value;
					}
				}
			}
		}
		if(null == FieldValue || "" == FieldValue)
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	catch(e)
	{
		alert("Exception(FieldHasValue): " + e.description);
	}
}

function MandatoryValidator(val)
{
    if(_suppressFieldValidationForKeyDown)
    {
        _suppressFieldValidationForKeyDown = false;
        return true;        
    }

	//alert("MandatoryValidator");
	if(null != m_oXmlForm) // && !m_bMandatoryValidatorDisabled)
	{
		//Xml exists and is ready to use
		//Run all value modification rules that depend on this field		
		var iFieldID = val.FieldID;
		if(typeof(iFieldID) != "undefined" && iFieldID != -1)
		{
			var oField = m_oXmlForm.selectSingleNode("/root/Form/Field[@ID = '" + iFieldID + "']");
			if(null != oField)
			{
				//Figure out if there is a mandatory rule that applies to this field
				if(null != oField.getAttribute("ExclusiveType") && oField.getAttribute("ExclusiveType") == "Mandatory" && oField.getAttribute("ExclusiveValue") == "1")
				{
//					alert("Mandatory field found: " + oField.xml);
					var strValue = GetHtmlControlValue(oField);
					if(null == strValue || "" == strValue || "null" == strValue)
					{
						return false;
					}
				}
				
				//Datebase validation on year in date fields
				//Standard validation happens inside the infragistisics control
				//This should rather be done in a special DatabaseYear validator
				if(null != oField.getAttribute("DataTypeName"))
				{
					var strDataType = oField.getAttribute("DataTypeName");
					if(strDataType == "DateTime")// || strDataType == "Time")
					{
						var oControlObject = igedit_getById('x' + oField.getAttribute("ClientID"));
						if(null != oControlObject)
						{
							if(null != oControlObject.getDate() && oControlObject.getDate().getFullYear() < m_dbMinYear)
							{
								//The year in this date field is to small for saving in database.
								return false;
							}
						}
					}
					else if(strDataType == "Date")
					{
						var oControlObject = igdrp_getComboById(oField.getAttribute("ClientID")); 
						if(null != oControlObject)
						{
							if(null != oControlObject.getValue() && oControlObject.getValue().getFullYear() < m_dbMinYear)
							{
								//The year in this date field is to small for saving in database.
								return false;
							}
						}
					}
				}
			}
		}
	}
	//In case of fall-through return true and let the server handle the validation
	return true;
}

function OnSubmitBizViewValidation()
{
	alert("OnSubmitBizViewValidation()");
}

function OpenDisabledFieldsForServer()
{
	var bOpenFields = true;
	var bValidationExists = false;
	if(null != window.ValidatorOnSubmit) // if validation function exists
	{
		bOpenFields = ValidatorOnSubmit();
		bValidationExists = true;
	}
	if(bOpenFields && null != window.m_oXmlForm)
	{
		// Enabled fields only if mandatory validator is successful
		// If this is always done the the validator could prevent postback
		// which would in turn leave all readonly fields enabled(open).
		// This means that the validation is run twice on submit.

		//Clean out information about behaviour rules, they will then be run again after the postback returns
		var oFieldList = m_oXmlForm.selectNodes("/root/Form/Field[@ExclusiveType]");
		var oField = oFieldList.nextNode();
		while(null != oField) //oExclusiveField)
		{
			oField.removeAttribute("ExclusiveType");
			oField.removeAttribute("ExclusivePriority");
			oField.removeAttribute("ExclusiveValue");
			oField.removeAttribute("ExclusiveRuleID");
			
			try
			{
				var oControl = document.getElementById(oField.getAttribute("ClientID"));
				if(null != oControl)
				{
					oControl.disabled = false; //Force disabled off, otherwise the field won't post its data
				}
			}
			catch(e)
			{
				//alert(e.description);
			}

			oField = oFieldList.nextNode();
		}
		oFieldList = m_oXmlForm.selectNodes("/root/Form/Field[@DisableWritePermission = '1']");
		oField = oFieldList.nextNode();
		while(null != oField)
		{
			try
			{
				var oControl = document.getElementById(oField.getAttribute("ClientID"));
				if(null != oControl)
				{
					EnableControl(oControl);
				}
			}
			catch(e)
			{
				//alert(e.description);
			}
			oField = oFieldList.nextNode();
		}
		
		oFieldList = m_oXmlForm.selectNodes("/root/Form/Field[@ShowHidePriority]");
		oField = oFieldList.nextNode();
		while(null != oField) //oExclusiveField)
		{
			oField.removeAttribute("ShowHidePriority");
			oField.removeAttribute("ShowHideValue");
			oField.removeAttribute("ShowHideRuleID");
			
			oField = oFieldList.nextNode();
		}
		
		// Force disable off on text input of all user fields.
		// Else the username stored there may not be posted.
		oFieldList = m_oXmlForm.selectNodes("/root/Form/Field[@DataTypeName = 'User']");
		oField = oFieldList.nextNode();
		while(null != oField) //UserField
		{
			var oControl = document.getElementById(oField.getAttribute("ClientID"));
			if(null != oControl)
			{
				var oControlObject = GetUserObject(oControl);
				if(null != oControlObject && null != oControlObject.TextInput)
				{
					oControlObject.TextInput.disabled = false;
				}
			}
			oField = oFieldList.nextNode();
		}
		//Open user fields in sub-documents
		oFieldList = m_oXmlForm.selectNodes("/root/Form/Field/Form/Field[@DataTypeName = 'User']");
		oField = oFieldList.nextNode();
		var oMultiDocFieldControl = null;
		if(null != oField)
		{
			var oMultiDocField = oField.parentNode.parentNode;
			oMultiDocFieldControl = document.getElementById(oMultiDocField.getAttribute("ClientID"));
		}
		if(null != oMultiDocFieldControl)
		{
			try
			{
				var nodeList2 = oMultiDocFieldControl.getElementsByTagName("INPUT");
				for (var i = 0; i < nodeList2.length; i++) 
				{
					if(nodeList2[i].disabled)
					{
						nodeList2[i].disabled = false;
					}
				}
			}
			catch(e)
			{
				alert("Exception, enabling fields before postback: " + e.description);
			}
		}
	}
	else if(bValidationExists) //and the validation failed
	{
		// This allows the failed validator to be run locally again.
		Page_BlockSubmit = true;
	}
}

function EnableControl(oControl)
{
	oControl.disabled = false; //Force disabled off, otherwise the field won't post its data
	for(var i = 0; i < oControl.childNodes.length; i++)
	{
		EnableControl(oControl.childNodes[i]);
	}

}

function UpdateFormXmlForServer()
{
	var oFormXmlElement = document.getElementById(m_strBaseControlName + "_FormXml");
	if(null != oFormXmlElement)
	{
		//Encode XML. <> are converted to curly braces {}
		oFormXmlElement.value = m_oXmlForm.xml.replace(/</g, "{").replace(/>/g, "}");
	}
}

function OnLookupKeyDownSimple(oControl, buttonId)
{
	if(window.event.keyCode == 13)
	{
		if(null != oControl && typeof(oControl.id) != "undefined")
		{
			var button = document.getElementById(buttonId);
			if(null != button)
			{
				m_strActiveLookupFieldId = oControl.id;
				m_strActiveLookupButtonFieldName = button.name;
			}
		}
	}
}

function OnLookupKeyDown(oControl)
{
	// Activate the default button of the UserLookup control (or other controls)
	if(window.event.keyCode == 13)
	{
		//Try first to handle extension object
		var oLookupObject = null;
		if(window.BizViewExtensionGetObject) // Check for extension input (originally ServiceLookup)
		{
			oLookupObject = BizViewExtensionGetObject(oControl);
		}
		if(null != oLookupObject)
		{
			// Handling for extension lookup (originally ServiceLookup)
			if(null != oLookupObject.getFocusInput())
			{
				m_strActiveLookupFieldId = oLookupObject.getFocusInput().id;
			}
			if(null != oLookupObject.getActionInput())
			{
				m_strActiveLookupButtonFieldName = oLookupObject.getActionInput().name;
			}
			//alert("Action button: " + m_strActiveLookupButtonFieldName);
			return true;
		}
		else // Try as user lookup object
		{
			oLookupObject = GetUserObject(oControl);
			if(null != oLookupObject)
			{
				if(oLookupObject.SearchButton.className.indexOf("Hidden") < 0)
				{
					m_strActiveLookupFieldId = oLookupObject.getFocusInput().id;
					m_strActiveLookupButtonFieldName = oLookupObject.SearchButton.name;					
					_suppressFieldValidationForKeyDown = true;
					return true; //Allow postback
				}
				else if (oLookupObject.CurrentButton.className.indexOf("Hidden") < 0)
				{
					CurrentUserLookup(oLookupObject.CurrentButton);
					return false; //Stop postback
				}
				else if (oLookupObject.ClearButton.className.indexOf("Hidden") < 0)
				{
					ClearUserLookup(oLookupObject.ClearButton);
					return false; //Stop postback
				}
			}
		}
	}
	return true;
}

function ClearUserLookup(oControl)
{
	var oControlObject = GetUserObject(oControl);
	if(null != oControlObject)
	{
		oControlObject.setValue(null);
		oControlObject.setFocus();
		//RunFieldValidation will mark the field as user has changed only if it is getting a value
		// Fix it here so it is marked as userhaschanged, this prevents default value rules from running on it again
		if(typeof(oControlObject.FieldID) != "undefined" && oControlObject.FieldID != -1)
		{
			var oField = m_oXmlForm.selectSingleNode("/root/Form/Field[@ID = '" + oControlObject.FieldID + "']");
			if(null != oField)
			{				
				oField.setAttribute("UserHasChanged", "yes");
			}
		}		
		RunFieldValidation(oControlObject.FieldID);
	}
	return false; //Prevent postback
}

function CurrentUserLookup(oControl)
{
	var oControlObject = GetUserObject(oControl);
	if(null != oControlObject)
	{
		//Get user information from field data - OK as long as not UIType = UserLookup
		var oUser = m_oXmlForm.selectSingleNode("/root/Form/Field[@ID = '" + oControlObject.FieldID + "']/U | /root/Form/Field/Form/Field[@ID = '" + oControlObject.FieldID + "']/U");
//		var oUser = m_oXmlForm.selectSingleNode("/root/Form/Field/Form/Field[@ID = '74']/U");
//		alert("oUser: " + oUser + "\noControlObject.FieldID: " + oControlObject.FieldID + "\nm_oXmlForm:" + m_oXmlForm.xml);
		//alert("m_oXmlForm.selectSingleNode: " + m_oXmlForm.selectSingleNode("/root/Form/Field/Form/Field[@ID = '" + oControlObject.FieldID + "']/U").xml + "\nm_oXmlForm:" + m_oXmlForm.xml);
		oControlObject.setValue(oUser);
		oControlObject.setFocus();
		RunFieldValidation(oControlObject.FieldID);
	}
	return false; //Prevent postback
}

function InfoUserLookup(oControl)
{
	//alert("InfoUserLookup");
	var oControlObject = GetUserObject(oControl);
	if(null != oControlObject && null != oControlObject.InfoTable)
	{
		if(oControlObject.InfoTable.className.indexOf("Hidden") < 0)
		{
			//Just hide the information table
			oControlObject.InfoTable.className = oControlObject.InfoTable.className + " Hidden";
			return false; //Prevent postback
		}
		else
		{
			//Show the information table
			oControlObject.InfoTable.className = oControlObject.InfoTable.className.replace(/Hidden/g, "");
			return false; //Prevent postback
		}
	}
	else
	{
		return true; //Allow postback
	}
}


//Client side validation fixed like this for the Infragistics control
function InfragisticsDateTimeValueChange(oEdit, oldValue, oEvent) 
{
    
	var iIndex = 10;
	var varParentElement = event.srcElement;
	while(null != varParentElement && iIndex-- > 0)
	{	
//		alert(varParentElement.outerHTML);
		if(typeof(varParentElement.FieldID) != "undefined")
		{
			RunFieldValidation(varParentElement.FieldID);
			return;
		}
		varParentElement = varParentElement.parentNode;
	}
}

function OnDefaultButtonKeyDown(strButtonName)
{
	if(event.keyCode == 13 && strButtonName != "")
	{
		//Pressing enter, do nothing, just cancel the Enter by changing the keycode to something harmless
		// to prevent submitting of the form
		event.keyCode = 9; //Horizontal tab, harmless keycode
	}
}

function OnButtonClick()
{
	if(typeof(event.srcElement.FieldID) != "undefined")
	{
		//Get the configuration XML for this button and see if there is any custom action 
		// to perform
		var oField = m_oXmlForm.selectSingleNode("/root/Form/Field[@ID = '" + event.srcElement.FieldID + "'] | /root/Form/Field/Form/Field[@ID = '" + event.srcElement.FieldID + "']");
		if(null != oField)
		{
			var paramString = oField.getAttribute("Param");
			if(null != paramString && "" != paramString)
			{
				var paramXml = new ActiveXObject("MSXML2.DOMDocument");
				paramXml.async = false;
				paramXml.loadXML(paramString);
				paramXml.setProperty("SelectionLanguage", "XPath");
				var param = paramXml.selectSingleNode("/root/Param[@Name = 'Action']");
				if(null != param)
				{
//					alert(param.xml);
				}
			}
		}
	}
}

function OpenPrintDialog(docPath, editWindow, ewHeight, ewWidth, resizable, status, scroll)
{
	if(window.showModalDialog)
	{
		var retval = window.showModalDialog(docPath + '/DlgBox.html','scrolling="'+scroll+'" src="'+editWindow+'"','dialogHeight:'+ewHeight+'px; dialogWidth:'+ewWidth+'px; center:yes; resizable:'+resizable+';help:no; minimize:no; maximize:no; status:'+status+'; border:thin');
	}
	else
	{
		sWinFeat = 'width='+ewWidth+'px,height='+ewHeight+'px;' 
		if(ewWidth != null && ewHeight != null)
		{
			sWinFeat += ',screenY='+((screen.availHeight-ewHeight)/2)+','; 
			sWinFeat += 'screenX='+((screen.availWidth-ewWidth)/2)+''; 
		} 
		var modalWin = window.open('/NetQbsDev/admin/Dialogs/DlgBox.html','',sWinFeat);
		window.onfocus = function() 
		{
			if(modalWin && typeof(modalWin.closed) != 'unknown' && !modalWin.closed)
			modalWin.focus();
		}
		modalWin.dialogArguments = editWindow; 
		return false;
	}
}

function DoPrint(docPath, moduleId, moduleDefId, moduleTabsId, docId) //printContentsDiv, iFrameName)
{
	//Open the print dialog box
    OpenPrintDialog(docPath, docPath + "/PrintDocument.aspx?ModuleId=" + moduleId + "&ModuleDefId=" + moduleDefId + "&ModuleTabsId=" + moduleTabsId + "&DocID=" + docId + "&PrintLayout=yes","600","850","no","no","yes");
	//OpenPrintDialog(docPath + "/PrintDocument.aspx?ModuleId=" + moduleId + "&ModuleDefId=" + moduleDefId + "&ModuleTabsId=" + moduleTabsId + "&DocID=" + docId + "&PrintLayout=yes","600","850","no","no");

//	var printFrame = document.frames["printFrame"];
//	if(null == printFrame || typeof(printFrame) == "undefined")
//	{
//		var tempIFrame = document.createElement('iframe');
//		tempIFrame.setAttribute('id','printFrame');
//		tempIFrame.style.border='0px';
//		tempIFrame.style.width='0px';
//		tempIFrame.style.height='0px';
//		document.body.appendChild(tempIFrame);      

//		printFrame = document.frames["printFrame"];
/*		
		var contents = document.getElementById(printContentsDiv);
		if(null != contents)
		{
			var win = window.open('', 'printerWindow', 'width=600,height=600,resizable,scrollbars=yes,toolbar=no,menubar=no');
			
			var heads = document.getElementsByTagName("HEAD");
			var headString = ""; //if LINK elements are in the HEAD the IFRAME doesn't print properly
			for(var i = 0; i < heads[0].children.length; i++)
			{
				if(heads[0].children[i].tagName == "TITLE" || heads[0].children[i].tagName == "LINK" )
				{						
					headString = headString + heads[0].children[i].outerHTML;
				}
			}
			win.document.open();
			win.document.write("<html><head>" + headString + "</head><body>" + contents.outerHTML + "</body></html>");
			win.document.close();
			win.focus();
			win.print();
//			win.close();	
		}		
		
*/
/*		printFrame = document.frames[iFrameName];
		if(null != printFrame)
		{
	//		printFrame.navigate("HTMLPage2.htm");
			var contents = document.getElementById(printContentsDiv);
			if(null != contents)
			{
				var heads = document.getElementsByTagName("HEAD");
				printFrame.document.open();		
				printFrame.document.write("<html><head>" + headString + "</head><body>" + contents.outerHTML + "</body></html>");
				printFrame.document.close();
				printFrame.focus();
				printFrame.print();
			}
		}
*/
//	}
}

//---------------------------------- Utility functions ----------------------------------
function XmlDateToDate(strValue)
{
	re = /-/g;
	var strValue = strValue.replace(re, "/");
	re = /T/g;
	strValue = strValue.replace(re, " ");	
	//2004-04-07T10:11:12
	strValue = strValue.substring(0, 16); //Cut off the seconds
	return new Date(strValue);				
}

function isNumericKeyStroke(isFloat)
{
	var returnValue = false;
	var keyCode = (window.event.which) ? window.event.which : window.event.keyCode;

	if ( ((keyCode >= 48) && (keyCode <= 57)) || // All numerics
		(keyCode ==  8) ||     // Backspace
		(keyCode == 13) ||	   // Carriage Return
		(true == isFloat && keyCode == 46)) //Period
	{
		returnValue = true;
	}
	window.event.returnValue = returnValue;
	return returnValue;
}


