
function forceSubmit(formName) {
	document.forms[formName].submit();
	document.forms[formName].target = '';
}

function _jevent_getValue(formName, elementName) {
	if(document.forms[formName] && document.forms[formName].elements[elementName])
		return document.forms[formName].elements[elementName].value;
	else
		return '';
}

function _jevent_setValue(formName, elementName, wert) {
	setWindowValue(document, formName, elementName, wert);
}

function _jevent_openWindow(url, name, options) {
	if (!options) {
		options = 'directories=no,left=50,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no,top=50,width=640,height=480';
	}
	var resultWindow = window.open(url, name, options);
	if (!resultWindow) {
		alert('Es konnte kein neues Fenster erzeugt werden.\nBitte überprüfen Sie die Einstellungen ihres Popup-Blockers.');
	}
	return resultWindow;
}

function setWindowValue(doc, formName, elementName, wert) {
	if (doc.forms[formName] && doc.forms[formName].elements[elementName]) {
		doc.forms[formName].elements[elementName].value = wert;
	}
}

function submitEintragDetails(formName, formAction, elementName, wert, width) {
	if(!width) {
		width = 1024;
	}
	var name = 'detailsWindow';
	if (window.opener) {
		name = name + '2';
	}
	_jevent_openWindow('', name, 'directories=no,left='+(screen.width/2 - width/2)+',location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no,top=50,width='+ width +',height=570');
	document.forms[formName].target = name;
	submitDetails(formName, formAction, elementName, wert);
}

function submitDetails(formName, formAction, elementName, wert) {
	_jevent_setValue(formName, elementName, wert);
	_jevent_setValue(formName, 'aktion', formAction);
	forceSubmit(formName);
}

function submitPage(formName, formAction, elementName, wert) {
	_jevent_setValue(formName, formName + '_suche', 1);
	submitDetails(formName, formAction, elementName, wert);
}

function submitSortWithDirection(formName, formAction, elementName, wert){
	var value = _jevent_getValue(formName, elementName);
	if (value.indexOf(wert) == 0) {
		if (value.indexOf("ASC") > 0) {
			wert += " DESC";
		} else {
			wert += " ASC";
		}
	} else {
		wert += " ASC";
	}
	submitSort(formName, formAction, elementName, wert);
}

function submitSort(formName, formAction, elementName, wert){
	submitQuery(formName, formAction, elementName, wert)
}

function submitStructure(formName, formAction, elementName, wert) {
	submitDetails(formName, formAction, elementName, wert);
}

function submitQuery(formName, formAction, elementName, wert){
	_jevent_setValue(formName, '__'+ formName +'_page', 1);
	_jevent_setValue(formName, formName + '_suche', 1);
	submitDetails(formName, formAction, elementName, wert);
}

function closeWindow() {
	window.close();
}

function showImage(id) {
	var url = document.getElementById(id).src;
	var imageWindow = _jevent_openWindow('', 'imageWindow', 'directories=no,left=100,location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no,dependent=yes,top=50,width=1024');
	imageWindow.document.open();
	imageWindow.document.write("<html><head><script src='javascript/jEvent.js' type='text/javascript'></script></head><body onload='adjustWindowSize((top.outerWidth ? 0 : 24),0,true);' style='margin:0px;'><img border='0' id='img1' src='"+ url +"' alt='' /></body></html>");
	imageWindow.document.close();
}

function toggleImage(id, url, description) {
	document.getElementById(id).src = url;
	if(description) {
		document.getElementById(id).alt = description;
		document.getElementById(id).parentNode.title = description;
	}
}

function showLocation(name, street, zip, city) {
	_jevent_openWindow('location.jsp?name='+ name +'&street=' + street + '&zip=' + zip + '&city='+ city, 'locationWindow', 'directories=no,height=480,left=100,location=no,menubar=no,resizable=yes,scrollbars=no,status=no,toolbar=no,dependent=yes,top=50,width=798');
}

function setWindowSize(width, height){
	if (this.document.body && this.document.body.scrollWidth){
		width = this.document.body.scrollWidth + 10;
		height = this.document.body.scrollHeight + 20;
	}
	if (this.window.sizeToContent){
		this.window.sizeToContent();
	} else if (this.window.innerWidth){
		this.window.innerWidth = this.document.width;
		this.window.innerHeight = this.document.height;
	} else if (this.window.resizeTo){
		this.window.resizeTo(width,height);
	} 
}

function adjustWindowSize(extra_x, extra_y, fitScreen){
	if (extra_x == undefined)
		extra_x = 0;
	if (extra_y == undefined)
		extra_y = 0;
	if(fitScreen == undefined)
		fitScreen = false;
	_adjustWindowSize(extra_x, extra_y, fitScreen);
	setTimeout("_adjustWindowSize(" + extra_x + "," + extra_y + "," + (fitScreen ? "true" : "false") + ")",0);
}

