// called onchange of a filter ddl
function UpdateQueryFilter(pDdlId, pFormFieldId, pAutoComplete, pAutoHide, pOptionLimit){
	var b = new ncBrowserObj();
	var oDdl = document.getElementById(pDdlId);
	
	var exp = GetQueryFilterExp();
	if(exp.test(oDdl.name)){
		exp.exec(oDdl.name);
		var fieldPrefix = RegExp.$1;
		var fieldId = RegExp.$2;
		var level = RegExp.$3; 
		var oReqDom = ncXml.createDomBase("Request", ["@type", "LoadFilterOptions", "@siteid", ncSiteId, "@featureid", ncFeatureId, 
										"@formfieldid", pFormFieldId, "@level", level, 
										"@optionlimit", pOptionLimit, "@value", oDdl[oDdl.selectedIndex].value]);
		var oRetMethod = new Function("LoadQueryFilter_Return(arguments[0], '" + oDdl.id + "', " + pFormFieldId + ", " + pAutoComplete + ", " + 
									pAutoHide + ", " + pOptionLimit + ");");
		ncXml.sendXmlHttpRequest(ncBaseHref + "../v/nc/FormLink_Remote.nc", oRetMethod, oReqDom);
	}
}
function GetQueryFilterExp(){
	return /^(Field_)(\d+)_Filter(\d+)$/i;
}
function LoadQueryFilter_Return(p_oXmlHttp, pDdlId, pFormFieldId, pAutoComplete, pAutoHide, pOptionLimit){
	if(p_oXmlHttp.readyState == 4){
		var ok = false;
		if(p_oXmlHttp.status == 200){
			try{
				var oDom = p_oXmlHttp.responseXML;
				var oDocEl = oDom.documentElement;
				if(oDocEl.tagName == "Response" && oDocEl.getAttribute('ok') == 1){
					var oDdl = document.getElementById(pDdlId);
					var exp = GetQueryFilterExp();
					exp.exec(oDdl.name);
					var fieldPrefix = RegExp.$1;
					var fieldId = RegExp.$2;
					var level = parseInt(RegExp.$3, 10); 
					var ddl = oDdl;
					
					var targetDdlId;
				
					// clear ddls down the hierarchy
					for(var i = level - 1; i >= -1; i--){
						targetDdlId = fieldPrefix + fieldId;
						if(i >= 0){
							targetDdlId += "_Filter" + i;	
						}
						var ddl = oDdl.form[targetDdlId];
						ddl.style.display = "";
						ddl.form[targetDdlId + "_Search"].style.display = "none";
						ddl.form[targetDdlId + "_Text"].style.display = "none";
						for(var j = ddl.options.length - 1; j > 0; j--){
							ddl.remove(j);
						}
						ddl.disabled = true;
					}
					targetDdlId = fieldPrefix + fieldId;
					if(level > 0){
						targetDdlId += "_Filter" + (level - 1);	
					}
					var targetDdl = oDdl.form[targetDdlId];
					
					// clear text preview (may be hidden using display: none;)
					var preview = oDdl.form[targetDdlId + "_Text"];
					preview.value = "";
					
					var search = oDdl.form[targetDdlId + "_Search"];
					var oOptionEls = ncXml.selectNodes(oDocEl, "Options/Option");
					if(parseInt(oDocEl.getAttribute("TotalResults"), 10) > pOptionLimit){
						// show search
						targetDdl.style.display = "none";
						preview.style.display = "";
						search.style.display = "";
					}else{
						// show ddl
						preview.style.display = "none";
						targetDdl.style.display = "";
						search.style.display = "none";
						
						if(oOptionEls.length > 0){
							targetDdl.disabled = false;
							for(var i = 0; i < oOptionEls.length; i++){
								var o = new Option(ncXml.getNodeText(oOptionEls[i]), oOptionEls[i].getAttribute("Value"));
								targetDdl.options.add(o);
							}
						}
					}	
					if(pAutoComplete){
						if(oOptionEls.length == 1){
							// auto-complete - only one option
							targetDdl.selectedIndex = 1;
							if(level > 0){
								// load next level of cascade
								UpdateQueryFilter(targetDdl.id, pFormFieldId, pAutoComplete, pAutoHide, pOptionLimit)
							}else{
								if(pAutoHide){
									// hide if only one option
									ShowHideQueryFilter(targetDdl, false);
								}
							}
						}else{
							if(pAutoHide){
								// show all ddls further down
								for(var i = level; i >= -1; i--){ 
									var ddlId = fieldPrefix + fieldId;
									if(i >= 0){
										ddlId += "_Filter" + i;	
									}
									ShowHideQueryFilter(oDdl.form[ddlId], true);
								}	
							}
						}
						if(pAutoHide){
							// hide parent ddl if there is one - it may have been autocompleted
							// (if display: none; a search is showing do not hide that)
							if(oDdl.length == 2 && oDdl.style.display != 'none'){
								ShowHideQueryFilter(oDdl, false);
							}
						}
					}
					ok = true;
				}
			}catch(e){}
		}
		if(!ok){
			alert("Sorry, load of options failed.");
		}
	}
}
function ShowHideQueryFilter(p_oDdl, p_bShow){
	var oParentEl = p_oDdl.parentNode;
	var sTagName = oParentEl.tagName.toLowerCase();
	while(sTagName != "td" && sTagName != "div"){
		oParentEl = oParentEl.parentNode;
		sTagName = oParentEl.tagName.toLowerCase();
	}
	if(sTagName == "div"){
		oParentEl.style.display = p_bShow ? '' : 'none';
	}else{
		var oRow = oParentEl.parentNode;
		for(var j = 0; j < oRow.cells.length; j++){
			oRow.cells[j].style.display = p_bShow ? '' : 'none';
		}
	}				
}
function SearchFormLink(pSearchButton, pFormFieldId, pAutoComplete, pAutoHide, pOptionLimit){
	var b = new ncBrowserObj();
	var exp = /^(Field_)(\d+)(?:_Filter(\d+))?_Search$/i;
	if(exp.test(pSearchButton.id)){
		var fieldId = pSearchButton.id.replace(exp, "$2");
		var level = pSearchButton.id.replace(exp, "$3");
		if(level == ""){
			level = -1;
		}else{
			level = parseInt(level, 10);
		}
		var previousFilterId = pSearchButton.id.replace(exp, "$1") + fieldId + "_Filter" + (level + 1);
		var previousFilterValue = 0;
		var previousFilterEl = document.getElementById(previousFilterId);
		
		// get current field value & text represenation
		var fieldName = pSearchButton.id.replace(/_Search$/, "");
		var value = 0, text = "";
		var fld = pSearchButton.form[fieldName];
		if(fld.tagName.toLowerCase() == "input"){
			value = fld.value;
			text = document.getElementById(fieldName + "_Text").value;
		}else if(fld.tagName.toLowerCase() == "select" && fld.selectedIndex != -1){
			var opt = fld[fld.selectedIndex];
			value = opt.value == "" ? 0 : parseInt(opt.value, 10);
			if(value > 0){
				text = opt.text;
			}
		}
		
		if(previousFilterEl){
			previousFilterValue = previousFilterEl.options[previousFilterEl.selectedIndex].value;
		}
		
		var a = {SiteId: ncSiteId, FeatureId: ncFeatureId, FormFieldId: pFormFieldId, 
							Level: level, PreviousFilterValue: previousFilterValue, Value: value, Text: text};
		var retMethod = new Function("SearchFormLink_Return(arguments[0], '" + pSearchButton.id + "', " +
									"'" + pFormFieldId + "', " + pAutoComplete + "," + pAutoHide + "," + pOptionLimit + ");");
		//ncModal.Show(ncBaseHref + "../v/htm/FormLinkPicker.htm", a, retMethod, null, 330, 350, false, true);
		top.ncIFrameModals.Show(top.ncBaseHref + '../v/htm/FormLinkPicker.htm', a, retMethod, null, 325, 325, window, true);
	}	
}
function SearchFormLink_Return(p_oSelection, p_sSearchBtnId, pFormFieldId, pAutoComplete, pAutoHide, pOptionLimit){
	if(p_oSelection){
		var oBtn = document.getElementById(p_sSearchBtnId);
		var f = oBtn.form;
		var fn = oBtn.id.replace("_Search", "");
		
		// update read-only text
		f.elements[fn + "_Text"].value = p_oSelection.Text;
		
		// update value field - hidden or hidden ddl if filters
		var oField = f.elements[fn];
		if(oField.tagName.toLowerCase() == 'input'){
			// single input field
			oField.value = p_oSelection.Value;
		}else{
			// filters
			for(var j = oField.options.length - 1; j > 0; j--){
				oField.remove(j);
			}
			var option = new Option(p_oSelection.Text, p_oSelection.Value);
			oField.options.add(option);
			option.selected = true;
			oField.disabled = false;
			UpdateQueryFilter(oField.id, pFormFieldId, pAutoComplete, pAutoHide, pOptionLimit);	
		}
	}
}
function SearchHashFormLink(pSearchButton, pFormFieldId){
	var ret = showModalDialog(ncBaseHref + "../v/htm/FormHashPicker.htm",
			{SiteId: ncSiteId, FeatureId: ncFeatureId, FormFieldId: pFormFieldId}, 
			"dialogWidth: 330px; dialogHeight: 360px; help: no; status: yes;");
	if(ret){
		var f = pSearchButton.form;
		var fieldName = pSearchButton.id.replace(/_Search$/, "");
		f[fieldName + "_Text"].value = ret.Text;
		f[fieldName].value = ret.Hash;
	}
}
function InitRecordLinkListBox(p_sFieldName, p_lFormFieldId, p_oSelectedArr){
	var sName = p_sFieldName + '_ListBox';
	var lb = window[sName] = new ncListBox(sName);
	lb.UpDownButtons = lb.EditButton = false;
	lb.AddValueCol('Value');
	lb.AddTextCol('Text', 200);
	lb.AddHandler = RecordLinkListBox_Add;
	lb.ClientData = {FormFieldId: p_lFormFieldId};
	lb.Build(document.getElementById(sName + 'Div'));
	
	lb.Refresh();
}
function RecordLinkListBox_Add(p_oListBox){
	var oArgs = {SiteId: ncSiteId, FeatureId: ncFeatureId, MultiplePick: true, FormFieldId: p_oListBox.ClientData.FormFieldId};
	var oRetMethod = new Function("return RecordLinkListBox_Add_Return(arguments[0], '" + p_oListBox.Name.replace('_ListBox', '') + "');");
	//ncModal.Show(ncBaseHref + "../v/htm/FormLinkPicker.htm", oArgs, oRetMethod, null, 330, 350, false, true);
	top.ncIFrameModals.Show(top.ncBaseHref + '../v/htm/FormLinkPicker.htm', oArgs, oRetMethod, null, 325, 325, window, true);
}
function RecordLinkListBox_Add_Return(p_oRetVal, p_sFieldName){
	if(p_oRetVal){
		var oListBox = window[p_sFieldName + '_ListBox'];
		
		var oDataArr = oListBox.Data;
		for(var i = 0; i < oDataArr.length; i++){
			if(p_oRetVal.Value == oDataArr[i][0]){
				return 'Selection not added - already selected.';
			}
		}
		oListBox.AddElement([p_oRetVal.Value, p_oRetVal.Text]);
		oListBox.Refresh();
		RecordLinkListBox_Update(p_sFieldName);
	}
	return true;
}
function RecordLinkListBox_Update(p_sFieldName){
	var sTemp = '';
	var oDataArr = window[p_sFieldName + '_ListBox'].Data;
	for(var i = 0; i < oDataArr.length; i++){
		sTemp += (i > 0 ? ',' : '') + oDataArr[i][0];
	}
	document.getElementById(p_sFieldName).value = sTemp;
}
