/**
 * this function is used for ListField selectboxes
 * in the future this should also be used for other selectboxes
 */
function doUpdateOptions(fieldObj, path, id, keepCurrent, maatwerk, param)
{
	if(fieldObj==null || fieldObj.options == null){return;}
	//create url
	
	var url = "./getListOptions.jsp?";
	if (maatwerk != undefined)
		url = "./" + maatwerk + "?";
	if (param != undefined)
		url += param + "&";
	
	if (path)
		url += "path="+path;
	else
		url += "id="+fieldObj.name;
	
	if (keepCurrent !== false)
	{
		url += "&value=" + fieldObj.value;
	}
	if (id)
		url += "&identifier=" + id;
	else if (document.getElementById("id"))
		url += "&identifier=" + document.getElementById("id").value;
	
	url = addParentParams(url, fieldObj);
	var xmlRequestObj = getAjaxRequestObject();
	xmlRequestObj.onreadystatechange = 	function(){doUpdateOptionsReady(xmlRequestObj,fieldObj);}
	xmlRequestObj.open("GET",url,true);
	xmlRequestObj.send(null);
}
/**
 * this function is used for ListField selectboxes
 * will be called upon onreadystatechange of ajax request
 */ 
function doUpdateOptionsReady(xmlRequestObj,fieldObj) 
{
	if(xmlRequestObj.readyState == 4 && (xmlRequestObj.status == 200 || xmlRequestObj.status == 304)) 
	{
		var value = fieldObj.value;
		
		//clear current options
		while(fieldObj.length>0){fieldObj.remove(0);}
		var xml = parseXml(xmlRequestObj.responseText).documentElement;
		if (!xml) return;

		var hasDefault = false;
		var selectedIndex = 0;
		for(var i=0;i<xml.childNodes.length;i++)
		{
			var optionNode = xml.childNodes[i];
			var id = optionNode.getAttribute("id");
			var alias = optionNode.getAttribute("alias");
			var fg = optionNode.getAttribute("fgcolor");
			var bg = optionNode.getAttribute("bgcolor");
			
			var name = "";
			if (optionNode.childNodes.length != 0)
				name = optionNode.childNodes[0].nodeValue;
			
			if(id==value)
			{
				selectedIndex=i;
				fieldObj.defaultValue = id;
				hasDefault = true;
			}
			
			fieldObj.options[i] = new Option(name,id);		
			fieldObj.options[i].alias = alias;
			fieldObj.options[i].setAttribute("alias", alias);
			if (fg) fieldObj.options[i].style.color = fg;
			if (bg) fieldObj.options[i].style.backgroundColor = bg;
		}
		fieldObj.selectedIndex = selectedIndex;
		
//		if (!hasDefault)
//			fieldObj.defaultValue = fieldObj.options[0].value;

		if(fieldObj.selectedIndex==0 && fieldObj.options.length==2 && document.getElementById(fieldObj.id + "_autoselect").value == "true")
		{
			if(!isdefined("autoselectonlyoption",fieldObj) || fieldObj.autoselectonlyoption=="true")
			{
				fieldObj.selectedIndex=1;
			}
		}
		
		if (value != fieldObj.value)
			$(fieldObj).trigger("change"); 
	}
}

/**
 * Updates all related fields.
 * @param fieldObj
 * @param value
 * @param path
 * @return
 */