function _getAbsoluteOffset(e) {
	if (!e.offsetWidth)
		return undefined;
	var ofs = e.offsetParent ? _getAbsoluteOffset(e.offsetParent) : [0,0];
	ofs[0] += e.offsetLeft;
	ofs[1] += e.offsetTop;
	ofs[2] = e.offsetWidth;
	ofs[3] = e.offsetHeight;
	return ofs;
}

function _adjustWindowSize(extra_x, extra_y, fitScreen){
	var queue = [document.body];
	var x = 0;
	var y = 0;

	for (var i = 0; i < queue.length; i++) {
		if (queue[i].nodeName == "FORM" || queue[i].nodeName == "BODY" || queue[i].nodeName == "DIV") {
			var l = queue[i].childNodes;
			for (var j = 0; j < l.length; j++)
				queue.push(l[j]);
		} else if (queue[i].offsetWidth) {
			var ofs = _getAbsoluteOffset(queue[i]);
			var x2 = ofs[0]+ofs[2];
			var y2 = ofs[1]+ofs[3];
			if (x2 > x)
				x = x2;
			if (y2 > y)
				y = y2;
		}
	}	
	
	if (top.outerWidth && top.innerWidth && top.outerHeight && top.innerHeight) {
		x += top.outerWidth - top.innerWidth;
		y += top.outerHeight - top.innerHeight;
		window.resizeTo(x + extra_x, y + extra_y);
	} else {
		x -= document.body.parentNode.offsetWidth;
		y -= document.body.parentNode.offsetHeight;
		x += extra_x;
		y += extra_y;
		window.resizeBy(x + 48, y + 48);
		window.resizeBy(-48, -48);
	} 
	
	if(fitScreen) {
		var screenHeight = screen.availHeight - 24;
		var screenWidth = screen.availWidth - 24;
		var windowHeight = window.outerHeight || document.body.parentNode.offsetHeight;
		var windowWidth = window.outerWidth || document.body.parentNode.offsetWidth;

		var new_x = windowWidth, new_y = windowHeight;
		if(windowWidth > screenWidth)
			new_x = screenWidth;
		if(windowHeight > screenHeight)
			new_y = screenHeight;
		if (top.outerWidth)
			window.resizeTo(new_x, new_y);
		else
			window.resizeBy(new_x - document.body.parentNode.offsetWidth, new_y - document.body.parentNode.offsetHeight);
	}
}

var ACTIVE_MENU = null;
function activateMenu(ctrl) {
	if (ACTIVE_MENU) {
		ACTIVE_MENU.className = '';
	}

	ACTIVE_MENU = ctrl;
	ctrl.className = 'active';
}

function selectGebiet(ctrlName, ctrl) {
	var structureKey = ctrl.options[ctrl.selectedIndex].value;
	initGebiet(ctrlName, structureKey, 0);
}

function setGebiet(ctrlName, structureKey, label) {
	var ctrl = document.getElementById(ctrlName);
	if (ctrl) {
		ctrl.value = structureKey;
	}
	ctrl = document.getElementById(ctrlName+ '_view');
	if (ctrl) {
		ctrl.innerHTML = label;
	}
}

function initGebiet(ctrlName, curStructureKey, extension, trials) {
	clearSelectBoxes(ctrlName);
	var url = "structurehandler?structureKey=" + curStructureKey + "&ctrlName=" + ctrlName;
	if(extension) {
		url += "&"+ ctrlName +"_ext="+ extension;
	}

	var request = null;
	try {
		request = createHttpRequest(url, "GET");
	} catch (e) {
		alert('could not retrieve url ' + url + ':' + "\n" + e);
	}

	if (request != null && request.readyState == 4 && request.responseText.toLowerCase().indexOf("bad request") == -1) {
		var xml = request.responseXML;
		var label = structureXmlToSelectBox(ctrlName, xml);
		setGebiet(ctrlName, curStructureKey, label);
	} else if (trials < 2) {
		window.setTimeout("initGebiet('" + ctrlName + "', '" + curStructureKey + "', '"+ extension +"', '" + trials+1 + "')", 100);
	} else {
		alert('Die Gebietskomponente konnte nicht initialisiert werden!\n\n' + request.responseText);
	}
}

function checkRegionSelect(name) {
	var div = document.getElementById('div_'+ name +'_boxes');
	var select;
	for (var i=div.childNodes.length-1; i >= 0 && !select; i--) {
		if (div.childNodes[i] && div.childNodes[i].style.display != 'none')
			select = div.childNodes[i];
	}
	if (select && select.options) {
		var optionIndex=select.selectedIndex ? select.selectedIndex : 0;
		var value = select.options[optionIndex].value;
		var regionLength = parseInt(select.getAttribute("structureIndex")) * 4;
		if (value) {
			value = value.substr("brd-rpn-".length);
			if (value.length < regionLength) {
				alert("Bitte wählen Sie eine Stadt bzw. einen Ort innerhalb Ihres momentan gewählten Gebietes aus!");
				return false;
			}
		}
	}
	return true;
}

