var ActionType = {
    PossibleValues: 0,
    SetValues: 1,
    HiddenFields: 2,
    VisibleFields: 7,
    Hidden_Tabs: 8,
    Required_Fields: 9,
    Disabled_Fields: 10,
    SetURLDynamicValues: 11,
	Disabled_Ticket: 22,
    CustomAction: 99
}

function MqDependentFields(objFieldCollection, strFieldsHTMLContainer, objMqAutoList, oHTTPReq, strExtraHTMLContainers, iRuleID) 
{
    var arrCachedDependencies = new Array();
    var ARR_TEXT = 1;
    var ARR_VALUE = 0;
    var ARR_URL = 0;
    var ARR_OUTPUT = 1;
    var INDEX_FIELD_ID = 0;
    var INDEX_FIELD_NAME = 1;
    var INDEX_ACTION_TYPE = 2;
    var INDEX_FORM_ELEM_OBJ = 3;
    var INDEX_INIT_VALUES = 4;

    // Condition Field array elements
    var IDX_COND_DEF_VALUE = 3;
    var IDX_COND_ALT_VALUE = 4;
    var IDX_COND_GETTEXT = 5;

    var INDEX_RET_FIELD_NAME = 0;
    var INDEX_RET_FIELD_VALUES = 1;
    var DELIMITER = ";";
    var LESS_THAN = "<";
    var GREATER_THAN = ">"
    var CUSTOM_URL_COND = "Custom URL";
    var AMPERSAND = "&";
    var DELIMITER_HTML_CONTAINER = ',';

    //private properties
    var m_arrTargetFields;
    var m_arrCondFields;
    var m_arrLocalConditions;
    var m_strURLName;
    var m_strURL_External_Resource="";
    var m_blnSelectFirstValue = true;
    var m_blnInitialized = false;
    var m_strTableName;
    var m_fDisplayCurrentValue = true;
	var m_strRuleDefs = "";
    var m_strFieldsHTMLContainer;
    var m_strFieldsExtraHTMLContainers;
    var m_oHTTPReq;
    var m_blnLinkFldValsByID;
    var m_objMqAutoList;
    var m_arrIssueHiddenFlds;
    var m_arrIssueVisibleFlds;
    var m_strHiddenTabs = "";
    var m_arrIssueReqFlds;
    var m_arrIssueDisabledFlds;
    var m_oDisplayElements;
    var m_blnEnabled = true;
    var m_strGlobalID = "";
    var m_blnTriggerOnLoadRec = true;
	var m_blnTriggerOnSaveRec = true;
	var m_iRuleID=iRuleID;
	
    if (oHTTPReq) {
        m_oHTTPReq = oHTTPReq;
    } else {
        m_oHTTPReq = objRequest;
    }

    m_strFieldsHTMLContainer = strFieldsHTMLContainer;
    m_strFieldsExtraHTMLContainers = strExtraHTMLContainers;

    var m_objFields = objFieldCollection;
    m_objMqAutoList = objMqAutoList;
    var m_oFldAcc = new CMqFldAcc(objFieldCollection, strFieldsHTMLContainer);

    function Initialize(arrTargetFields, arrCondFields, strSourcePage,strTableName, blnLinkFldValsByID, objDisplayElements, arrLocalConditions,
							strURL_External_Resource) {

        if (!m_blnInitialized) {
            m_arrTargetFields = arrTargetFields;
            m_arrCondFields = arrCondFields;
            m_arrLocalConditions = arrLocalConditions;
            m_strURLName = strSourcePage;
            m_strTableName = strTableName;
            m_blnLinkFldValsByID = blnLinkFldValsByID;
            m_oDisplayElements = objDisplayElements;
			if(typeof(strURL_External_Resource)!="undefined"){
				m_strURL_External_Resource = strURL_External_Resource;
			}
        }

        //initialize the target values, this happens only once
        InitializeTargetValues(m_objFields, m_strFieldsHTMLContainer);

    }

    function InitializeTargetFields() {
        //initialize the target values, this happens only once
        InitializeTargetValues(m_objFields, m_strFieldsHTMLContainer);

    }

	function GetTargetValues(strCondFields)
	{
		var strTargetFields = GetActionFieldsQryStr();
		
		return ResolveActionRule(strCondFields, strTargetFields);
	}

    function SetDependentField(rsOrigFldVals, blnOnFieldChange, blnVerifyCondFldsExist, strTriggerFieldID) 
    {
		
		if (m_blnEnabled)
		{
	        if (EvalLocalConditions()) {
				if (typeof(blnOnFieldChange)=="undefined")
				{
					blnOnFieldChange=true;
				}

	            WriteConsole("[Dependent Fields] Executing biz rule [" + m_iRuleID + "]. Using source: " + m_strURLName + " , and table: " + m_strTableName);
	
	            var strCondFields = GetConditionFieldsQryStr(m_objFields, m_strFieldsHTMLContainer, rsOrigFldVals, blnVerifyCondFldsExist);
	
	            WriteConsole("[Dependent Fields] Biz rule [" + m_iRuleID + "]. Condition Fields: " + strCondFields);
	
				// We check if the rule should be enabled or not in the GetConditionFieldsQryStr, so check again if rule should be executed
				if (m_blnEnabled)
				{
		
		            var strTargetFields = GetActionFieldsQryStr();
		
		            WriteConsole("[Dependent Fields] Biz rule [" + m_iRuleID + "]. Action Fields: " + strTargetFields);
		
		            var strTargetValues = ResolveActionRule(strCondFields, strTargetFields);
		
					WriteConsole("[Dependent Fields] Biz rule [" + m_iRuleID + "]. Returned Actions: " + g_MqRef.MqStr.MqDecodeURIComponent(g_MqRef.MqStr.MqDecodeURIComponent(strTargetValues)));


		            switch (GetValueActionType(strTargetFields)) {
		                case ActionType.HiddenFields:
		                    MakeFieldsHidden(strTargetValues, m_strFieldsHTMLContainer);
		                    break;
		                case ActionType.Required_Fields:
		                    MakeFieldsRequired(strTargetValues, m_strFieldsHTMLContainer);
		                    break;
		                case ActionType.Hidden_Tabs:
		                    FixTabs(strTargetValues, m_strFieldsHTMLContainer);
		                    break;
		                case ActionType.Disabled_Fields:
		                    MakeFieldsDisabled(strTargetValues, m_strFieldsHTMLContainer);
		                    break;
		                case ActionType.CustomAction:
		                    DoCustomAction(strTargetValues, m_strFieldsHTMLContainer, blnOnFieldChange, strTargetFields);
		                    break;
		                case ActionType.VisibleFields:
		                    MakeFieldsVisible(strTargetValues, m_strFieldsHTMLContainer);
		                    break;
		                case ActionType.SetURLDynamicValues:
		                    SetValueOnTargetField(strTargetValues, m_objFields, blnOnFieldChange);
		                    break;
		                case ActionType.SetValues:
							setTargetValues(strTargetValues, this.DisplayCurrentValue, m_objFields, m_strFieldsHTMLContainer, blnOnFieldChange, strTriggerFieldID);
		                    break;
		                case ActionType.PossibleValues:
		                    setTargetValues(strTargetValues, this.DisplayCurrentValue, m_objFields, m_strFieldsHTMLContainer, blnOnFieldChange, strTriggerFieldID);
		                    break;
						case ActionType.Disabled_Ticket:
							SetTicketDisabled(strTargetValues, m_strFieldsHTMLContainer);
							break;
		                default:
		                    setTargetValues(strTargetValues, this.DisplayCurrentValue, m_objFields, m_strFieldsHTMLContainer, blnOnFieldChange, strTriggerFieldID);
		                    break;
		            }
	
	
		            WriteConsole("[Dependent Fields] Finished executing biz rule [" + m_iRuleID + "].");
		
		            return true;
	   			}else{

					//g_MqRef.Deb.SetEnableLog(true);
				   	WriteConsole("[Dependent Fields] Rule was not executed because it is now disabled. Source: " + m_strURLName + " , and table: " + m_strTableName);
				}		           
	        }
	   }else{
	   
			WriteConsole("[Dependent Fields] Rule was not executed because it is disabled. Source: " + m_strURLName + " , and table: " + m_strTableName);
	   }
	   

    }

    function EvalLocalConditions() {
        var blnResult = false;
        if (typeof m_arrLocalConditions === "undefined") {
            blnResult = true;
        }
        else {
            for (i = 0; i < m_arrLocalConditions.length; i++) {

                var fnDynamicFunction = new Function(m_arrLocalConditions[i].Condition);

                if (fnDynamicFunction() == m_arrLocalConditions[i].ExpectedValue) {
                    blnResult = true;
                }
                else {
                    blnResult = false;
                }
            }
        }
        return blnResult;
    }

    function GetActionType() {
        var lngActionType = -1;

        if (m_arrTargetFields) {
            if (m_arrTargetFields[0]) {
                if (m_arrTargetFields[0][INDEX_ACTION_TYPE]) {
                    lngActionType = m_arrTargetFields[0][INDEX_ACTION_TYPE];

                }
            }
        }
        //WriteConsole("[Dependent Fields] lngActionType: " + lngActionType);
        return lngActionType;
    }

    function GetValueActionType(strActionType) {

        if (strActionType == ";" || strActionType == "") {
            return GetActionType();
        }
        else {
            switch (strActionType) {
                case "Visible_Fields":
                    return ActionType.VisibleFields;
                    break;
                case "Hidden_Fields":
                    return ActionType.HiddenFields;
                    break;
                case "Hidden_Tabs":
                    return ActionType.Hidden_Tabs;
                    break;

                case "Required_Fields":
                    return ActionType.Required_Fields;
                    break;

                case "Disabled_Fields":
                    return ActionType.Disabled_Fields;
                    break;

                case "CustomAction":
                    return ActionType.CustomAction;
                    break;

				case "Disabled_Ticket":
					return ActionType.Disabled_Ticket;
					break;
					
                default:
                    for (j = 0; j < m_arrTargetFields.length ; j++) {
                        if (m_arrTargetFields[j]) {
                            if (m_arrTargetFields[j][INDEX_ACTION_TYPE] == ActionType.PossibleValues) {
                                return ActionType.PossibleValues
                            }
                            else {
                                return ActionType.SetValues;
                            }
                        }
                    }
                    break;
            }
        }


    }

    function IsCustomAction() {
        var blnReturn = false;

        if (GetActionType() == ActionType.CustomAction) {
            blnReturn = true;
        }
        return blnReturn;
    }

    function SetOnChange(strFieldID, strFunction) {
        var oCtrl = m_oFldAcc.GetCtrl(strFieldID);
        if (oCtrl) {
            var strBody = "";
            if (oCtrl.onchange) {
                strBody = "var objFunction=" + oCtrl.onchange.valueOf() + ";" + "objFunction();" + strFunction;
            } else {
                strBody = strFunction;
            }
            var objFunc = new Function(strBody);
            oCtrl.onchange = objFunc;
        }
    }


    function GetIsSelectFirstValue() {
        return m_blnSelectFirstValue;
    }

    function SetIsSelectFirstValue(blnSelectFirstValue) {
        m_blnSelectFirstValue = blnSelectFirstValue;
    }

    function getTargetFieldIDs() {
        var strParams = "";
        var lngCount;
        var objParameterElement;

        for (lngCount = 0; lngCount < m_arrTargetFields.length; lngCount++) {
            if (m_arrTargetFields[lngCount]) {
                strParams += m_arrTargetFields[lngCount][INDEX_FIELD_ID] + DELIMITER;
            }
        }

        if (strParams.indexOf(DELIMITER) > 0) {
            strParams = strParams.substr(0, strParams.length - 1);
        }

        return strParams;
    }

    function getSourceFieldIDs() {
        var strParams = "";
        var lngCount;
        var objParameterElement;

        for (lngCount = 0; lngCount < m_arrCondFields.length; lngCount++) {
            if (m_arrCondFields[lngCount]) {
                strParams += m_arrCondFields[lngCount][INDEX_FIELD_ID] + DELIMITER;
            }
        }

        if (strParams.indexOf(DELIMITER) > 0) {
            strParams = strParams.substr(0, strParams.length - 1);
        }

        return strParams;
    }

    function SetEnabled(blnEnabled) {
        m_blnEnabled = blnEnabled;
    }

    function GetEnabled() {
        return m_blnEnabled;
    }

	function SetRuleDefs(strRuleDefs) {
        m_strRuleDefs = strRuleDefs;
    }

    function GetRuleDefs() {
        return m_strRuleDefs;
    }
	
    function GetGlobalID() {
        return m_strGlobalID;
    }

    function SetGlobalID(strGlobalID) {
        m_strGlobalID = strGlobalID;
    }

    function SetTriggerOnLoadRec(blnTriggerOnLoadRec) {
        m_blnTriggerOnLoadRec = blnTriggerOnLoadRec;
    }

    function GetTriggerOnLoadRec() {
        return m_blnTriggerOnLoadRec;
    }

	function SetTriggerOnSaveRec(blnTriggerOnSaveRec) {
        m_blnTriggerOnSaveRec = blnTriggerOnSaveRec;
    }

    function GetTriggerOnSaveRec() {
        return m_blnTriggerOnSaveRec;
    }
    // Public properties
    this.DisplayCurrentValue = m_fDisplayCurrentValue;
    this.SetEnabled = SetEnabled;
    this.GetEnabled = GetEnabled;
	this.SetRuleDefs = SetRuleDefs;
	this.GetRuleDefs = GetRuleDefs;
	
    //Public functions
    this.Initialize = Initialize;
    this.InitializeTargetFields = InitializeTargetFields;
    this.SetDependentField = SetDependentField;
    this.SetOnChange = SetOnChange;
    this.GetIsSelectFirstValue = GetIsSelectFirstValue;
    this.SetIsSelectFirstValue = SetIsSelectFirstValue;
    this.ValidateRequiredFields = ValidateRequiredFields;
    this.getTargetFieldIDs = getTargetFieldIDs;
    this.getSourceFieldIDs = getSourceFieldIDs;
    this.GetGlobalID = GetGlobalID;
    this.SetGlobalID = SetGlobalID;
    this.SetTriggerOnLoadRec = SetTriggerOnLoadRec;
    this.GetTriggerOnLoadRec = GetTriggerOnLoadRec;
	this.SetTriggerOnSaveRec = SetTriggerOnSaveRec;
    this.GetTriggerOnSaveRec = GetTriggerOnSaveRec;
	this.GetTargetValues=GetTargetValues;
	
    //private functions	


    function InitializeTargetValues(objFields, strFieldsHTMLContainer) {
        var i;
        if (!m_blnInitialized) {
            var objTargetElement;
            for (i = 0; i < m_arrTargetFields.length ; i++) {
                if (m_arrTargetFields[i]) {
                    objTargetElement = GetFormElement(m_arrTargetFields[i][INDEX_FIELD_ID], objFields, strFieldsHTMLContainer);
                    if (objTargetElement) {
                        m_arrTargetFields[i][INDEX_FORM_ELEM_OBJ] = objTargetElement;
                        m_arrTargetFields[i][INDEX_INIT_VALUES] = objTargetElement.GetPossibleValues();
                    }
                }
            }
            m_blnInitialized = true;
        } else {
            for (i = 0; i < m_arrTargetFields.length ; i++) {
                if (m_arrTargetFields[i]) {
                    if (m_arrTargetFields[i][INDEX_FORM_ELEM_OBJ]) {
                        if (m_arrTargetFields[i][INDEX_INIT_VALUES]) {
                            m_arrTargetFields[i][INDEX_FORM_ELEM_OBJ].SetPossibleValues(m_arrTargetFields[i][INDEX_INIT_VALUES]);
                        }
                    }
                }
            }
        }
    }



    function GetConditionFieldsQryStr(objFields, strFieldsHTMLContainer, rsOrigFldVals, blnVerifyFldsExist) 
    {
        var arrCondFields = m_arrCondFields;
        var strParams = "";
        var lngCount;
        var objParameterElement;
        var blnValidField;
        var objRSHelper = new CMqRSHelper();
        var strParameterElementValue;
        var c = 0;
        var arrExtraContainers;

		// m_strFieldsExtraHTMLContainers to check not null, not ""
        if (typeof (m_strFieldsExtraHTMLContainers) != 'undefined' && m_strFieldsExtraHTMLContainers) {
            arrExtraContainers = m_strFieldsExtraHTMLContainers.split(DELIMITER_HTML_CONTAINER);
        }

        for (lngCount = 0; lngCount < arrCondFields.length; lngCount++) 
        {
            blnValidField = false;
            if (arrCondFields[lngCount]) {


                var strFieldId = arrCondFields[lngCount][INDEX_FIELD_ID];
				var sCondName=arrCondFields[lngCount][INDEX_FIELD_NAME];

				blnValidField = IsValidDtsField(sCondName, strFieldId);

                var strAltValue = arrCondFields[lngCount][IDX_COND_ALT_VALUE];
                if (strAltValue != null) {
                    if (strAltValue != "") {
                        strAltValue = "|" + strAltValue;
                    }
                } else {
                    strAltValue = "";
                }

                if (blnValidField) {
                    objParameterElement = GetFormElement(strFieldId, objFields, strFieldsHTMLContainer);

                    if (objParameterElement) {
						
                        strParameterElementValue = objParameterElement.GetValue(null, null,
														null, arrCondFields[lngCount][IDX_COND_GETTEXT]);

                        if (strParameterElementValue == '') {
                            if ((!objParameterElement.GetElement()) && (typeof (m_strFieldsExtraHTMLContainers) != 'undefined' && m_strFieldsExtraHTMLContainers != '')) {
                                if(arrExtraContainers)
								{
									 while (c < arrExtraContainers.length && strParameterElementValue == '') {
                                    objParameterElement = GetFormElement(strFieldId, objFields, arrExtraContainers[c]);
                                    strParameterElementValue = objParameterElement.GetValue();

                                    c++;
									}
								}
                            }
                        }

                        blnValidField = false;
                        if (blnVerifyFldsExist) {
                            if (objParameterElement.GetElement()) {
                                blnValidField = true;
                            }
                        } else {
                            blnValidField = true;
                        }
                        if (blnValidField) {
                            strParams +=AddParam( sCondName, strParameterElementValue + strAltValue);
                            //strParams += arrCondFields[lngCount][INDEX_FIELD_NAME] + "=" +
							//		 strParameterElementValue + strAltValue + DELIMITER;

                        }
                    } else {
                        var strDefVal = "";
                        if (arrCondFields[lngCount][IDX_COND_DEF_VALUE]) {
                            strDefVal = arrCondFields[lngCount][IDX_COND_DEF_VALUE];
                        }
						// In what cases it is OK to send the default value?
						WriteConsole("Biz rule [" + m_iRuleID + "], condition field :" + strFieldId + " not found in the view." );

						m_blnEnabled=false;

                        strParams +=AddParam( sCondName, strDefVal);
                        //strParams += arrCondFields[lngCount][INDEX_FIELD_NAME] + "=" +
							//strDefVal + DELIMITER;
                    }
                    
                } else {
                    var strMacroCond = ResolveMacro(arrCondFields[lngCount], rsOrigFldVals, objRSHelper);
                    if (strMacroCond) {
                        strParams += strMacroCond + DELIMITER;
                        
                        
                    } else {
                    
                        strParams +=AddParam( sCondName, "");
                        //strParams += arrCondFields[lngCount][INDEX_FIELD_NAME] + "=" +
                        //    "" + DELIMITER;

                    }
                }
            }
        }

        return strParams;
    }

	function AddParam( sField, sValue)
	{
									
        var ret="";        
		if(sField!=="")
		{
			if(typeof(sValue)!="undefined")
			{
				ret= sField + "=" + window.encodeURIComponent(sValue) + DELIMITER;
			}
		}

		return ret;
	}		
	
	function IsValidDtsField(sCondName, sCondFieldID)
	{
		//var  MACRO_USER_IN_GROUP = "<User_In_Group>";
		var  PREFIX_MACRO_NOT_IN_GROUP = "_User_Not_In_Group_";
		var ret=false;
		
		if (sCondFieldID != null  && sCondFieldID!="") 
		{
			if (sCondName!=null) 
			{
				if (	sCondName.indexOf( PREFIX_MACRO_NOT_IN_GROUP, 0) != 0 ) 
				{
					ret=true;
				}
			}
		}
		return ret;
		
	}
	
    function ResolveMacro(oCondField, rsOrigFldVals, objRSHelper) {
        var strResolvedMacro = "";
        var VAL_YES = "1";
        var VAL_NO = "2";

        if (oCondField) {
            if (oCondField[INDEX_FIELD_NAME]) {
                var strMacroName = oCondField[INDEX_FIELD_NAME];

                if (strMacroName.toLowerCase() == g_MqRef.RESX["MACRO_NEW_ISSUE"].toLowerCase()) {
                    if(g_VWS.RecordMgr().CurrentRecord().IsNewRecord()){
                        strResolvedMacro = strMacroName + "=" + VAL_YES;
                    } else {
                        strResolvedMacro = strMacroName + "=" + VAL_NO;
                    }
                }
            }
        }
        return strResolvedMacro;
    }

    function GetActionFieldsQryStr() {
        var strParams = "";
        var lngCount;
        var objParameterElement;

        for (lngCount = 0; lngCount < m_arrTargetFields.length; lngCount++) {
            if (m_arrTargetFields[lngCount]) {
                strParams += m_arrTargetFields[lngCount][INDEX_FIELD_NAME] + DELIMITER;
            }

        }
        if (strParams.indexOf(DELIMITER) > 0) {
            strParams = strParams.substr(0, strParams.length - 1);
        }

        return strParams;

    }

    function ResolveActionRule(strCondFields, strTargetFields) {
		
		if(m_strURL_External_Resource!="")
        {
            var strURL=m_strURL_External_Resource + CleanConditionFields(strCondFields);

			if(g_MqRef.MqStr.Left(strURL, 1)=="/"){
				//assumption it's a local URL
				//add the beginning of the URL and the VD
				strURL=location.protocol + "//" + location.hostname + "/" + g_VWS.URL().BaseVDName() + strURL;
			}
			
			strOutput = m_oHTTPReq.Get(strURL);
			
			strOutput=strTargetFields + "=" + strOutput;
			
			return strOutput;
        }
        else
        {
			var strXML=GetRuleDefs();
			var strOutput="";
			
			if(strXML!="")
			{
				strOutput=GetActionFromXML(strXML, strCondFields, strTargetFields);	
			}
			else{
				strOutput=GetActionFromServer(strCondFields, strTargetFields);
			}
			
			return String(strOutput);
		}
    }

	function GetActionFromServer(strCondFields, strTargetFields)
	{
		var strCurrentLocation;
		var strOutput="";
		
		if (strCondFields !== "" && m_strURLName !== "") {
			if (m_strURLName.indexOf("?") == -1) {
				m_strURLName += "?";
			}
			
			strCurrentLocation = GetCurrentLocation();

			var strUrl = strCurrentLocation +  ResolveURL(strCondFields, strTargetFields);

			if (!isDependenciesCached(strUrl)) {
				//WriteConsole("[Dependent Fields] Resolving rule from server. ULR: " + strUrl);
				strOutput = setCachedDependencies(strUrl);
			} else {
				//WriteConsole("[Dependent Fields] Resolving rule from server. ULR: " + strUrl);
				strOutput = setCachedDependencies(strUrl);
			}
		}
		return strOutput;
	}
	
	
	function GetActionFromXML(strXML, strCondFields, strTargetFields)
	{
		var strActionResult="";
		
		var strTargetValue="";
		if(strXML!="" && strCondFields!="" && strTargetFields!="")
		{
			strCondFields=g_MqRef.MqStr.StripTrailing(strCondFields, ";");
			var arrCondFlds=strCondFields.split(";");
			
			var RULES_NODE="rules";
			var RULE_NODE="rule";
			var EQUALS_DELIM="=";
			
			var strXPathCond=GetXMLCondPath(arrCondFlds);
			
			if (!isDependenciesCached(strXPathCond)) {
				
				var strPath="/" + RULES_NODE + "/" + RULE_NODE + "[" + strXPathCond + "]/" + strTargetFields;
				if (window.DOMParser) { 
					var parser = new DOMParser();
					var xmlDoc = parser.parseFromString (strXML, "text/xml");
					if (xmlDoc.evaluate) {
						var iterator = xmlDoc.evaluate(strPath, xmlDoc, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null );

						try {
							var node = iterator.iterateNext();

							while (node) {
								strTargetValue+=node.textContent + DELIMITER;
								node = iterator.iterateNext();
							} 
						}
						catch (e) {
							WriteConsole( 'Error: GetActionFromXML failed getting node values ' + e );
						}
					}else{
						//IE
						var doc = new ActiveXObject('Microsoft.XMLDOM'); 
						doc.loadXML(strXML); 
						var nodes = doc.selectNodes(strPath);
						for (var y=0; y<nodes.length; y++) {
							if(nodes[y]){
								if(nodes[y].childNodes){
									if(nodes[y].childNodes[0]){
										strTargetValue+=nodes[y].childNodes[0].nodeValue + DELIMITER;
									}
								}
							}
						}
					}
				}
				strTargetValue=g_MqRef.MqStr.StripTrailing(strTargetValue, DELIMITER);
				strActionResult=g_MqRef.MqStr.MqEncodeURIComponent(strTargetFields+EQUALS_DELIM+strTargetValue);
				
				//set it in the cache for next time to not need to resolve it again
				SetValueInCache(strXPathCond, strActionResult);
			}else{
				//get cached value				
				strActionResult=getCachedDependencies(strXPathCond);
			}
		}
		return strActionResult;
	}	
	
	function GetXMLCondPath(arrCondFlds)
	{
		var strXPathCond="";
		var CONDIITON_PREFIX="Cond_";
		var EQUALS_DELIM="=";
		var XPATH_AND=" and ";
		var XPATH_OR=" or ";
		var MACRO_ANY="<Any>";
		var MACRO_EMPTY="<Empty>";
		
		for(var x=0; x<arrCondFlds.length; x++)
		{
			var arrCond=arrCondFlds[x].split(EQUALS_DELIM);
			var strElement=arrCond[0];
			var strValue=arrCond[1];
			
			strXPathCond+="(" + CONDIITON_PREFIX + strElement + "='" + strValue + "'";
			
			if(strValue==""){
				strXPathCond+=XPATH_OR + CONDIITON_PREFIX + strElement + "='" + MACRO_EMPTY + "'";
			}
			
			strXPathCond+=XPATH_OR + CONDIITON_PREFIX + strElement + "='" + MACRO_ANY + "')" + XPATH_AND;
		}
		
		strXPathCond=g_MqRef.MqStr.StripTrailing(strXPathCond, XPATH_AND);
		
		return strXPathCond;
	}
	
	
    function ResolveURL(strCondFields, strTargetFields) {
        var strUrl;
        if (strCondFields.indexOf(CUSTOM_URL_COND) >= 0) {
            strUrl = m_strURLName + CleanConditionFields(strCondFields);
        }
        else {
            strUrl = m_strURLName +
					"Cond=" + g_MqRef.MqStr.MqEncodeURIComponent(strCondFields) +
					"&Target=" + g_MqRef.MqStr.MqEncodeURIComponent(strTargetFields) +
					"&From=" + g_MqRef.MqStr.MqEncodeURIComponent(m_strTableName);
        }
        return strUrl;
    }
	
    function CleanConditionFields(strConditions) {
        var arrConditions = strConditions.split(DELIMITER);
        var arrCleanFields = new Array();
        var intFields = 0;
        var strParamsURL;
        for (i = 0; i < arrConditions.length; i++) {
            if (arrConditions[i].indexOf( LESS_THAN ) < 0 && arrConditions[i] != "") {
                arrCleanFields[intFields] = arrConditions[i];
                intFields++;
            }
        }

        for (j = 0; j < arrCleanFields.length; j++) {
            var paramName = arrCleanFields[j].substring(0, arrCleanFields[j].indexOf("="));
            var paramValue = g_MqRef.MqStr.MqEncodeURIComponent(arrCleanFields[j].substring(arrCleanFields[j].indexOf("=") + 1, arrCleanFields[j].length));

            if (typeof strParamsURL === "undefined") {
                strParamsURL = paramName + "=" + paramValue;
            }
            else {
                if (strParamsURL.indexOf(paramName) >= 0) {
                    strParamsURL += " " + paramValue;
                }
                else {
                    strParamsURL += AMPERSAND + paramName + "=" + paramValue;
                }
            }
        }
        return strParamsURL;
    }

    function GetCurrentLocation() {
        var File = new MqFiles;
        return location.protocol + "//" + location.hostname + ":" + location.port + File.getPath(location.pathname);
    }

    function SetValueOnTargetField(strTargetValues, m_objFields, blnOnFieldChange) {

        if (blnOnFieldChange) {
            if (typeof m_arrTargetFields[0][INDEX_FORM_ELEM_OBJ] != "undefined") {
                objElement = m_arrTargetFields[0][INDEX_FORM_ELEM_OBJ].GetElement();
                if (objElement.value != strTargetValues) {
                    objElement.value = strTargetValues;
					
					if (objElement.onchange) {
						objElement.onchange();
					}
                }
            }
        }
    }

    function setTargetValues(strValues, fDisplayCurrentValue, objFields, strFieldsHTMLContainer, blnOnFieldChange, strTriggerFieldID) {
        if (m_arrTargetFields === "") {
            return false;
        }
		
        var arrValues;
        var arrTargetFieldInfo;
        var strFieldName;
        var strFieldValues;
        var arrTargetFields;
        var intCount;
        var i, j;
        var INDEX_FIRST_ELEMENT = 0;
        var strValText;
        var lngID;
        var lngCtrlType;

        if (strValues !== "") {
            arrTargetFields = strValues.split(DELIMITER);

            for (i = 0; i < arrTargetFields.length; i++) {

                arrTargetFieldInfo = unescape(arrTargetFields[i]);
                arrTargetFieldInfo = arrTargetFieldInfo.split("=");
                strFieldName = arrTargetFieldInfo[INDEX_RET_FIELD_NAME];

                for (j = 0; j < m_arrTargetFields.length ; j++) {
                    if (m_arrTargetFields[j]) {

                        if (m_arrTargetFields[j][INDEX_FIELD_NAME] == strFieldName) {

                            strFieldValues = unescape(arrTargetFieldInfo[INDEX_RET_FIELD_VALUES]);

                            //WriteConsole("[Dependent Fields] Setting value for:" + m_arrTargetFields[j]);

                            if (m_arrTargetFields[j][INDEX_ACTION_TYPE] == ActionType.PossibleValues) {

                                SetPossibleValues(fDisplayCurrentValue, strFieldValues, strTriggerFieldID, blnOnFieldChange);

                            } else {
                                SetFieldValue(m_arrTargetFields[j][INDEX_FIELD_ID], strFieldValues, objFields, strFieldsHTMLContainer, blnOnFieldChange);
                            }
                        }
                    }
                }
            }
        }
    }

    function SetPossibleValues(fDisplayCurrentValue, strFieldValues, strTriggerFieldID, blnOnFieldChange)
    {
        var arrValues;
        var objElement;
        var arrItems = new Array();

        var strCurrentValue = "";

        if (fDisplayCurrentValue) {
            if (m_arrTargetFields[j][INDEX_FORM_ELEM_OBJ]) {
                strCurrentValue = m_arrTargetFields[j][INDEX_FORM_ELEM_OBJ].GetValue();
            }
        }
        //WriteConsole("[Dependent Fields] Rule of type Possible Values. Current Value if retrieved:" + strCurrentValue);

        if (strCurrentValue) {
            if (strCurrentValue.length > 0) {
                if (strFieldValues.length === 0) {
                    strFieldValues = strCurrentValue;
                } else {
                    strFieldValues += DELIMITER + strCurrentValue;
                }
            }
        }

        if (m_arrTargetFields[j][INDEX_INIT_VALUES]) {
            if (strFieldValues.length > 0) {

                arrValues = strFieldValues.split(DELIMITER);

                if (arrValues) {
                    arrValues = g_MqRef.MqArr.RemoveDuplicateElements(arrValues);

                    for (intCount = 0; intCount < arrValues.length; intCount++) {

                        if (m_arrTargetFields[j][INDEX_FORM_ELEM_OBJ]) {
                            lngCtrlType = m_arrTargetFields[j][INDEX_FORM_ELEM_OBJ].GetControlType();
                        } else {
                            lngCtrlType = CTRL_TYPE_COMBO;
                        }
                        if (lngCtrlType == CTRL_TYPE_LIST || lngCtrlType == CTRL_TYPE_LARGE_LIST) {
                            strValText = arrValues[intCount];
                            lngID = getIDFromTarget(arrValues[intCount],
                                                    m_arrTargetFields[j][INDEX_INIT_VALUES]);
                        } else {
                            strValText = getTextFromTarget(arrValues[intCount],
                                                    m_arrTargetFields[j][INDEX_INIT_VALUES]);

                            lngID = arrValues[intCount];
                        }

                        if (typeof (strValText) != "undefined") {
                            arrItems[intCount] = new Array(lngID, strValText);
                        }
                    }
                }

            } else {
                arrItems = m_arrTargetFields[j][INDEX_INIT_VALUES];
            }

        } else {

            if (strFieldValues.length > 0) {
                //WriteConsole("[Dependent Fields] No initial set of choices. Updating MqWrkFlwVals filter with value:" + strFieldValues);
                arrItems = strFieldValues;
            }

        }

        if (m_arrTargetFields[j][INDEX_FORM_ELEM_OBJ]) {
			if (m_arrTargetFields[j][INDEX_FORM_ELEM_OBJ].SetPossibleValues(arrItems,
                        SelectFirstPossValItem(arrItems), null, null, strTriggerFieldID)) {
                if (blnOnFieldChange || SelectFirstPossValItem(arrItems)==true) {
                    objElement = m_arrTargetFields[j][INDEX_FORM_ELEM_OBJ].GetElement();
                    if (objElement) {
                        if (objElement.onchange) 
                        {
                        	try
                        	{

	                        	// objElement.onchange() would not preserve the original context
								var evt =objElement.ownerDocument.createEvent("HTMLEvents");
								    evt.initEvent("change", false, true);
								    objElement.dispatchEvent(evt);                        
							}catch(e)
							{
								objElement.onchange();
							}
						}
							                        
                    }
                }
            }
        }
    }

    function SetFieldValue(strFieldId, strFieldValues, objFields, strFieldsHTMLContainer, blnOnFieldChange)
    {
        var objFormElement;
        var arrValues;
        var objMacros = new CMqMacros();
        var objElement;


        if (strFieldValues.length > 0) {
			objFormElement = GetFormElement(strFieldId, objFields, strFieldsHTMLContainer);

            if (objFormElement) {
                if (objFormElement.GetControlType() == CTRL_TYPE_LIST || objFormElement.GetControlType() == CTRL_TYPE_LARGE_LIST) {
                    arrValues = Array(strFieldValues);
                } else {
                    arrValues = strFieldValues.split(DELIMITER);
                }

                if (arrValues) {
                    for (intCount = 0; intCount < arrValues.length; intCount++) {
                        if (arrValues[intCount]) {
                            SetDepValsValue(objFormElement, arrValues[intCount], objFields,strFieldsHTMLContainer, m_blnLinkFldValsByID, objMacros);

                            if (blnOnFieldChange) {
                                objElement = objFormElement.GetElement();
                                if (objElement) {
                                    if (objElement.onchange) {
                                        objElement.onchange();
                                    }
                                }
                            }

                        }
                    }
                }
            }
        }
    }

    function SelectFirstPossValItem(arrItems) {
        var blnReturn = m_blnSelectFirstValue;

        if (blnReturn == true) {
            if ($.isArray(arrItems)) {
                if (arrItems.length > 1) {
                    blnReturn = false;
                }
            } else {
                blnReturn = true;
            }
        }
        return blnReturn;
    }
    function SetDepValsValue(objFormElement, strValue, objFields, strFieldsHTMLContainer, blnLinkFldValsByID, objMacros) {
        WriteConsole("[Dependent Fields] Setting the value of a dependent field [" + objFormElement.Name() +
					"] with value:" + strValue);

        var WKFLW_NO_VALUES = "-1";
        if (strValue == WKFLW_NO_VALUES) {
            strValue = "";
        }

        if (!SetDepValsValue_Macro(strValue, objFields, objFormElement, strFieldsHTMLContainer, blnLinkFldValsByID, objMacros)) {
            objFormElement.SetValue(strValue);
            var objElement = objFormElement.GetElement();
            if (objElement) {
                objElement.setAttribute("MqWrkFlwVals", "");
            }
        }
    }

    function SetDepValsValue_Macro(strValue, objFields, objTargetFormElement, strFieldsHTMLContainer, blnLinkFldValsByID, objMacros) {
        var strLinkedFieldID;
        var blnReturn = true;
        var objSourceFormElement;
        var lngFieldValID;
        var strFieldValue;

        if (objMacros) {
            strLinkedFieldID = objMacros.GetFieldMacroContents(strValue);
        }

        if (strLinkedFieldID) {
            if (strLinkedFieldID.length > 0) {

                objSourceFormElement = GetFormElement(strLinkedFieldID, objFields, strFieldsHTMLContainer);

                if (blnLinkFldValsByID) {

                    if (objSourceFormElement) {
                        lngFieldValID = objSourceFormElement.GetValue();
                        if (lngFieldValID != "") {
                            objTargetFormElement.SetValue(lngFieldValID);
                        }
                    }
                } else {

                    if (objSourceFormElement) {
                        strFieldValue = objSourceFormElement.GetValue(null, null, null, true);
                        if (strFieldValue != "") {
                            objTargetFormElement.SetValue(strFieldValue, null, null, null, null, true);
                        }
                    }
                }
            } else {
                blnReturn = false;
            }
        } else {
            blnReturn = false;
        }
        return blnReturn;
    }

    function GetFormElement(strFieldId, objFields, strFieldsHTMLContainer) {
        var objFormElement;
        var objField;

        if (strFieldId != null) {
            if (objFields) {
                objField = objFields.Field(strFieldId);
                if (objField) {
                    objFormElement = new CMqFormElement();
                    objFormElement.Initialize(objField.GetBoundControl(), objField.GetControlType(), strFieldsHTMLContainer, m_objMqAutoList);
                }
            }
        }
        return objFormElement;
    }


    function getTextFromTarget(intValue, arrInitValuesTarget) {
        var intCount;
        var arrTemp;
        var strText;
        if (arrInitValuesTarget) {
            for (intCount = 0; intCount < arrInitValuesTarget.length; intCount++) {
                arrTemp = arrInitValuesTarget[intCount];
                if (arrTemp[ARR_VALUE] == intValue) {
                    strText = arrTemp[ARR_TEXT];
                    break;
                }
            }
        }
        return strText;
    }

    function getIDFromTarget(strText, arrInitValuesTarget) {
        var intCount;
        var arrTemp;
        var intValue;
        if (arrInitValuesTarget) {
            for (intCount = 0; intCount < arrInitValuesTarget.length; intCount++) {
                arrTemp = arrInitValuesTarget[intCount];
                if (arrTemp[ARR_TEXT] == strText) {
                    intValue = arrTemp[ARR_VALUE];
                    break;
                }
            }
        }
        return intValue;
    }

    function isDependenciesCached(strIdentifier) {
        var lngCount;
        var blnFound;

        blnFound = false;
        for (lngCount = 0; lngCount < arrCachedDependencies.length; lngCount++) {
            if (arrCachedDependencies[lngCount][ARR_URL] == strIdentifier) {
                blnFound = true;
                break;
            }
        }
        return blnFound;
    }

    function getCachedDependencies(strIdentifier) {
        var lngCount;
        var strFound;

        strFound = "";
        for (lngCount = 0; lngCount < arrCachedDependencies.length; lngCount++) {
            if (arrCachedDependencies[lngCount][ARR_URL] == strIdentifier) {
                strFound = arrCachedDependencies[lngCount][ARR_OUTPUT];
                break;
            }
        }

        return strFound;
    }

    function setCachedDependencies(strUrl) {
        var strOutput;
        var FALSE = "False";
        var objString = new MqString();

        if (m_oHTTPReq) {
            strOutput = m_oHTTPReq.Get(strUrl);

            strOutput = String(strOutput);

            strOutput = objString.getNullTerminatedString(strOutput);

            if (strOutput != m_oHTTPReq.CANCEL_PROCESS) {
                if (strOutput.substr(0, 5).toUpperCase() != FALSE.toUpperCase()) {
                    SetValueInCache(strUrl, strOutput);
                } else {
                    strOutput = "";
                }
            } else {
                strOutput = "";
            }
        } else {
            strOutput = "";
        }

        return strOutput;
    }

	function SetValueInCache(strIdentifier, strValue)
	{
		arrCachedDependencies[arrCachedDependencies.length] = new Array(strIdentifier, strValue);
	}
	
    function CMqFldAcc(oFlds, strDoc) {
        var m_oDoc;
        var m_strDoc = strDoc;
        var m_oFlds = oFlds;

        function GetHTMLDoc() {
            if (!m_oDoc) {
                m_oDoc = eval(m_strDoc);
            }
            return m_oDoc;
        }

        function GetCtrl(lnfFldId) {
            var oDoc = GetHTMLDoc();
            var oFld = m_oFlds.Field(lnfFldId);
            var oCtl;

            if (oDoc && oFld) {
                oCtl = oDoc.getElementById(oFld.GetBoundControl());
            }

            return oCtl;
        }

        this.GetCtrl = GetCtrl;

    }

    function MakeFieldsHidden(strFields, strFieldsHTMLContainer) {
        var arrHidFlds = new Array();
        var arrTarget;

        if (strFields != "") {
            var objContext = eval(strFieldsHTMLContainer);
            if (objContext) {

                UnHideAllFields(objContext);

                m_arrIssueHiddenFlds = new Array();

                arrTarget = unescape(strFields).split("=");

                arrHidFlds = unescape(arrTarget[1]).split(";");

                if (arrHidFlds.length > 0) {
                    SetFieldsHidden(arrHidFlds, objContext);
                }
            }
        }
    }

    function MakeFieldsVisible(strFields, strFieldsHTMLContainer) {
        var arrVisibleFlds = new Array();
        var arrTarget;
        var objFormElement = new CMqFormElement();

        if (strFields != "") {
            var objContext = eval(strFieldsHTMLContainer);
            if (objContext) {

                HideAllFields(objContext);

                m_arrIssueVisibleFlds = new Array();

                arrTarget = unescape(strFields).split("=");

                arrVisibleFlds = unescape(arrTarget[1]).split(";");

                if (arrVisibleFlds.length > 0) {
                    for (lngCount = 0; lngCount < arrVisibleFlds.length; lngCount++) {
                        if (m_objViewFields) {
                            var lngFieldID = m_objViewFields.GetFieldIDByCaption(arrVisibleFlds[lngCount]);
                            var objField = m_objViewFields.Field(lngFieldID);
                            if (objField) {
                                var strFieldName = objField.GetBoundControl()
                                var objCtrl = objContext.getElementById(strFieldName);
                                objFormElement.HideElement(false, objCtrl, true, lngFieldID, objContext);
                                AddElementToArray(m_arrIssueVisibleFlds, lngFieldID);
                            }
                        }
                    }
                }
            }
        }
    }

	function SetFieldsHidden(arrFlds, objContext) {
        var objFormElement = new CMqFormElement();
        var lngCount;
        var objTD
        var blnClearHiddenFieldVals = false;

        if (objContext) {
        	
            for (lngCount = 0; lngCount < arrFlds.length; lngCount++) {
				
                // Change this when supporting multiple records
                var oFrmFld =g_VWS.RecordMgr().CurrentRecord().GetFormField(arrFlds[lngCount]);
                if (oFrmFld) 
                {
	                if (blnClearHiddenFieldVals) 
	                {
		                oFrmFld.GetValueControl().SetValue("");
	                }
	                    
	                if (!oFrmFld.IsHiddenType())
					{
						// Move to Vn form field
						oFrmFld.GetValueControl().HideElement(true, null, true, arrFlds[lngCount], objContext);
	
	                	AddElementToArray(m_arrIssueHiddenFlds, arrFlds[lngCount]);
	                }
	            }
            }
        }
    }

    function SetFieldsUnHidden(arrFlds, objContext) {
        var lngCount;
        var objFont;
        var lngChildCount;
        var objFormElement = new CMqFormElement();

        if (objContext) {
            for (lngCount = 0; lngCount < arrFlds.length; lngCount++) {
                objFormElement.HideElement(false, null, true, arrFlds[lngCount], objContext);
            }
        }
    }

    function UnHideAllFields(objContext) {
        if (m_arrIssueHiddenFlds) {
            SetFieldsUnHidden(m_arrIssueHiddenFlds, objContext);
        }
    }

    function HideAllFields(objContext) {
        var objFormElement = new CMqFormElement();
        if (m_arrIssueVisibleFlds) {
            if (objContext) {
                for (lngCount = 0; lngCount < m_arrIssueVisibleFlds.length; lngCount++) {
                    objFormElement.HideElement(true, null, true, m_arrIssueVisibleFlds[lngCount], objContext);
                }
            }
        }
    }

    function AddElementToArray(arrArray, varElement) {
        if (arrArray) {
            var lngLen = arrArray.length;
            arrArray.length++;
            arrArray[lngLen] = varElement;
        }
        return arrArray;
    }

    function FixTabs(strHiddenTabs, strFieldsHTMLContainer) {
        var arrHideTabs = new Array();
        var arrHiddenTabs;
        var lngTabsCount;
        if (strHiddenTabs != "") {
            if (objTabsMgr) {


                var arrTarget = unescape(strHiddenTabs).split("=");

                arrHiddenTabs = unescape(arrTarget[1]).split(";");

                for (lngTabsCount = 0; lngTabsCount < arrHiddenTabs.length; lngTabsCount++) {
                    arrHideTabs = AddElementToArray(arrHideTabs, arrHiddenTabs[lngTabsCount]);
                }

                if (arrHideTabs.length > 0) {
                    if (m_strHiddenTabs != "") {
                        objTabsMgr.UnHideTabs(m_strHiddenTabs.split(";"));
                    }
                    m_strHiddenTabs = arrHideTabs.join(";");
                    objTabsMgr.HideTabs(arrHideTabs, true);
                }

                objTabsMgr.RefreshTabDisplay();
            }
        }
    }

    function MakeFieldsRequired(strFields, strFieldsHTMLContainer) {
        var arrReqFlds = new Array();
        var arrTarget;

        if (strFields != "") {
            var objContext = eval(strFieldsHTMLContainer);
            if (objContext) {

                UnRequireAllFields(objContext);

                m_arrIssueReqFlds = new Array();

                arrTarget = unescape(strFields).split("=");

                arrReqFlds = unescape(arrTarget[1]).split(";");

                if (arrReqFlds.length > 0) {
                    SetFieldsRequired(arrReqFlds, objContext);
                }
            }
        }
    }

    function SetFieldsRequired(arrFlds, objContext) {
        var lngCount;
        var objFont;
        var lngChildCount;

        if (objContext) {
            for (lngCount = 0; lngCount < arrFlds.length; lngCount++) {
                var objTD = objContext.getElementById("MqFC_" + arrFlds[lngCount]);
                if (objTD) {
                    for (lngChildCount = 0; lngChildCount < objTD.childNodes.length; lngChildCount++) {
                        objFont = objTD.childNodes.item(lngChildCount);
                        if (objFont) {
                            if (objFont.tagName) {
                                if (objFont.tagName.toLowerCase() == "font") {
                                    objFont.className = "requiredfield";
                                    AddElementToArray(m_arrIssueReqFlds, arrFlds[lngCount]);
                                    //break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    function SetFieldsUnRequired(arrFlds, objContext) {
        var lngCount;
        var objFont;
        var lngChildCount;

        if (objContext) {
            for (lngCount = 0; lngCount < arrFlds.length; lngCount++) {
                var objTD = objContext.getElementById("MqFC_" + arrFlds[lngCount]);
                if (objTD) {
                    for (lngChildCount = 0; lngChildCount < objTD.childNodes.length; lngChildCount++) {
                        objFont = objTD.childNodes.item(lngChildCount);
                        if (objFont) {
                            if (objFont.tagName) {
                                if (objFont.tagName.toLowerCase() == "font") {
                                    objFont.className = "normalfield";
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    function UnRequireAllFields(objContext) {
        if (objContext) {
            if (m_arrIssueReqFlds) {
                SetFieldsUnRequired(m_arrIssueReqFlds, objContext);
            }
        }
    }

    function ValidateRequiredFields() {

        var lngCount;
        var strFieldName;
        var objField;



        var blnReturn = true;
        var lngNumBatchRows = 0;
        var strBatchFieldIDs = "";
        var arrBatchFieldIDs = new Array();

        if (m_objLoadDataMgr) {
            lngNumBatchRows = m_objLoadDataMgr.GetNumBatchRows();
            strBatchFieldIDs = m_objLoadDataMgr.GetBatchFieldIDs();
        }

        if (strBatchFieldIDs != "") {
            arrBatchFieldIDs = strBatchFieldIDs.split(",");
        }

        if (m_arrIssueReqFlds && m_objViewFields) {
            for (lngCount = 0; lngCount < m_arrIssueReqFlds.length; lngCount++) {
                objField = m_objViewFields.Field(m_arrIssueReqFlds[lngCount]);
                if (objField) {
                    strFieldName = objField.GetBoundControl()

                    blnReturn = VerifyFieldReq(strFieldName, m_arrIssueReqFlds[lngCount]);

                    if (blnReturn == false) {



                        break;
                    }

                    if (g_MqRef.MqArr.IsValueInArray(m_arrIssueReqFlds[lngCount], arrBatchFieldIDs)) {
                        for (x = 1; x <= lngNumBatchRows; x++) {
                            var regExp = new RegExp(objField.GetID(), "g");
                            var strBatchFieldName = strFieldName.replace(regExp, objField.GetID() + "_" + x);

                            blnReturn = VerifyFieldReq(strBatchFieldName, m_arrIssueReqFlds[lngCount]);

                            if (blnReturn == false) {
                                break;
                            }
                        }
                    }

                    if (blnReturn == false) {
                        break;
                    }
                }
            }
        }
        return blnReturn;
    }

    function VerifyFieldReq(strFieldName, lngFieldID) {
        var blnReturn = true;
        var objCtrl;

        objCtrl = eval(strFieldsHTMLContainer).getElementById(strFieldName);

        if (objCtrl) {
            var objFormElement = new CMqFormElement();
            var strFldValue = objFormElement.GetValue(false, objCtrl);
            if (strFldValue == "") {
                if (m_objViewFields) {
                    var strFieldCaption = m_objViewFields.GetFieldCaption(lngFieldID, eval(strFieldsHTMLContainer));
                    g_MqRef.MsgHlpr.DisplayMessage(g_MqRef.MqStr.Format(g_MqRef.RESX['WARNING_MESSAGE_REQUIRED_FIELD'], strFieldCaption));

                    var lngTabID = m_objViewFields.Field(lngFieldID).GetTabID();
                    if (objTabsMgr) {
                        objTabsMgr.OnTabClick(lngTabID);
                    }
                    objCtrl.focus();

                    blnReturn = false;
                }
            }
        }
        return blnReturn;
    }

    function MakeFieldsDisabled(strFields, strFieldsHTMLContainer) {
        var arrDisFlds = new Array();
        var arrTarget;

        if (strFields != "") {
            var objContext = eval(strFieldsHTMLContainer);
            if (objContext) {

                EnableAllFields(objContext);

                m_arrIssueDisabledFlds = new Array();

                arrTarget = unescape(strFields).split("=");

                arrDisFlds = unescape(arrTarget[1]).split(";");

                if (arrDisFlds.length > 0) {
                    SetFieldsDisabled(arrDisFlds, objContext);
                }
            }
        }
    }

    function DoCustomAction(strVal, strFieldsHTMLContainer, blnOnFieldChange, strAction) {
        eval(strAction + "('" + strVal + "', '" + strFieldsHTMLContainer + "', " + blnOnFieldChange + ")");
    }

	function SetTicketDisabled(strDoDisable, strFieldsHTMLContainer)
	{
		var arrTarget = unescape(strDoDisable).split("=");

		var objContext = eval(strFieldsHTMLContainer);
		if (objContext) {
			var arrAllFlds=new Array();
			var lngCount;
			var objField;
			if(m_objViewFields){
				var objFieldColl=m_objViewFields.GetFieldCol();
				for(lngCount=0; lngCount<objFieldColl.length; lngCount++){
					objField=m_objViewFields.Field(lngCount);
					
					if(objField){
						arrAllFlds[lngCount]=objField.GetID();
					}
				}
			}
			if(arrTarget[1]=="1"){
				SetFieldsDisabled(arrAllFlds, objContext);	
			}else{
				SetFieldsEnabled(arrAllFlds, objContext);	
			}
		}
	}
	
    function SetFieldsDisabled(arrFlds, objContext) {
        var lngCount;

        if (objContext) {
            for (lngCount = 0; lngCount < arrFlds.length; lngCount++) {

                if (m_objViewFields) {
                    var objField = m_objViewFields.Field(arrFlds[lngCount]);
                    if (objField) {
                        var strFieldName = objField.GetBoundControl()
                        var objCtrl;

                        objCtrl = objContext.getElementById(strFieldName);

                        if (objCtrl) {
                            m_objLoadDataMgr.DisableElement(objCtrl, objField, true, m_oDisplayElements, objContext)
                            AddElementToArray(m_arrIssueDisabledFlds, arrFlds[lngCount]);
                        }
                    }
                }
            }
        }
    }

    function SetFieldsEnabled(arrFlds, objContext) {
        var lngCount;

        if (objContext) {
            for (lngCount = 0; lngCount < arrFlds.length; lngCount++) {
                if (m_objViewFields) {
                    var objField = m_objViewFields.Field(arrFlds[lngCount]);
                    if (objField) {
                        var strFieldName = objField.GetBoundControl()
                        var objCtrl;

                        objCtrl = objContext.getElementById(strFieldName);

                        if (objCtrl) {
                            m_objLoadDataMgr.DisableElement(objCtrl, objField, false, m_oDisplayElements, objContext)
                        }
                    }
                }
            }
        }
    }

    function EnableAllFields(objContext) {
        if (m_arrIssueDisabledFlds) {
            SetFieldsEnabled(m_arrIssueDisabledFlds, objContext);
        }
    }
}


/**
	Collection and manager of Biz Rules (DependentFields objects)
	@constructor
*/
function CMqWorkFlowRules(objViewFldDefs,oLoadDataMgr, oMqAutoList, oDisplayElements)
{
	var DEFAULT_SRC_PAGE = "../ASP/GetWorkFlowValues.asp?m=1&";
	var m_varDependentFields;
	var m_rsOrigFldVals;
	var m_blnVerifyCondFldsExist;
	var m_oStaticDepFlds=new MqDependentFields();
	var m_objViewFldDefs=objViewFldDefs;
	var m_oLoadDataMgr = oLoadDataMgr;
	var m_oMqAutoList=oMqAutoList;
	var m_oDisplayElements=oDisplayElements;
	var m_arrDisabledBizRuleIDs=new Array();
	var m_arrRuleOrder=new Array();
	var m_blnBizRlsLoaded=false;
	var _me=this;
	var m_mqFiles = new MqFiles();
	
	function Initialize(objFieldCollection,strHTMLContainer,objMqAutoList, objDisplayElements, blnVerifyCondFldsExist, strExtraHTMLContainers)
	{
		if (!m_varDependentFields){
			m_varDependentFields= new Array();
		}

		m_blnVerifyCondFldsExist = blnVerifyCondFldsExist;
		var INDEX_FIELD_ID=0;

		// Initialize the pre-declared biz rules written in CMqWorkflow.js
		if (typeof(_me.InitDeclaredBizRules)!="undefined")
		{
			if (_me.InitDeclaredBizRules!=null)
			{
				_me.InitDeclaredBizRules(_me, objFieldCollection, m_oLoadDataMgr.GetDataHTMLDocument(), 
									m_oMqAutoList, m_oDisplayElements, strExtraHTMLContainers);
			}
		}

		// Load business rules at the end of the init
		_me.LoadBizRules();

	}//End Function

	function OnLoad()
	{		
		WriteConsole("[Wrkflow rules] OnLoad");
		
		var iDepFldsID;
		if (m_varDependentFields)
		{
			if(m_arrRuleOrder){
				for (var i=0;i<m_arrRuleOrder.length;i++)
				{
					iDepFldsID=m_arrRuleOrder[i];
					if(m_varDependentFields[iDepFldsID])
					{
						if(m_varDependentFields[iDepFldsID].GetTriggerOnLoadRec())
						{
							WriteConsole("[Wrkflow rules] OnChange" + iDepFldsID);
							_me.OnChange(iDepFldsID);
						}
					}
				}
			}		
		}
	}
	
	function OnSave()
	{
		WriteConsole("[Wrkflow rules] OnSave");
		var iDepFldsID;
		
		if (m_varDependentFields)
		{
			if(m_arrRuleOrder)
			{
				for (var i=0;i<m_arrRuleOrder.length;i++)
				{
					iDepFldsID=m_arrRuleOrder[i];
					if(m_varDependentFields[iDepFldsID])
					{
						if(m_varDependentFields[iDepFldsID].GetTriggerOnSaveRec())
						{
							WriteConsole("[Wrkflow rules] OnSave" + iDepFldsID);
							_me.OnChange(iDepFldsID);
						}
					}
				}
			}		
		}
	}
	
	function OnChange(intID, blnOnFieldChange,strTriggerFieldID)
	{

		WriteConsole("[Wrkflow rules] Executing Biz Rule " + intID);
		
		if (m_varDependentFields)
		{
			if (m_varDependentFields[intID]){
				m_varDependentFields[intID].SetDependentField(m_rsOrigFldVals, blnOnFieldChange, m_blnVerifyCondFldsExist, strTriggerFieldID);
			}
			
		}

		WriteConsole("[Wrkflow rules] Finished Executing Biz Rule " + intID);
		
	}
	
	function SetOrigFldValues(rsOrigFldVals)
	{
		m_rsOrigFldVals=rsOrigFldVals;
	}
	
	function ValidateRequiredFields()
	{
		var blnReturn=true;
		
		if (m_varDependentFields){
			for (var i=0;i<m_varDependentFields.length;i++){
				if(m_varDependentFields[i]){
					blnReturn=m_varDependentFields[i].ValidateRequiredFields();
				
					if(blnReturn==false){
						break;
					}
				}
			}		
		}
		return blnReturn;
	}
	function GetDependentFields(){
		return m_varDependentFields;
	}
	
	function SetDependentFields(varDependentFields){
		m_varDependentFields=varDependentFields;
	}

	function GetOrigFldValues()
	{
		return m_rsOrigFldVals;
	}
	
	function GetVerifyCondFldsExist()
	{
		return m_blnVerifyCondFldsExist;
	}

	function LoadBizRules()
	{
		if(!m_blnBizRlsLoaded){
			WriteConsole("[WorkflowRules] Loading business rules from server. URL:" + window.location); 

			m_mqFiles.LoadScriptSync("../asp/GetBizRules.asp?rd=" + Math.floor(Math.random()*1000001));
			m_blnBizRlsLoaded=true;
		}
	}
		
	function AddBizRule(oBizRuleParams)
	{
	
		if (oBizRuleParams && m_objViewFldDefs && m_oLoadDataMgr && m_oMqAutoList && m_oDisplayElements)
		{
			var strRefToWkflObj="";
			var strURL=DEFAULT_SRC_PAGE;
			
			if (!m_varDependentFields){
				m_varDependentFields= new Array();
			}

			if(!BizRuleExists(oBizRuleParams.GlobalID))
			{

				var intOrder=m_varDependentFields.length;

				WriteConsole("[WorkflowRules] Adding new rule with GlobalID:" + oBizRuleParams.GlobalID + " and current Order:" + intOrder );
							
				// MqDependentFields(objFieldCollection, strFieldsHTMLContainer, objMqAutoList, oHTTPReq, strExtraHTMLContainers, iRuleID) 
				m_varDependentFields[intOrder]=new MqDependentFields(m_objViewFldDefs,m_oLoadDataMgr.GetDataHTMLDocument(),m_oMqAutoList, null,null,intOrder);
				
				var blnAdded = false;
				if(typeof(oBizRuleParams.AddAtBeginning)!="undefined"){
					if(oBizRuleParams.AddAtBeginning==true){
						m_arrRuleOrder.unshift(intOrder);
						blnAdded=true;
					}
				}
				if(!blnAdded){
					m_arrRuleOrder[m_arrRuleOrder.length]=intOrder;
				}

				var arrCondFields=oBizRuleParams.Conditions;
			
				if (oBizRuleParams.TriggerOnChange==true)
				{
					for (i=0;i<arrCondFields.length;i++){
						if (arrCondFields[i]){
							var strFieldID=arrCondFields[i].FieldID;
							if (strFieldID){
								m_varDependentFields[intOrder].SetOnChange(strFieldID,strRefToWkflObj+
										"m_objWorkFlow.OnChange("+intOrder+", true,"+strFieldID+");");
							}
						}
					}
				}

				if(typeof(oBizRuleParams.DisplayCurrentValue)!="undefined")
				{
					m_varDependentFields[intOrder].DisplayCurrentValue=oBizRuleParams.DisplayCurrentValue;
				}else{
					// Assumption: most of dependent fields don't display current value - workflow does
					if (oBizRuleParams.TriggerOnChange==true)
					{
						m_varDependentFields[intOrder].DisplayCurrentValue=false;
					}else{
						m_varDependentFields[intOrder].DisplayCurrentValue=true;
					}
				}
				
				if(typeof(oBizRuleParams.TriggerOnSave) != "undefined")
				{
					m_varDependentFields[intOrder].SetTriggerOnSaveRec(oBizRuleParams.TriggerOnSave);
				}
				
				if(typeof(oBizRuleParams.TriggerOnLoad) != "undefined")
				{
					m_varDependentFields[intOrder].SetTriggerOnLoadRec(oBizRuleParams.TriggerOnLoad);
				}
				
				MakeParamsBackwardsCompatible(oBizRuleParams.Conditions, oBizRuleParams.Actions);
				
				if (oBizRuleParams.URL) {
				    strURL = oBizRuleParams.URL;
				}

				m_varDependentFields[intOrder].Initialize(oBizRuleParams.Actions,oBizRuleParams.Conditions,
							strURL, oBizRuleParams.GlobalID, false, m_oDisplayElements, oBizRuleParams.LocalConditions,
							oBizRuleParams.ExternalResource);
							
				m_varDependentFields[intOrder].SetGlobalID(oBizRuleParams.GlobalID);

				if(typeof(oBizRuleParams.SelectFirstValue)!="undefined"){
					m_varDependentFields[intOrder].SetIsSelectFirstValue(oBizRuleParams.SelectFirstValue);
				}

				//if(m_varDependentFields[intOrder].GetTriggerOnLoadRec()){
				//	OnLoad();
				//}
			}
		}else{
			WriteConsole("[WorkflowRules] Objects not initialized," + oBizRuleParams );
		}
		return true;
	}

	function BizRuleExists(strGlobalID)
	{
		var blnReturn=false;
		if(m_varDependentFields){
			for(var x=0; x<m_varDependentFields.length;x++){
				if(m_varDependentFields[x]){
					if(m_varDependentFields[x].GetGlobalID()==strGlobalID){
						blnReturn=true;
						break;
					}
				}
			}
		}
		return blnReturn;
	}
	
	function MakeParamsBackwardsCompatible(arrCondFields,arrActions)
	{
		var IDX_COND_FIELD_ID=0;
		var IDX_COND_FIELD_NAME=1;
	
		var INDEX_FIELD_ID=0;
		var INDEX_FIELD_NAME=1;
		var INDEX_ACTION_TYPE=2;
		var i;
		
		for (i=0;i<arrCondFields.length;i++){
			if (arrCondFields[i]){
				// Add backwards compatible elements
				arrCondFields[i][IDX_COND_FIELD_ID]=arrCondFields[i].FieldID;
				arrCondFields[i][IDX_COND_FIELD_NAME]=arrCondFields[i].ParamReplace;
			}
		}

		for (i=0;i<arrActions.length;i++){
			if (arrActions[i]){
				// Add backwards compatible elements
				arrActions[i][INDEX_FIELD_ID]=arrActions[i].TargetFieldID;
				arrActions[i][INDEX_FIELD_NAME]=arrActions[i].ValueSource;
				arrActions[i][INDEX_ACTION_TYPE]=arrActions[i].ActionType;
				
				//get the Field Name from the Field ID 
				if(typeof(arrActions[i].ValueSource)=="undefined")
				{
					if (m_objViewFields) {
						if(arrActions[i].TargetFieldID){
							var objField = m_objViewFields.Field(arrActions[i].TargetFieldID);
							if (objField) {
								arrActions[i][INDEX_FIELD_NAME]=objField.GetName();
							}
						}
					}
				}
			}
		}

	}
	
	function SetDisabledBizRuleIDs(arrBizRuleIDs)
	{
		m_arrDisabledBizRuleIDs=arrBizRuleIDs;
	}
	
	function GetDisabledBizRules()
	{
		return m_arrDisabledBizRuleIDs;
	}
	
	function GetRuleOrder()
	{
		return m_arrRuleOrder;
	}	
	
	this.Initialize=Initialize;	
	this.OnLoad=OnLoad;
	this.OnChange=OnChange;
	this.OnSave=OnSave;
	this.SetOrigFldValues=SetOrigFldValues;
	this.ValidateRequiredFields=ValidateRequiredFields;
	this.GetDependentFields=GetDependentFields;
	this.SetDependentFields=SetDependentFields;
	this.GetOrigFldValues=GetOrigFldValues;
	this.GetVerifyCondFldsExist=GetVerifyCondFldsExist;
	this.LoadBizRules=LoadBizRules;
	this.AddBizRule=AddBizRule;
	this.SetDisabledBizRuleIDs=SetDisabledBizRuleIDs;
	this.GetDisabledBizRules=GetDisabledBizRules;
	this.GetRuleOrder=GetRuleOrder;
	this.InitDeclaredBizRules=null;
}

/**
	Manage loading data view actions
	@constructor
*/
function CMqLoadDataViewActions(){
	var m_objLoadDVActions;
	var m_objLoadData;
	
	function SetLoadDataMgr(objLoadDataMgr){
		m_objLoadData=objLoadDataMgr;
		
	}	

	function Add(varCondFields,varDVFields,varDataViews,objHTTPRequest,strHTTPLocation,varCondVals,objRecord){
		
		if (!m_objLoadDVActions){
			m_objLoadDVActions=new Array();			
		}		
		var lngIndex=-1;
		if (varCondFields && varDataViews){
			if ((varCondFields.length>0) && (varDataViews.length>0)){
				lngIndex=m_objLoadDVActions.length;
				m_objLoadDVActions[lngIndex]=new CMqLoadDataViews(varCondFields,varDVFields,varDataViews,m_objLoadData,objHTTPRequest,strHTTPLocation,varCondVals,objRecord);
			}
		}
		return lngIndex;
	}
	
	function Item(lngIndex){
		var objAction;
		if (m_objLoadDVActions){
			objAction= m_objLoadDVActions[lngIndex];
		}
		return objAction;
	}
	function Reset(){
		if (m_objLoadDVActions){
			for(var i=0;i<m_objLoadDVActions.length;i++){
				if (m_objLoadDVActions[i]){
					m_objLoadDVActions[i].Reset();
				}
			}
		}
	}
	this.Add=Add;
	this.Item=Item;
	this.Reset=Reset;
	this.SetLoadDataMgr=SetLoadDataMgr;

}


/**
	Manage loading data view
	@constructor
*/
function CMqLoadDataViews(varCondFields,varDVFields,varDataViews,objDataMgr,objHTTPRequest,strHTTPLocation,varCondVals,objRecord){
	var m_strCondition="";
	//start constructor
	var m_varCondFields=varCondFields;
	var m_varDataViews=varDataViews;
	var m_objLoadData=objDataMgr;	
	var m_objHTTPRequest=objHTTPRequest;
	var m_strHTTPLocation=strHTTPLocation;
	var m_varDVFields =varDVFields;
	var m_varCondVals=varCondVals;
	var m_objRecord=objRecord;
	//end constructor

	function SetCondFields(varCondFields){
		m_varCondFields=varCondFields;
	}
	
	function GetCondFields(){
		return m_varCondFields;
	}
	
	function SetCondVals(varCondVals){
		m_varCondVals=varCondFields;
	}
	
	function GetCondVals(){
		return m_varCondVals;
	}
	
	function SetDataViews(varDataViews){
		m_varDataViews=varDataViews;
	}
	
	function GetDataViews(){
		return m_varDataViews;
	}
	

	function Reset(){
		if(!m_varCondVals){
			m_strCondition=BuildCond(m_varCondFields,m_objLoadData);		
		}
	}
	
	function Apply(){
		if (m_objLoadData){	
			var strNewCond=BuildCond(m_varCondFields,m_objLoadData,m_varCondVals);
			if (IsCondChanged(m_strCondition,strNewCond) || !IsDVLoaded(m_varDVFields,m_objLoadData)){
				m_strCondition=strNewCond;									
				var objRsValue= m_objLoadData.GetObjFieldValues().GetFromServer(m_varDataViews,m_strCondition,m_objHTTPRequest,m_strHTTPLocation);		
				if (objRsValue){
					m_objLoadData.Load(objRsValue);
				}
			}
		}
	}
	

	this.SetCondFields=SetCondFields;
	this.GetCondFields=GetCondFields;
	this.SetDataViews=SetDataViews;	
	this.GetDataViews=GetDataViews;
	this.Reset=Reset;
	this.Apply=Apply;
	this.SetCondVals=SetCondVals;
	this.GetCondVals=GetCondVals;
	
	//private methods
	function BuildCond(varCondFields,objDataMgr,varCondVals){
		var strCond="";
		var blnGetFromDoc=true;
		var blnNoCond=false;
		
		var strVal="";
		if (objDataMgr){
			if(varCondFields){
				if(varCondVals){
					if(varCondFields.length==varCondVals.length){
						for(x=0;x<varCondFields.length;x++){
							strVal=varCondVals[x];
							if(strVal=="%RecordNumber%"){
								if(m_objRecord){
									strVal=m_objRecord.GetRecordId();
									if(strVal<=0 || strVal==""){
										blnNoCond=true;
										break;
									}
								}
							}
							strCond+=varCondFields[x] + "=" + strVal + "&";
						}
						strCond=g_MqRef.MqStr.StripTrailing(strCond, "&");
						strCond=g_MqRef.MqStr.MqEncodeURIComponent(strCond);
						blnGetFromDoc=false;
					}
				}
				if(blnNoCond){
					strCond="";
				}else{
					if(blnGetFromDoc){
						strCond=objDataMgr.GetObjFieldValues().GetFromDocument(varCondFields);		
					}
				}
			}
		}
		return strCond;
	}
	
	function IsCondChanged(strCurrentCond,strNewCond){
		return !(strCurrentCond==strNewCond);
	}

	function IsDVLoaded(varDVFields,objDataMgr)
	{
		var blnLoaded =true;
		if (varDVFields && objDataMgr){
			for(var i=0;i<varDVFields.length;i++){
				if (!objDataMgr.GetFieldValue(varDVFields[i],false,false)){
					blnLoaded=false;
					break;
				}
			}
		}
		return blnLoaded;
	}
	
}