function doUpdateLinkRelations(fieldObj)
{
	var empty = fieldObj.value == "";

	//create url
	var url = "./getRelatedOptions.jsp?id=" + fieldObj.id + "&value=" + fieldObj.value;
	var appendix = fieldObj.id.replace(/^formfield_\d+(_-?\d+)?(_.+)?$/, "$1");

	var params = "";
	
	var arr = new Array();
	var parents = document.getElementsByName(fieldObj.id + "_parents");
	for (var i = 0; i < parents.length; i++) {
		arr.push(parents[i]);
	}
	
	if (appendix && window.tabAppendedParents[appendix.substring(1)]) {
		for (var i = 0; i < window.tabAppendedParents[appendix.substring(1)].length; i++) {
			arr.push(window.tabAppendedParents[appendix.substring(1)][i]);
		}
	}
	parents = arr;

	if (parents.length > 0) {
		for (var i = 0; i < parents.length; i++) {
			if (parents[i].className != "path") {
				if (empty) {
					var field = document.getElementById("formfield_" + parents[i].value + appendix);
					var displayField = document.getElementById("formfield_" + parents[i].value + appendix + "_display");
					if (!field) field = document.getElementsByName("insert_" + parents[i].value + appendix)[0];
					if (!field || hasClass(parents[i], "linkfield")) continue;

					field.value = "";
					if (displayField)
						displayField.value = "";
				} else {
					url += "&parentFieldId=" + parents[i].value;
				}
			}
		}
	}
	// Maak alle verborgen gerelateerde velden leeg.
	if (empty) 
		return;
	var fieldAppendix = fieldObj.id.replace(/^formfield_\d+(_-?\d+)?(_.+)?$/, "$1");
	var xmlRequestObj = getAjaxRequestObject();
	xmlRequestObj.onreadystatechange = 	function(){doUpdateLinkRelationsReady(xmlRequestObj, fieldAppendix, fieldObj);}
	xmlRequestObj.open("GET",url,true);
	xmlRequestObj.send(null);		
}
function doUpdateLinkRelationsReady(xmlRequestObj,fieldAppendix, sourceField) 
{
	if(xmlRequestObj.readyState == 4 && (xmlRequestObj.status == 200 || xmlRequestObj.status == 304)) 
	{
		var xml = parseXml(xmlRequestObj.responseText).documentElement;
		if (!xml) return;
		for(var i=0;i<xml.childNodes.length;i++)
		{
			var optionNode = xml.childNodes[i];
			if (!optionNode.nodeName) continue;
			var field = optionNode.getAttribute("field");
			var originalField = field;
			var displayValue = optionNode.getAttribute("displayValue");
			var postValue = optionNode.getAttribute("postValue");
			var addName = optionNode.getAttribute("add");
			var executeOnblur = optionNode.getAttribute("onblur");

			if (/_/.test(field))
				field = document.getElementById("formfield_" + field);
			else
				field = document.getElementById("formfield_" + field + fieldAppendix);
			
			if (!field) field = getFieldObject(originalField, fieldAppendix);
			
			// Als het veld niet bestaat of readonly is, en er is een add property aanwezig, maak het veld dan aan.
			if ((!field || hasClass(field, "readonly")) && addName)
			{
				if (getFieldObject(pathField[originalField + "_add"]))
				{
					getFieldObject(pathField[originalField + "_add"]).value = postValue;
				}
				else
				{
					var element = createElement("input", "hidden", addName, addName)
					element.value = postValue;
					document.bodyform.appendChild(element);
					pathField[originalField + "_add"] = addName;
				}
			}

			if (!field)
				continue;
			var displayField = document.getElementById(field.id + "_display");
			var oldFieldValue = field.value;
			var oldDisplayValue;
			if (displayField)
				oldDisplayValue = displayField.value;
			
			// Set the display value and post value for the correct field.
			if (displayField) {
				field.value = postValue;
				displayField.value = displayValue;
			} else {
				field.value = postValue;
			}
			
			// Perform onchange events if they exist and if the value has changed.
			if ((!executeOnblur || executeOnblur == "true") &&  oldFieldValue != field.value){
				$(field).trigger("change");
				$(field).trigger("onblur");
			}
			if ((!executeOnblur || executeOnblur == "true") &&  displayField && oldDisplayValue != displayField.value) {
				$(displayField).trigger("change");
				$(displayField).trigger("onblur");
			}
		}
	}
}

/** 
 * this function is used for LinkField selectboxes and 
 * will call update of all related childFields
 */
function doUpdateOptionsChildLinkField(fieldObj) {
	// Give the child link fields new options.
	doUpdateFirstChildLinkField(fieldObj);

	var path = pathField[fieldObj.id];
	$("*[name=" + path + "_children]").map(function(x,a) {
		var elem = document.getElementById(a.value);
		if (elem) {
			doUpdateOptions(elem, undefined, undefined, false);
		}
	});
	
	// Give the non link fields new values.
	doUpdateLinkRelations(fieldObj);
}
/**
 * Updates the first child link field.
 * @param fieldObj
 * @return
 */
function doUpdateFirstChildLinkField(fieldObj, fromClear) 
{
	var path = pathField[fieldObj.name];
	if(!path)
	{
		//alert(fieldObj.name+" could not be resolved to a path?");
		return;
	}
	var post;
	if (/formfield_\d+(_.+)/.test(fieldObj.id))
		post = RegExp.$1;
		
	while(path.split(".").length > 2) 
	{
		path = path.replace(/\.[^\.]+$/, "");
		var field = getFieldObject(path, post);

		if (field) 
		{
			if (fromClear && /input/i.test(field.tagName)) {
				field.value = '';
				doUpdateLinkRelations(field);
			} else {
				var tab = getEnclosingElem(fieldObj, "div");
				if (tab)
					tab = getEnclosingElem(tab.parentNode, "div");
				
				if (!tab && document.getElementById("editIds_" + post))
					doUpdateOptions(field, undefined, document.getElementById("editIds_" + post).value, false);
				else if (tab && /smiletable_(\d+)/.test(tab.id))
					doUpdateOptions(field, undefined, document.getElementById("editIds_"+RegExp.$1+post).value, false);
				else
					doUpdateOptions(field, undefined, undefined, false);
			}
			break;
		}
	}
}
function updateChildFieldsFromName(name) {
	map( document.getElementsByName(name + "_children"), function(a) {
		var elem = document.getElementById(a.value);
		if (elem) {
			doUpdateOptions(elem);
		}
	});
}
/**
 * this function is used for ListField selectboxes and will call update of all
 * related childFields
 */