function clearSelectBoxes(ctrlName) {
	var destCtrl = document.getElementById('div_'+ ctrlName +'_boxes');

	for (var i = 0; i<=destCtrl.childNodes.length; i++) {
		var curNode = destCtrl.childNodes[i];
		if (curNode) {
			curNode.length = 0;
			curNode.style.display = 'none';
		}
	}
	destCtrl = document.getElementById('div_'+ ctrlName +'_ext');
	if (destCtrl) {
		destCtrl.style.display = 'none';
	}
	destCtrl = document.getElementById(ctrlName +'_ext');
	if (destCtrl) {
		destCtrl.length = 0;
	}
}

var JEVENT_STRUCTURE_IS_SELECTABLE = new Array();
function structureXmlToSelectBox(ctrlName, xml) {
	var label = 'Land Rheinland-Pfalz';
	var selectBoxes = xml.firstChild.childNodes;

	var destCtrl = document.getElementById('div_' + ctrlName + '_boxes');
	if (destCtrl) {
		for (var j = 0; j < selectBoxes.length; j++) {
			var selectBox = document.getElementById(selectBoxes[j].nodeName);
			if (j == 4 && !selectBox) {
				selectBox = document.getElementById(ctrlName+'_ext');
			}
			if (selectBox) {
				var optionItems = selectBoxes[j].childNodes;
				var selectedIndex = -1;
				for (var i = 0; i < optionItems.length; i++) {
					var selected = (optionItems[i].getAttribute("selected") != null && optionItems[i].getAttribute("selected") != '' ? true : false);
					var selectable = (optionItems[i].getAttribute("selectable") != null && optionItems[i].getAttribute("selectable") == 1 ? optionItems[i].getAttribute("selectable") : '');
					var tmpStructureKey = optionItems[i].getAttribute("structureKey")

					if (selectable) { 
						JEVENT_STRUCTURE_IS_SELECTABLE.push(tmpStructureKey);
					}

					if (selected) {
						selectedIndex = i;
						label = optionItems[i].getAttribute("label");
					}
					var opt = createOption(tmpStructureKey, optionItems[i].getAttribute("label"), optionItems[i].getAttribute("selected"));
					selectBox.appendChild(opt);
				}

				if (j<4) {
					destCtrl.appendChild(selectBox);
					selectBox.style.display = 'block';
				} else {
					var destCtrl2 = document.getElementById('div_' + ctrlName + '_ext');
					if (destCtrl2) {
						destCtrl2.appendChild(selectBox);
						destCtrl2.style.display = 'block';
					}
				}

				if (selectedIndex > -1) {
					selectBox.selectedIndex = selectedIndex;
				}
			}
		}
	}
	return label;
}

function createOption(value, label, selected) {
	var opt = document.createElement("option");
	opt.selected = (selected != null && selected != '' ? true : false);
	opt.setAttribute("value", value);
	var labelNode = document.createTextNode(label);
	opt.appendChild(labelNode);

	return opt;
}

function showDescription(ctrl, keyName, content) {
	var label = keyName;

	fillInformationDiv(label, ctrl, keyName, content);
}

function fillInformationDiv(label, ctrl, keyName, content) {
	var contentCtrl = document.getElementById("JEVENT_DESCRIPTION_content");
	if (contentCtrl) {
		while(contentCtrl.hasChildNodes()) {
			contentCtrl.removeChild(contentCtrl.lastChild);
		}

		var newTBody = document.createElement("tbody");
		var newTr = document.createElement("tr");
		var newTd = document.createElement("td");
		var newVAlign = document.createAttribute("valign");
		newVAlign.nodeValue = "top";
		newTd.setAttributeNode(newVAlign);

		newTd.innerHTML = content;
		newTr.appendChild(newTd);

		newTBody.appendChild(newTr);
		contentCtrl.appendChild(newTBody);
	}

	showInformation(ctrl, label);
}

function showInformation(source, label) {
	var dest = document.getElementById("JEVENT_DESCRIPTION");
	if (dest) {
		var labelCtrl = document.getElementById("JEVENT_DESCRIPTION_label");
		if (labelCtrl) {
			labelCtrl.innerHTML = label;
		}

		var posData = getAbsoluteOffset(source);

		dest.style.left = null;
		dest.style.right = null;
		dest.style.display = 'inline';
		
		elementWidth = dest.clientWidth ? dest.clientWidth : dest.offsetWidth ? dest.offsetWidth : -1;
		windowWidth = window.innerWidth ? window.innerWidth : document.body.clientWidth ? document.body.clientWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : window.outerWidth ? window.outerWidth : -1;
		
		if(elementWidth >= 0 && windowWidth >= 0 && (posData[0]-5+elementWidth) >= windowWidth) {
			dest.style.left = (windowWidth - elementWidth - 10) + "px";
		} else if (screen.width - posData[0] > 0) {
			dest.style.left = (posData[0]-5) + 'px';
		} else {
			dest.style.right = '5px';
		}
		dest.style.top = (posData[1]-dest.offsetHeight) < 0 ? '0px' : (posData[1]-dest.offsetHeight) + 'px';
	}
}

function closeDiv(divId) {
	showDiv(divId, 'none');
}

function showDiv(divId, mode) {
	if (!mode) {
		mode = 'inline';
	}
	var d = document.getElementById(divId);
	if (d) {
		d.style.display = mode;
	}
}

var JEVENT_MANDATORY_FIELDS = new Array();
var JEVENT_MANDATORY_FIELD_DEFINITIONS = new Array();
function registerMandatoryField(fieldName, fieldLabel, wizardStep, illegalValue, ownMessage, minLength, maxLength, alternatives, callback) {
	var curData = null;
	if (typeof fieldName == 'object') {
		curData = new Array(fieldName, fieldLabel);
	} else {
		curData = new Array(fieldName, (fieldLabel ? fieldLabel : fieldName), illegalValue, ownMessage, minLength, maxLength, alternatives, callback);
	}
	if (!JEVENT_MANDATORY_FIELDS[wizardStep]) {
		JEVENT_MANDATORY_FIELDS[wizardStep] = new Array();
	}
	JEVENT_MANDATORY_FIELDS[wizardStep].push(curData);
	JEVENT_MANDATORY_FIELD_DEFINITIONS[fieldName] = curData;
}

function unregisterMandatoryField(fieldName, wizardStep) {
	for(var i=0; i<JEVENT_MANDATORY_FIELDS[wizardStep].length;i++) {
		if(JEVENT_MANDATORY_FIELDS[wizardStep][i][0] == fieldName) {
			JEVENT_MANDATORY_FIELDS[wizardStep][i] = new Array();
		}
	}
}

function checkAllMandatoryFields() {
	for(var i=0; i<JEVENT_MANDATORY_FIELDS.length; i++) {
		if (!checkMandatoryFields(i)) {
			return false;
		}
	}

	return true;
}

function checkMandatoryFields(stepNr) {
	if (!JEVENT_MANDATORY_FIELDS[stepNr] || JEVENT_MANDATORY_FIELDS[stepNr].length == 0) {
		return true;
	}

	for(var i=0; i<JEVENT_MANDATORY_FIELDS[stepNr].length;i++) {
		for(var k=0; k<JEVENT_MANDATORY_FIELDS[stepNr][i].length; k++){
			if (typeof JEVENT_MANDATORY_FIELDS[stepNr][i][0] == 'object' && JEVENT_MANDATORY_FIELDS[stepNr][i][0].length) {
				var fields = JEVENT_MANDATORY_FIELDS[stepNr][i][0];
				var labels = JEVENT_MANDATORY_FIELDS[stepNr][i][1];
				var isOK = false;
				var k = 0;
				while(k<fields.length && !isOK) {
					var fieldName = fields[k];
					var fieldLabel = (typeof labels == 'object' && labels.length && labels[k]) ? labels[k] : fields[k];
					var field = getElement(fieldName);
					isOK = true && checkField(field, false);
					k++;
				}
				if (!isOK) {
					var msg = 'Bitte füllen Sie mindestens eines der folgenden Felder aus:\n';
					for(var k=0;k<fields.length; k++) {
						highlightField(getElement(fields[k]));
						msg += ((typeof labels == 'object' && labels.length && labels[k]) ? labels[k] : fields[k]) + (k==fields.length-2 ? ' oder ' : ', ');
					}					
					msg = msg.substr(0, msg.length-2);

					alert(msg);
					return false;
				}
			} else {
				var msg = checkFieldAlternatives(JEVENT_MANDATORY_FIELDS[stepNr][i], new Array());
				if(msg) {
					alert(msg);
					return false;
				}
			}
		}
	}

	return true;
}

function ArrayContains(array, element) {
	for(var i=0; i<array.length; i++) {
		if(array[i] == element)
			return true;
	}
	return false;
}

function ArrayClone(array) {
	var a = new Array();
	for(var i=0; i<array.length; i++) {
		a[i] = array[i];
	}
	return a;
}

/**
 * Prüft ein Feld und seine Alternativfelder.
 * Achtung: Gibt bei Erfolg "false" zurück.
 * Ansonsten die Fehlermeldung.
 */