function doUpdateOptionsChildField(fieldObj)
{
  // Give the child link fields new options.
  doUpdateFirstChildLinkField(fieldObj);

  updateChildFieldsFromName( fieldObj.id );
  updateChildFieldsFromName( pathField[fieldObj.id] );
  
  if (!document.getElementById(fieldObj.id + "_child")) 
	  return;
  
  var childPaths = document.getElementById(fieldObj.id + "_child").value;
  if (childPaths == "")
	  return;
  
  var childField;;
  if (/formfield_\d+(_-?\d+)/.test(fieldObj.id))
  	childField = document.getElementById(pathField[childPaths] + RegExp.$1);
  else
  {
	var arr = getFieldObjectArr(childPaths);
	for (var i = 0; i < arr.length; i++)
	{
		childField = arr[i];
		if (childField != null)
			  doUpdateOptions(childField);
	}
	return;
  }
  if (childField != null)
	  doUpdateOptions(childField);
}
/**
 * This function is used for LinkField select boxes
 * in the future these functions should be phased out
 *
 * selectBox: Select element
 * listId: id of list
 * valueId: id of selected value (ignored if null)
 */
function setOptions(selectBox,options,value)
{
	var selectedIndex = 0;
	var optionList = null;
	if(selectBox==null){return;}
	if(!options || !options.length || options.length==0)
	{
		options = new Array(new Option('-','')); 
	}
	selectBox.length=0;
	for(i=0;i<options.length;i++)	
	{
		if(options[i]!=null) 
		{
			if(options[i].value==value){selectedIndex=i;}
			// clone the option else options array can only be used once
			var option = new Option(options[i].text, options[i].value);
			selectBox.options[i] = option;
		}
	}
	selectBox.selectedIndex = selectedIndex;
	if(selectBox.selectedIndex==0 && selectBox.options.length==2)
	{
		if(!isdefined(selectBox,"autoselectonlyoption") || selectBox.autoselectonlyoption=="true")
		{
			selectBox.selectedIndex=1;
		}
	}
}
 /**
  * selects the options in the selectbox
  */
function select_option(selectBox,value)
{
	if(selectBox==null || isEmpty(value)){return;}
 	for(i=0;i<selectBox.options.length;i++)	
	{
		var option = selectBox.options[i];
		if(option!=null && option.value==value){selectBox.selectedIndex=i;break;}
	}
}

function addParentParams(url, fieldObj) {
	var postFix = "";
	if (/\d+(_-?\d+)$/.test(fieldObj.id))
		postFix = RegExp.$1;
	// Top-Down
	var parents = document.getElementsByName(fieldObj.id + "_parents");
	if (parents.length > 0) {
		for (var i = 0; i < parents.length; i++) {
			// If the parent is a linkfield, add the value to the filter list.
			if (parents[i].className == "linkfield" || parents[i].className == "listfield") {
				var field = document.getElementById("formfield_" + parents[i].value + postFix);
				if (!field || field.className == "readonly") continue;
				
				// Field is searchfield but parent is not.
				if (fieldObj.tagName.toLowerCase() == "input" && field.tagName.toLowerCase() != "input")
					continue;

				url += "&parentValue=" + parents[i].value + "=" + field.value;
			}
			else if (parents[i].className == "path") {
				var fieldPath = parents[i].value;
				var field = getFieldObject(fieldPath);
				var originalPath = fieldPath;
				var usedPath = fieldPath;
				var index = 0;
				
				do {
					field = getFieldObject(fieldPath);
					usedPath = fieldPath;
					fieldPath = fieldPath.replace(/\.[^\.]+$/, "");					
				}
				while (!field && fieldPath.indexOf(".") != -1);
				
				if (originalPath != usedPath)
				{
					map( document.getElementsByName(originalPath + "_children"), function (a) {if (a) a.name = usedPath + "_children"});
				}
				
				if (field) {
					var fieldAppendix = fieldObj.id.replace(/^formfield_\d+(_-?\d+)?(_.+)?$/, "$1");
					if (!document.getElementById(field.id + fieldAppendix)) continue;
					url += "&thisHandlerValue=" + field.id.replace("formfield_", "") + "=" + document.getElementById(field.id+ fieldAppendix).value;
				}
			}
		}
	}
	
	//pass parent value's in url
	var parentHiddenFieldObj = document.getElementById(fieldObj.id + "_parent");
	if (parentHiddenFieldObj != null && parentHiddenFieldObj.value!="")
	{
		var parentPaths = parentHiddenFieldObj.value.split(",");
		for(var i=0;i<parentPaths.length;i++)
		{
			var parentFieldObj = getFieldObject(parentPaths[i], postFix);
			if(parentFieldObj!=null){url=url+"&parentvalue"+i+"="+parentFieldObj.value;}
			else if (parentPaths[i] != "")
				url=url+"&parentvalue"+i+"="+parentPaths[i];
		}
	}
	
	var href = location.href;
	while (/(link_.*?=.*?)($|&)/.test(href)) {
		url += "&" + RegExp.$1;
		href = href.replace(/(link_.*?=.*?)($|&)/, "");
	}
	return url;
}