function checkFieldAlternatives(data, ignoreFields) {
	var fieldName = data[0];
	var fieldLabel = data[1];
	var illegalValue = (data[2] ? data[2] : '');
	var ownMessage = (data[3] ? data[3] : '');
	var minLength = (data[4] ? parseInt(data[4]) : -1);
	var maxLength = (data[5] ? parseInt(data[5]) : -1);
	var alternatives = data[6];
	var callback = data[7];
	
	if(ArrayContains(ignoreFields, fieldName))
		return true;
	
	if (isCheckBox(fieldName)) {
		bool = checkCheckBoxes(fieldName);
		if(!bool && alternatives)
			bool = checkAlternatives(fieldName, alternatives, ignoreFields);
		if(callback && window[callback] && window[callback](field))
			bool = true;
		
		if (!bool) {
			var msg = "Das Feld '" + fieldLabel + "' ist ein Pflichtfeld und muss ausgefüllt werden!";
			if (alternatives) {
				msg += createAlternativesMsg(alternatives);
			}
			if (ownMessage) {
				msg = ownMessage;
			}
			return msg;
		}
	} else {
		var field = getElement(fieldName);
		bool = checkField(field, illegalValue, minLength, maxLength);
		if(!bool && alternatives)
			bool = checkAlternatives(fieldName, alternatives, ignoreFields);
		if(callback && window[callback] && window[callback](field))
			bool = true;
		
		if (!bool) {
			highlightField(field);
			var msg = "Das Feld '" + fieldLabel + "' ist ein Pflichtfeld und muss ausgefüllt werden!";
			if (alternatives) {
				msg += createAlternativesMsg(alternatives);
			}
			if (ownMessage) {
				msg = ownMessage;
			}
			forceFocus(fieldName);
			return msg;
		} else {
			field.style.background = '';
		}
	}
	return false;
}

function checkAlternatives(fieldName, alternatives, ignoreFields) {
	var bool = false;
	var alternativeIgnore = ArrayClone(ignoreFields);
	alternativeIgnore.push(fieldName);
	for(var i=0; i<alternatives.length && !bool && alternatives.length > 0; i++) {
		bool = !(true && checkFieldAlternatives(JEVENT_MANDATORY_FIELD_DEFINITIONS[alternatives[i]], alternativeIgnore));
		alternativeIgnore.push(JEVENT_MANDATORY_FIELD_DEFINITIONS[alternatives[i]][0]);
	}
	return bool;
}

function callbackCheckHighLevel(field) {
	var skey = field.value;
	if(skey.match(/\w{3}-\w{3}-(\d{4}){3,}/))
		return true;
	var url = "structurehandler?query=" + encodeURIComponent(skey);
	var request = null;
	try {
		request = createHttpRequest(url, "GET");
	} catch (e) {
		alert('could not retrieve url ' + url + ':' + "\n" + e);
	}
	if (request != null && request.readyState == 4 && request.responseText.toLowerCase().indexOf("bad request") == -1) {
		var xml = request.responseXML;
		if(xml) {
			var items = xml.getElementsByTagName('item');
			if(items) {
				for(var i=0; i<items.length; i++) {
					var item = items.item(i);
					if(item.getAttribute('structureKey') == skey) {
						var leaf = item.getAttribute('leaf');
						if(leaf == 'true') {
							return true;
						}
					}
				}
			}
		}
	}
	return false;
}

function createAlternativesMsg(alternatives) {
	if(alternatives.length == 0)
		return "";
	
	var msg = "\nAlternativ können sie auch ";
	if(alternatives.length == 1)
		msg += "dieses Feld ausfüllen: ";
	else
		msg += "eines dieser Felder ausfüllen: ";
	
	for(var i=0; i<alternatives.length; i++) {
		msg += (i>0 ? ", " : "") + JEVENT_MANDATORY_FIELD_DEFINITIONS[alternatives[i]][1];
	}
	
	return msg;
}

function isCheckBox(fieldName) {
	var isCheckBox = true;
	var ctrls = document.getElementsByName(fieldName);
	for (var i=0; i<ctrls.length; i++) {
		isCheckBox = isCheckBox && ctrls[i].type == "checkbox"; 
	}
	return isCheckBox;
}

function checkCheckBoxes(fieldName) {
	var ctrls = document.getElementsByName(fieldName);
	for(var i=0; i< ctrls.length; i++) {
		if (ctrls[i].checked) {
			return true;
		}
	}

	return false;
}

function checkField(field, illegalValue, minLength, maxLength) {
	if(field){
		if (isCheckBox(field.name)) {
			alert('checkbox found!');
		} else {
			if(!field.value || field.value.length == 0 || (illegalValue && field.value == illegalValue) || (minLength != -1 && field.value.length < minLength) || (maxLength != -1 && field.value.length > maxLength)){
				if (field.value.indexOf('brd-rpn-') != 0) {
					return false;
				} else {
					return isSelectable(field.value);
				}
			}
		}
	}
	return true;
}

function highlightField(field) {
	if (field) {
		field.style.background = '#ffcbcb';
	}
}

function isSelectable(structureKey) {
	if (!JEVENT_STRUCTURE_IS_SELECTABLE.length) {
		return false;
	}

	var tmp = '|' + JEVENT_STRUCTURE_IS_SELECTABLE.join('|') + '|';
	return (tmp.indexOf('|' + structureKey + '|') > -1);
}

function doGebietSearch(ctrlName, trials) {
	var structureKey = '';
	var elem = getElement(ctrlName + '_query');
	var query = elem.value.replace(/[^ \D-\.\/\(\)]/g, "");
	if (query == '' || query == '<Stadt/Ort>') {
		query = '%';
		var ctrl = getElement(ctrlName);
		structureKey = ctrl.value;
	}
	if (elem) {
		var url = "structurehandler?query=" + encodeURIComponent(query) + "&ctrlName=" + encodeURIComponent(ctrlName);
		if (structureKey != '') {
			url = url + "&structureKey=" + structureKey;
		}
		var request = null;
		try {
			request = createHttpRequest(url, "GET");
		} catch (e) {
			alert('could not retrieve url ' + url + ':' + "\n" + e);
		}
		if (request != null && request.readyState == 4 && request.responseText.toLowerCase().indexOf("bad request") == -1) {
			var xml = request.responseXML;
			var hinweis = document.getElementById(ctrlName+'_hinweis');
			var selectBox = document.getElementById(ctrlName+'_ort');
			selectBox.length = 0;
			var items = xml.firstChild.childNodes;
			for (var j = 0; j < items.length; j++) {
				var kreis = items[j].getAttribute("kreis");
				var label = items[j].getAttribute("label");
				var structureKey = items[j].getAttribute("structureKey");
				label = kreis.length > 0 ? label +', '+ kreis : label;
				var opt = createOption(structureKey, label, false);
				selectBox.appendChild(opt);
			}
			if (items.length == 0) {
				selectBox.style.display = 'none';
				hinweis.innerHTML = '';
				alert('Die Suche nach \''+ query +'\' lieferte keine Treffer.');
			} else {
				selectBox.style.display = 'inline';
				hinweis.innerHTML = 'Ergebnis Ihrer Suche:';
			}
		} else if (trials < 2) {
			window.setTimeout("doGebietSearch('" + ctrlName + "', '" + trials+1 + "')", 100);
		} else {
			alert('Die Stadt-/Ortsauswahl konnte nicht initialisiert werden!\n\n' + request.responseText);
		}
	}
}

var menuedObject;
function activateContextMenu(obj, menu, event) {
	if (menu && window.CHAMAELEON) {
        menuedObject=obj;
        var contextMenu = CHAMAELEON.lookupResource('chamaeleon:ContextMenu');
        if (contextMenu) {
        	contextMenu.render(event, menu,
				{
					onclose: function(event) {
						if (menuedObject) {
							var obj = menuedObject;
							menuedObject=null;
							var id = obj.id;
							while (obj.nodeName != "TABLE") obj = obj.parentNode;
							highlightMenuActivator(obj, id, false);
						}
					}
				}
        	);
        }
    }
}

function highlightMenuActivator(obj, activatorId, highlight) {
    if (menuedObject) return;
    if (obj) {
		obj.style.borderColor= highlight ? "black" : "";
	}
	if (activatorId.match(/^link_/)) {
		activatorId = activatorId.substring(5);
	}
	var activator=document.getElementById(activatorId);
    if (activator) {
        activator.style.visibility = highlight ? "visible" : "hidden"; 
	}
}

function initChamaeleonResources(resourcePath) {
    CHAMAELEON.init( { chamaeleon: resourcePath + "/resources/"} );
    CHAMAELEON.resourceCall('chamaeleon:ContextMenu');
}

var CENTURY = 21;
		
function getMillenium() { return CENTURY * 100 - 100; }

function getDateTime(value) {
	if (!value) return null;
	
	var arrDateTime = value.split(" ");
	var arrDate="";
	var arrTime="";
	
	if (arrDateTime.length == 1) {
		arrDate = arrDateTime[0] ? 
			arrDateTime[0].match(/^((\d\d?)\.(\d\d?).(\d\d\d?\d?))?$/) : "";
		arrTime = arrDateTime[0] ? 
			arrDateTime[0].match(/^((([0-2])?[0-9]):(([0-5])?[0-9])(:(([0-5])?[0-9]?))?)?$/) : "";
	}
	else if (arrDateTime.length > 1) {
		arrDate = arrDateTime[0] ? 
			arrDateTime[0].match(/^((\d\d?)\.(\d\d?).(\d\d\d?\d?))?$/) : "";
		arrTime = arrDateTime[1] ? 
			arrDateTime[1].match(/^((([0-2])?[0-9]):(([0-5])?[0-9])(:(([0-5])?[0-9]?))?)?$/) : "";
	}
	
	if (!arrDate && !arrTime)
		return null;

	var day = 1;
	var month = 0;
	var year = 1970;
	var hours = 0;
	var minutes = 0;
	var seconds = 0;

	if(arrDate){
		day = parseInt(arrDate[2], 10);
		month = parseInt(arrDate[3], 10) - 1;
		year = arrDate[4].length == 4 ?
			parseInt(arrDate[4], 10) :
			parseInt(arrDate[4], 10) + getMillenium();
	}

	if(arrTime){
		hours = parseInt(arrTime[2], 10);
		minutes = parseInt(arrTime[4], 10);
		if (arrTime[7])
			seconds = parseInt(arrTime[7], 10);
	}

	return new Date(year, month, day, hours, minutes, seconds).getTime();	
}

/* Return:
	0  = date1 == date2 date1 ist gleich date2
	-1 = date1 < date2  date1 ist älter als date2
	1  = date1 > date2  date2 ist jünger als date2
*/
function compareDate(date1, date2) {
	var d1 = getDateTime(date1);
	var d2 = getDateTime(date2);
	if (d1 == d2) return 0;
	if (d1 < d2) return -1;
	return 1;
}

/* Testet ob fieldDateStart einen Datumswert enthält, der vor dem Datumswert von fieldDateEnd liegt oder gleich ist */
function checkTimespan(fieldDateStart, fieldDateEnd) {
	var field1 = document.getElementById(fieldDateStart);
	var field2 = document.getElementById(fieldDateEnd);
	
	if (!field1 || !field2)
		return true;
	
	var result = compareDate(field1.value, field2.value) <= 0;
	if (!result)
		alert("Das angegebene Startdatum ist jünger als das Enddatum!");
	return result;
}

function _jevent_validateInput(feld){
	var val;
	if(val = getValue(feld)) {
		if(!val.match("^[><]{0,1}(\\d+)$")) {
			alert('Sie m\u00FCssen eine ganze Zahl eingeben!');
			forceFocus(feld);
			return false;
		}
		return true;
	}
	return val == "";
}

function getGlobalArray(name) {
	if(!window.globalArrays) window.globalArrays={};
	if(!window.globalArrays[name]) window.globalArrays[name]=[];
	return window.globalArrays[name];
}

/* Javascript-Funktionen für den chamaeleon.html.SimpleCalendar */

/**
 * Ermittle den Abstand des gegebenen Elements vom oberen Rand der Seite,
 * also gewissermaßen den absoluten Top-Wert des Elements.
 */
function getTopFromPage(elem) {
	var totalOffset = 0;
	while(elem.offsetParent) {
		totalOffset += elem.offsetTop;
		elem = elem.offsetParent;
	}
	return totalOffset;
}

/**
 * Öffne bzw. schließe das Kalenderpopup mit dem angegebenen Index.
 * 
 * Wenn das Popup bereits geöffnet ist wird es geschlossen und umgekehrt.
 * Falls beim Öffnen bereits ein anderes Popup geöffnet ist, wird dieses
 * zusätzlich geschlossen.
 * 
 * Das Popup wird entweder oberhalb oder unterhalb des Eingabefeldes geöffnet,
 * abhängig davon, wie viel Platz noch unter dem Eingabefeld verfügbar ist.
 */
function simpleCalendarToggle(calendarUuid){
	var container = document.getElementById('CALENDARVIEW_'+calendarUuid+'_DIV');
	var innerDiv = document.getElementById('CALENDARVIEW_'+calendarUuid+'_INNERDIV');
	
	if (container.style.display == 'block'){
		container.style.display = 'none';
		window['currentPopup'] = null;
	} else {
		if (window['currentPopup'] != null) {
			window['currentPopup'].style.display = 'none';
			window['currentPopup'] = null;
		}

		// Falls nicht genug Platz vorhanden ist, um den Kalender nach unten zu öffnen, öffne ihn nach oben */
		var inputTable = document.getElementById('CALENDERVIEW_TABLE_'+calendarUuid);
		var htmlElement = document.body.parentNode;
		var screenBottom = htmlElement.scrollTop + htmlElement.clientHeight;
		var calendarStartBelow = getTopFromPage(inputTable) + inputTable.offsetHeight;
		var spaceBelow = screenBottom - calendarStartBelow;
		if(spaceBelow > container['calendarHeight']) {
			innerDiv.style.bottom='';
			innerDiv.style.top='0px';
		} else {
			innerDiv.style.top='';
			innerDiv.style.bottom=''+inputTable.offsetHeight+'px';
		}		
		container.style.display = 'block';
		setTimeout('window["currentPopup"] = document.getElementById("CALENDARVIEW_'+calendarUuid+'_DIV");',0);
	}

	return true;
}

/**
 * Setze den Inhalt des Eingabefelds für die Datumsauswahl auf einen gegebenen Wert und
 * schließe bei Bedarf das Kalenderpopup.
 * 
 * Diese Funktion wird aus dem iFrame heraus aufgerufen, in dem sich der Inhalt des
 * Kalenderpopups befindet.
 */
function simpleCalendarApplyData(calendarUuid,inputElementName,date,calendarClosed,isEmpty){
	if (!calendarClosed) {
		simpleCalendarToggle(calendarUuid);
	}
	
	var ctrl = document.getElementById(inputElementName);
	if (!isEmpty) {
		ctrl.value = date;
	} else {
		ctrl.value = '';
	}
}

/**
 * Versuche, die Kalenderauswahl zu initialisieren.
 * 
 * Dazu wird zum einen die Höhe des Kalenders für Berechnungen in simpleCalendarToggle()
 * gespeichert, zum anderen wird dem iFrame mit dem Inhalt der Datumsauswahl eine Funktion
 * übergeben, mit der aus diesem iFrame heraus das Textfeld der Datumsauswahl geändert
 * werden kann.
 */
function simpleCalendarInit(calendarUuid, inputElementName, calendarHeight, nthcall){
	// Speichere die Soll-Hoehe des Kalenderpopups
	var container = document.getElementById('CALENDARVIEW_'+calendarUuid+'_DIV');
	container['calendarHeight'] = calendarHeight;
	
	if (window.frames && window.frames.length > 0){
		var w = window.frames['CALENDARVIEW_'+calendarUuid+'_iframe'];
		var applyFunction = new Function(
				"date", "calendarClosed", "isEmpty",
				"simpleCalendarApplyData('"+calendarUuid+"','"+inputElementName+"',date,calendarClosed,isEmpty);");
		var isOk = true;
		try {
			w['setDate'] = applyFunction;
		} catch (e) {
			isOk = false;
		}
		if (! (isOk && w['setDateDone'])){
			if (nthcall == 30){
				alert('could not fetch setDateDone!');
			} else {
				window.setTimeout("simpleCalendarInit('"+calendarUuid+"','"+inputElementName+"',"+calendarHeight+","+ (nthcall+1) +");", 150);
			}
		}
	}
}

/* JS-Funktionen für die Bilderanzeige (view.components.attributes.ImageAttribute) */

function enqueueImageLink(galleryid, url, description) {
	var imginfo = {"url": url, "description": description};
	getGlobalArray("images_"+galleryid).push(imginfo);
}

function initGallery(galleryid) {
	var images = getGlobalArray("images_"+galleryid);
	var controls = document.getElementById("controls_"+galleryid);
	
	if(images.length>=2 && controls && !controls.initialized) {
		controls.currentImage=0;
		controls.images = images;
		controls.first = document.getElementById("imagecontrol_first_"+galleryid);
		controls.prev = document.getElementById("imagecontrol_prev_"+galleryid);
		controls.next = document.getElementById("imagecontrol_next_"+galleryid);
		controls.last = document.getElementById("imagecontrol_last_"+galleryid);
		
		// Erzwinge vertikale Scrollbar, um ein Springen der Kontrollelemente zu verhindern
		document.getElementsByTagName("html")[0].style.overflowY="scroll";
		
		controls.style.display="block";
		
		controls.initialized=true;
	}
}

function firstImage(galleryid) {
	var controls = document.getElementById("controls_"+galleryid);
	
	controls.currentImage=0;
	setGalleryImage(galleryid, controls.images[controls.currentImage]);
	updateGalleryControls(controls);
}

function prevImage(galleryid) {
	var controls = document.getElementById("controls_"+galleryid);
	
	if(controls.currentImage>0) {
		setGalleryImage(galleryid, controls.images[--controls.currentImage]);
		updateGalleryControls(controls);
	}
}

function nextImage(galleryid) {
	var controls = document.getElementById("controls_"+galleryid);
	
	if(controls.currentImage < controls.images.length-1) {
		setGalleryImage(galleryid, controls.images[++controls.currentImage]);
		updateGalleryControls(controls);
	}
}

function lastImage(galleryid) {
	var controls = document.getElementById("controls_"+galleryid);
	
	controls.currentImage = controls.images.length-1;
	setGalleryImage(galleryid, controls.images[controls.currentImage]);
	updateGalleryControls(controls);
}

function updateGalleryControls(controls) {
	var isFirstImage = (controls.currentImage == 0);
	var isLastImage = (controls.currentImage == controls.images.length-1);
	
	controls.first.src = isFirstImage ? "images/scroller_first_disabled.png" : "images/scroller_first.png";
	controls.prev.src = isFirstImage ? "images/scroller_rewind_disabled.png" : "images/scroller_rewind.png";
	controls.next.src = isLastImage ? "images/scroller_forward_disabled.png" : "images/scroller_forward.png";
	controls.last.src = isLastImage ? "images/scroller_last_disabled.png" : "images/scroller_last.png";
}

function setGalleryImage(galleryid, image) {
	toggleImage(galleryid, image.url, image.description);
}