var global = new Global();

function Global() {
	
	this.get_base_path = function() {
	
		var scripts = document.getElementsByTagName("script"),
		src = scripts[scripts.length - 1].src;
		
		return src ? src.substring(0, src.length - 23) : '/';
	};
	
	this.base_path = this.get_base_path();
	
	this.get_base_guid = function(thiz) {
	    
		var base_guid = null;
		var httpObject = getHTTPObject();
		
		if(httpObject != null) {
			
			httpObject.open('GET', this.base_path + 'includes/get_local_guid.php');
			
			httpObject.onreadystatechange = function() {
		
				try {
					if(httpObject.readyState == 4) {
						if(httpObject.status == 200) {
							base_guid = trim(httpObject.responseText);
							if(base_guid)
								thiz.base_guid = parseInt(base_guid);
						}
					}
				}
				catch(e) {
					// Do nothing...
				}
			};
			httpObject.send(null);
		}
	}
	
	this.base_guid = 0;
	
	this.is_base_guid_remotely = typeof(is_base_guid_remotely) != "undefined" && is_base_guid_remotely;
	
	if(this.is_base_guid_remotely)
		this.get_base_guid(this);
	
	this.generate_local_guid = function() { return this.is_base_guid_remotely ? this.base_guid++ : (new Date().getTime() + 1) * 1000 + this.base_guid++; };
}

var dialog = new Dialog();

function Dialog(containerId) {

	var onscroll = window.onscroll;
	
	this.show = function(title, content, width, noBackground) {
		
		if(this.container == null) {
			this.containerId = 'body';
			this.container = document.body;
		}
		
		window.scrollTo(0, 0);
		
		if(typeof(width) == 'undefined' || width == null)
			width = 300;
		
		this.overlay = document.getElementById(this.containerId + '_overlay');
		if(this.overlay) {
			this.container.removeChild(this.overlay);
		}
		this.overlay = new Element('div', { 'id': this.containerId + '_overlay', 'class': 'overlay' }).hide();
		try {
			this.overlay.style.minHeight = getDocumentHeight() + 'px';
		}
		catch(e) {
			// Do nothing...
		}
		this.container.appendChild(this.overlay);
		
		this.dialog = document.getElementById(this.containerId + '_dialog');
		if(this.dialog) {
			this.container.removeChild(this.dialog);
		}
		this.dialog = new Element('div', { 'id': this.containerId + '_dialog', 'class': 'dialog' }).hide();
		this.container.appendChild(this.dialog);
		
		this.dialog.innerHTML = '<div class=\"page_message_title\">' + title + '</div><div class=\"page_message_content\">' + content + '</div>';
		
		this.dialog.style.position = 'absolute';
		this.dialog.style.top = '0px';
		this.dialog.style.width = width + 'px';
		this.dialog.style.overflow = 'visible';
		
		this.dialog.style.left = (this.container.offsetWidth - width) / 2 + 'px';
		
		Event.observe(this.overlay, 'click', this.hide.bindAsEventListener(this));
		
		if(noBackground)
			this.overlay.style.backgroundColor = 'transparent';
		
		if(navigator.appVersion.indexOf('MSIE 6') != -1) {
			
			this.overlay.style.display = 'block';
			this.dialog.style.display = 'block';
		}
		else {

			if(noBackground)
				this.overlay.style.display = 'block';
			else
				new Effect.Appear(this.overlay, { duration: 0.15,  to: 0.8 });

			new Effect.BlindDown(this.dialog, { duration: 0.15 });
		}

		//this.container.style.overflow = 'hidden';
		//window.onscroll = function() { window.scrollTo(0, 0); };
		
		return this;
	};
	
	this.hide = function(event) {
		
		//this.container.style.overflow = 'auto';
		if(this.onscroll) {
			window.onscroll = this.onscroll;
		}
		else {
			window.onscroll = null;
		}

		if(navigator.appVersion.indexOf('MSIE 6') != -1) {
			
			this.overlay.style.display = 'none';
			this.dialog.style.display = 'none';
		}
		else {

			new Effect.BlindUp(this.dialog, { duration: 0.15 });
			new Effect.Fade(this.overlay, { duration: 0.15,  to: 0.0 });
		}
		
		this.overlay.style.backgroundColor = '#000000';
		
		return this;
	};
	
	this.containerId = '';
	this.container = null;
	
	if(typeof(containerId) != 'undefined' && containerId == null) {
		this.containerId = containerId;
		this.container = document.getElementById(containerId);
	}
}

CustomBaseAutocompleter = Class.create(Ajax.Autocompleter, {

	customBaseInitialize: function(element, update, url, options) {	
		this.baseInitialize(element, update, options);
		this.options.asynchronous  = true;
		this.options.onComplete    = this.onComplete.bind(this);
		this.options.defaultParams = this.options.parameters || null;
		this.url                   = url;
		this.options.onShow        = this.customBaseAutocompleterOnShow.bind(this);
		this.baseOnHide            = this.options.onHide;
		this.options.onHide        = this.customBaseAutocompleterOnHide.bind(this);
		this.positionStyle         = 'absolute';
		this.keepFocus             = false;
		
		Event.observe(this.update, "mousedown", this.onMouseDown.bindAsEventListener(this));
		Event.observe(this.update, "mouseup", this.onMouseUp.bindAsEventListener(this));

		// Not really needed if the choices do not cause scrollbars to appear for the body...
		/*
		this.body = null;

		try {
			this.body = document.getElementsByTagName('body')[0];
		}
		catch(exc) {
			this.body = null;
		}
		*/
	},

	onMouseDown: function(event) {
		
		this.keepFocus = this.hasFocus;
	},
	
	onMouseUp: function(event) {
		
		this.keepFocus = false;
	},
	
	onBlur: function($super, event) {

		if(!this.keepFocus) {
			$super(event);
		}
		else {
			this.keepFocus = false;
			this.element.focus();
		}
	},
	
	customBaseAutocompleterOnShow: function(element, update) {
			
		var zIndex = getzIndex(element) + 1;

		// Not really needed if the choices do not cause scrollbars to appear for the body...
		/*
		if(this.body != null)
			this.body.style.overflow = 'hidden';
		*/
		
		update.style.zIndex = zIndex > 1 ? zIndex : 2;
		
		update.style.position = this.positionStyle;
		
		Position.clone(element, update, {
			setHeight: false
		});
		
		update.style.top = (absTop(element) + element.offsetHeight) + 'px';
		if(element.currentStyle) {
			update.style.left = (absLeft(element) + absLeftBorder(element, true) - 1) + 'px';
		}
		else {
			update.style.left = (absLeft(element) + absLeftBorder(element, false) - 1) + 'px';
		}

		update.style.width = (element.offsetWidth - absLeftBorder(element, true) - 1) + 'px';
		
		if(navigator.appVersion.indexOf('MSIE 6') != -1)
			update.style.display = 'block';
		else
			Effect.Appear(update, { duration: 0.15 });
	},
	
	customBaseAutocompleterOnHide: function(element, update) {
		
		this.baseOnHide(element, update);
		this.update.innerHTML = '';
		
		// Not really needed if the choices do not cause scrollbars to appear for the body...
		/*
		if(this.body != null)
			this.body.style.overflow = 'auto';
		*/
	},
	
	fixIEOverlapping: function() {
		
	    Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
	    this.iefix.style.zIndex = this.update.style.zIndex - 1;
	    Element.show(this.iefix);
	}
});

CustomAutocompleter = Class.create(CustomBaseAutocompleter, {

	initialize: function(element, update, url, options, value, doRevert) {
		this.customBaseInitialize(element, update, url, options);
		this.value                 = value;
		this.doRevert              = doRevert;
		this.isRevert              = doRevert;
		this.customBaseOnHide      = this.options.onHide;
		this.options.onHide        = this.customAutocompleterOnHide.bind(this);
		this.options.updateElement = this.customAutocompleterUpdateElement.bind(this);
	
		this.valueElement = this.element;
		try {
			var valueElements = this.element.id.split('#');
			var valueElement = null;
			if(valueElements.length >= 2 && valueElements[valueElements.length - 1] == "show") {
				this.valueElement = document.getElementById(this.element.id.substring(0, this.element.id.length - 5));
			}
		}
		catch(e) {
			// Do nothing
		}		
	},

	customAutocompleterOnHide: function(element, update) {
		this.customBaseOnHide(element, update);
		if(this.isRevert) {
			this.element.value = this.value;
		}
		this.isRevert = this.doRevert;
	},
	
	customAutocompleterUpdateElement: function(selectedElement) {
		if(this.valueElement != null) {
			var selectedElementValues = selectedElement.id.split('#');
			this.valueElement.value = selectedElementValues[selectedElementValues.length - 1];
			this.element.value = selectedElement.innerHTML;
			this.element.focus();
		}
		else {
			this.options.updateElement = null;
			this.updateElement(selectedElement);
		}
		this.value = this.element.value;
		this.isRevert = false;
	}
});

SemAutocompleter = Class.create(CustomBaseAutocompleter, {
	
	initialize: function(element, update, url, options) {
		this.customBaseInitialize(element, update, url, options);
		this.semUpdate = document.getElementById(update);
	}
});

var semSelector = null;

function SemSelector(urls, minChars, isLoaded, lastField, fields) {

	semSelector = this;

	this.urls = urls;

	if(lastField != null) {
		this.lastField = document.getElementById(lastField);
		this.lastField = this.lastField ? this.lastField : null;
	}
	else {
		this.lastField = null;
	}

	if(fields != null)
		this.fields = fields;
	else
		this.fields = new Array('semnr', 'vernr', 'doznr', 'submitButton');

	this.firstField = document.getElementById(this.fields[0]);
	this.secondField = document.getElementById(this.fields[1]);
	this.thirdField = document.getElementById(this.fields[2]);
	if(this.fields.length > 3)
		this.submitButton = document.getElementById(this.fields[3]);
	else
		this.submitButton = null;
	
	this.clearElement = function(element) {
	
		if(element != null) {
			for(var i = 1; i < element.options.length; i++) {
				element.remove(i);
			}
			element.options.length = 1;
			element.selectedIndex = 0;
		}
	}
	
	this.clearSelect = function(field) {

		switch(field) {
			case 1:
				this.clearElement(this.secondField);
				this.secondField.disabled = true;
			case 2:
				this.clearElement(this.thirdField);
				this.thirdField.disabled = true;
			case 3:
				if(this.lastField != null) {
					this.clearElement(this.lastField);
					this.lastField.disabled = true;
				}
			default:
				if(this.submitButton != null)
					this.submitButton.disabled = true;
		}
	};
	
	this.getnr = function(field) {

		try {
			this.clearSelect(field);
			
			var querystring = this.fields[0] + '=' + this.firstField.value;
			var fieldElement = this.secondField;
			for(var i = 2; i <= field; i++) {
				switch(i) {
					case 2:
						querystring += '&' + this.fields[1] + '=' + this.secondField.value;
						fieldElement = this.thirdField;
						break;
					case 3:
						querystring += '&' + this.fields[2] + '=' + this.thirdField.value;
						fieldElement = this.lastField != null ? this.lastField : null;
						break;
				}
			}
			
			if(fieldElement != null) {
				
				if(this.urls[field].indexOf('?') > 0)
					querystring = '&' + querystring;
				else
					querystring = '?' + querystring;
				
				var httpObject = getHTTPObject();
				if(httpObject != null) {
					httpObject.open('GET', this.urls[field] + querystring, true);
					httpObject.onreadystatechange = function() { semSelector.readnr(httpObject, field, fieldElement); };
					httpObject.send(null);
				}
				else {
					this.firstField.disabled = false;
					this.secondField.disabled = false;
					this.thirdField.disabled = false;
					if(this.lastField != null)
						this.lastField.disabled = false;
					if(this.submitButton != null)
						this.submitButton.disabled = false;
				}
			}
		}
		catch(e) {
			location.reload();
		}
	};

	this.readnr = function(httpObject, field, fieldElement) {
		
		try {
			if(httpObject.readyState == 4) {
				
				var response = httpObject.responseText;
				var items = response.split('#');
				var count = items.length - 1;
				
				for(var i = 0; i < count; i++) {
					var options = items[i].split('!');
					fieldElement.options[i + 1] = new Option(options[1], options[0]);
				}
				
				if(fieldElement.options.length > 0 && fieldElement.options.length <= 2 && fieldElement.options[fieldElement.options.length - 1].value != '') {
					fieldElement.selectedIndex = fieldElement.options.length - 1;
					if(field < 3)
						this.getnr(field + 1);
				}
										
				this.firstField.disabled = false;

				switch(field) {
					case 3:
						if(this.lastField != null) {
							this.lastField.disabled = false;
							if(this.submitButton != null && this.lastField.options.length > 0 && this.lastField.options.length <= 2 && this.lastField.options[this.lastField.options.length - 1].value != '')
								this.submitButton.disabled = false;
						}
					case 2:
						this.thirdField.disabled = false;
						if(this.lastField == null && this.submitButton != null && this.thirdField.options.length > 0 && this.thirdField.options.length <= 2 && this.thirdField.options[this.thirdField.options.length - 1].value != '') {
							this.submitButton.disabled = false;
						}
					case 1:
						this.secondField.disabled = false;
				}
			}
		}
		catch(e) {
			location.reload();
		}
	};

	if(!isLoaded) {
		this.clearSelect(1);
	}
	
	this.firstFieldLastValue = this.firstField.value;
	
	this.firstField.onchange = function() {
		
		if(semSelector.firstField.value != semSelector.firstFieldLastValue) {
			
			semSelector.clearSelect(1);
		}
		
		return false;
	};
	
	this.firstFieldAfterUpdateElement = function(element, selectedElement) {
		semSelector.firstFieldLastValue = element.value;
		semSelector.getnr(1);
	};
	
	this.firstFieldAutoCompleter = new SemAutocompleter(this.fields[0], 'autocomplete', this.urls[0], {minChars: minChars, afterUpdateElement: this.firstFieldAfterUpdateElement});

	this.secondField.onchange = function() { if(semSelector.secondField.value != '') { semSelector.getnr(2); } else { semSelector.clearSelect(2); } };
	this.thirdField.onchange = function() { if(semSelector.thirdField.value != '') { if(semSelector.lastField != null) { semSelector.getnr(3); } else { if(semSelector.submitButton != null ) { semSelector.submitButton.disabled = false; } } } else { semSelector.clearSelect(3); } };

	if(this.lastField != null) {
		this.lastField.onchange = function() { if(semSelector.lastField.value != '') { if(semSelector.submitButton != null ) { semSelector.submitButton.disabled = false; } } else { semSelector.clearSelect(4); } };
	}
}

function getzIndex(el) {

	if(typeof(el.tagName) == 'undefined')
		return 0
	
	if(el.currentStyle)
		return (el.style && !isNaN(parseInt(el.currentStyle['zIndex']))) ? parseInt(el.currentStyle['zIndex']) : (el.parentNode ? getzIndex(el.parentNode) : 0);
	else
		return (!isNaN(parseInt(document.defaultView.getComputedStyle(el, null).getPropertyValue('z-index'))) && parseInt(document.defaultView.getComputedStyle(el, null).getPropertyValue('z-index')) > 0) ? parseInt(document.defaultView.getComputedStyle(el, null).getPropertyValue('z-index')) : (el.parentNode ? getzIndex(el.parentNode) : 0);
}

function absLeft(el) {
	return (el.offsetParent) ? el.offsetLeft + absLeft(el.offsetParent) : el.offsetLeft;
}

function absTop(el) {
	return (el.offsetParent) ? el.offsetTop + absTop(el.offsetParent) : el.offsetTop;
}

function absLeftBorder(el, onlyFirst) {
	
	var border = null;
	var intVal = 0;
	var retVal = 0;
	
	try {
		while(el) {
			border = el.currentStyle ? el.currentStyle['borderLeftWidth'] : document.defaultView.getComputedStyle(el, null).getPropertyValue('border-left-width');
			if(border) {
				intVal = parseInt(border);
				if(!isNaN(intVal))
					retVal += intVal;
			}
			if(onlyFirst)
				break;
			el = el.offsetParent;
		}
	}
	catch(exc) {
		// Do nothing...
	}

	return retVal;
}

function makeArray() {
	
	this.length = makeArray.arguments.length;
	
	this.getRandomItem = function() {
		
		if(this.length > 0) {
			
			if(this.length == 1)
				return this[0];
			
			var random = 1;
			while(random == 1)
				random = Math.random();
			
			return this[Math.floor(random * this.length)];
		}
		
		return null;
	};
	
    for (i = 0; i < this.length; i++)
        this[i] = makeArray.arguments[i];
}

function miscWindow(url, name, width, height, param) {
	
	if(param != '') {
		param = '?param=' + param;
	}

	var handle = window.open(url + param, name, 'width=' + width + ', height=' + height + ', titlebar=yes, directories=no, location=no, dependent=yes, resizable=yes, scrollbars=yes, status=no, toolbar=no, menubar=yes');
	try {
		handle.focus();
	}
	catch(e) {
		// Do nothing...
	}

	return;
}

function printWindow(url) {

	var handle = window.open(url, 'printWindow', 'width=1024, height=700, titlebar=yes, directories=no, location=no, dependent=yes, resizable=no, scrollbars=yes, status=no, toolbar=no, menubar=no');
	try {
		handle.focus();
	}
	catch(e) {
		// Do nothing...
	}
	
	return;
}

function getHTTPObject() {

	var httpObject = null
	if(window.XMLHttpRequest) {
		httpObject = new XMLHttpRequest();
	}
	else if(window.ActiveXObject) {
	
		try {
			httpObject = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e) {
			try {
				var httpObject = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e) {
				httpObject = null;			
			}		
		}	
	}
	return httpObject;
}

function sendHTTPRequest(method, url, elementId, callback, timeout) {

	var httpObject = getHTTPObject();
	
	if(httpObject != null) {
		
		try {
			
			var doIt = true;
			var isFull = false;
			var element = null;
			var content = null;

			if(elementId) {
				if(typeof elementId != 'string') {
					if(elementId.parentNode.tagName.toUpperCase() == 'DIV') {
						element = elementId.parentNode;
						content = elementId;
						isFull = true;
					}
					else {
						doIt = false;
					}
				}
				else {
					element = document.getElementById(elementId);
				}
			}
			
			if(doIt) {

				timeout = (timeout || timeout === 0) ? Math.abs(timeout) : 500;
				
				var loadingTimeout = timeout / 1000;
				
				var qIndex = url.indexOf('?');
				
				if(qIndex != -1)
					url = url.substring(0, qIndex + 1) + 'is_ajax=true&' + url.substring(qIndex + 1);
				else
					url += '?is_ajax=true';
		
				var appear = new makeArray('Appear', 'BlindDown', 'SlideDown', 'Grow').getRandomItem();
				var disappear = new makeArray('Fade', 'BlindUp', 'SlideUp', 'Shrink').getRandomItem();
				
				if(element) {
					
					closeWindows();
					
					if(timeout > 0) {
						
						var overlay_id = 'ajax_overlay';
						var overlay = document.getElementById(overlay_id);
						if(!overlay) {
							overlay = new Element('div', { 'id': overlay_id, 'class': 'overlay ajax_overlay' }).hide();
							document.body.appendChild(overlay);
						}
						try {
							overlay.style.minHeight = getDocumentHeight() + 'px';
						}
						catch(e) {
							// Do nothing...
						}
						overlay.style.display = 'block';
						
						var loading_overlay_id = 'ajax_loading_overlay';
						var loading_overlay = document.getElementById(loading_overlay_id);
						if(!loading_overlay) {
							loading_overlay = new Element('div', { 'id': loading_overlay_id, 'style': 'z-index:39000;position:fixed;top:150px;left:0px;width:100%;text-align:center;' }).hide();
							loading_overlay.innerHTML = '<img src="' + global.base_path + 'images/loading_big.gif" style="display:inline;"/>';
							document.body.appendChild(loading_overlay);
						}
						loading_overlay.style.display = 'block';
					}
					
					content = isFull ? content : document.getElementById(elementId + '_content');
					if(!content) {
						
						content = document.createElement('div');
						content.setAttribute('id', elementId + '_content');
						content.style.display = 'none';
						element.appendChild(content);
					}
					
					if(element.style.display != 'none') {
						
						element.style.minHeight = element.offsetHeight + 'px';
						
						if(navigator.appVersion.indexOf('MSIE 6') != -1) {
							content.style.display = 'none';
						}
						else {
							if(isFull)								
								eval('new Effect.Fade(content, { duration: loadingTimeout, to: 0.2 })');
							else
								eval('new Effect.' + disappear + '(content, { duration: loadingTimeout });');
						}
					}
					else {
						
						element.style.display = 'block';
					}
					
					if(content)
						content.style.width = element.offsetWidth + 'px';
				}
				
				httpObject.open(method, url);
				httpObject.onreadystatechange = function() {
		
					try {
						if(httpObject.readyState == 4) {
						
							if(httpObject.getResponseHeader("PHP_UNIPLUS_SESSION_STATE") == '0') {
							
								if(loading_overlay)
									loading_overlay.style.display = 'none';
									
								dialog.show('Sitzung beendet', '<div class="message_text">Die Sitzung wurde zwischenzeitlich beendet. Wir bitten um Entschuldigung.', null, true);
							
								window.setTimeout(function () { location.reload(); }, 3000);
							}
							else {
								if(httpObject.status != 200) {
									
									location.reload();
								}
								else {
									
									if(isFull) {

										try {
											Effect.ScrollTo(element, loadingTimeout * 2);
										}
										catch(scrollE) {
											window.scrollTo(0, 0);
										}
									}
									
									var head = document.getElementsByTagName('head')[0];
									var removeScriptNode = null;
									var scriptCounter = 0;
									
									while(true) {
										scriptCounter++;
										removeScriptNode = document.getElementById('helper_script_' + scriptCounter);
										if(removeScriptNode)
											head.removeChild(removeScriptNode);
										else
											break;
									}
									
									var responseText = httpObject.responseText;
									
									window.setTimeout(function () {
										
										if(!callback && eval('typeof generalCallback') == 'function')
											callback = eval('generalCallback');
										
										if(element) {
											content.style.display = 'none';
										}
										if(callback) {
											responseText = callback(responseText);
										}
										if(responseText && element) {
											if(isFull) {
												element.innerHTML = responseText;
												content = element.childNodes[0];
												scriptCounter = 0;
												element.innerHTML.extractScripts().map(function(script) {
													scriptCounter++;
													var addScriptNode = document.createElement('script');
													addScriptNode.setAttribute('id', 'helper_script_' + scriptCounter);
													addScriptNode.setAttribute('type', 'text/javascript');
													if(navigator.appVersion.indexOf('MSIE') != -1) {
														addScriptNode.text = script;
													}
													else {
														var textNode = document.createTextNode(script);
														addScriptNode.appendChild(textNode);
													}
													head.appendChild(addScriptNode);
												});
											}
											else {
												content.innerHTML = responseText;
											}
											if(navigator.appVersion.indexOf('MSIE 6') != -1) {
												content.style.display = 'block';
												if(isFull) {
													window.scrollTo(0, 0);
												}
											}
											else {
												if(isFull)
													eval('new Effect.Appear(content, { duration: loadingTimeout, from: 0.2 })');
												else
													eval('new Effect.' + appear + '(content, { duration: loadingTimeout })');
											}
										}
										if(element) {
											window.setTimeout(function () {
												
												if(element.style.minHeight) {
													
													window.setTimeout(function () {
														
														var ratio = content.offsetHeight / element.offsetHeight;
														
														if(ratio >= 1 || navigator.appVersion.indexOf('MSIE 6') != -1) {
															element.style.minHeight = '0px';
														}
														else {
			
															element.style.height = element.offsetHeight + 'px';
															element.style.minHeight = '0px';
															new Effect.Scale(element, ratio * 100, { scaleContent: false, scaleX: false, duration: loadingTimeout / 3 });
															window.setTimeout(function () { element.style.height = 'auto'; }, timeout);
														}
													}, timeout / 3);
												}
											}, timeout);
										}
										
										if(loading_overlay)
											loading_overlay.style.display = 'none';
										
										if(overlay)
											overlay.style.display = 'none';
									}, timeout);
								}
							}
						}
					}
					catch(innerE) {
						location.reload();
					}
				};
				
				httpObject.send(null);
			}
			else {
				alert('Es wurde keine Element (DIV) zum Einfügen für neuen Inhalt gefunden.');
			}
		}
		catch(outerE) {
			
			if(loading_overlay)
				loading_overlay.style.display = 'none';
			
			if(overlay)
				overlay.style.display = 'none';
		}
	}
}

function getDocumentHeight() {

    return Math.max(
        Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
        Math.max(document.body.clientHeight, document.documentElement.clientHeight)
    );
}

function trim(str) {
	
	return str.replace(/^\s+|\s+$/g, '');
}

function number2float(number, id) {
	
	var withoutSeparator;
	var splitted;
	var count;
	var start;
	var changedNumber = "";
	var i;
	
	withoutSeparator = number.replace(/\./, "");
	
	splitted = withoutSeparator.split(",");
	
	count = Math.floor(splitted[0].length/3);
	
	start = splitted[0].length-count*3;
	
	changedNumber = splitted[0].substr(0, start);
	
	for(i=1; i<=count; i++)
	{
		
		if(!(i==1 && start==0))
			changedNumber += '.';
		
		anfang = start+(i-1)*3; 
		
		changedNumber += splitted[0].substr(anfang, 3);
	}
	
	if(splitted.length>1)
	{
		changedNumber += ','+splitted[1];
	} else {
		changedNumber += ',00';
	}
	
	document.getElementById(id).value = changedNumber;
}

function showAddress(address, comment) {
	
	var geocoder = new google.maps.Geocoder();
	
	if (geocoder) {
		
		geocoder.geocode( { 'address': address}, function(results, status) {
				
			if (status == google.maps.GeocoderStatus.OK) {
				
				var options = {
					zoom: 15,
					mapTypeId: google.maps.MapTypeId.ROADMAP
				}
				map = new google.maps.Map(document.getElementById('google_map'), options);
				
				map.setCenter(results[0].geometry.location);
				var marker = new google.maps.Marker({
					map: map,
					position: results[0].geometry.location,
					title: address
				});

				if(comment)
					comment = '<b>' + comment + '</b><br />' + address;
				else
					comment = address;

				var infowindow = new google.maps.InfoWindow({ content: comment });
				
				var openInfoWindow = function() {
					infowindow.open(map, marker);
				}
				
				google.maps.event.addListener(marker, 'click', openInfoWindow);
				
				window.setTimeout(openInfoWindow, 300);
			}
			else {
				try {
					Effect.BlindUp(document.getElementById('google_map').parentNode, { duration: 0.3 });
				}
				catch(e) {
					// Do nothing...
				}
			}
		});
	}
}

function Calendar(datfield) {

	this.y2k = function(number) {
	
		return (number < 1000) ? number + 1900 : number;
	}
	
	this.getStartYear = function() {
		
		return this.y2k(this.today.getYear()) - 70;
	}
	
	this.getEndYear = function() {
		
		return this.y2k(this.today.getYear()) + 5;
	}
	
	this.fillDat = function()  {
	
	    this.month++;
	    
	    var strDay = this.day.toString();
	    var strMonth = this.month.toString();
	
	    if(strMonth.length < 2)
	    	strMonth = '0' + strMonth;
	    if(strDay.length < 2)
	    	strDay = '0' + strDay;
	    	
	    document.getElementById(this.datfield).value = strDay + '.' + strMonth + '.' + this.year;
	}
	
	this.changeDay = function(day) {
	    this.day = day;
	    this.fillDat();
	    this.hide();
	}

	this.changeMonth = function(month) {
	    this.month = month;
	    this.reload();
	}
	
	this.changeYear = function(year) {
	    this.year = year;
	    this.reload();
	}
	
	this.reload = function() {
		this.window.innerHTML = this.content(this.month, this.year);
		this.bug(true);	
	}
	
	this.hide = function() {
		if(this.window != null) {
			this.bug(false);
			this.window.style.display = 'none';
			this.window.innerHTML = '';
		}
	}
	
	this.content = function(month, year) {

		var output = '';
	   
	    output += '<table width="100%" align="center" border="0" cellpadding="0" cellspacing="0" class="calendar"><tr><td style="text-align:center;vertical-align:middle;" width="50%" class="calendarheader" nowrap="nowrap">' + this.names[month] + ' ' + year + '</td><td width="50%" align="center" class="calendarheader"><table align="center" border="0" cellpadding="0" cellspacing="0"><tr><td>';
	    
	    output += '<select name="month" onchange="javascript:self.calendar.changeMonth(this.value);" style="visibility:hidden;">';
	
	    for (m = 0; m < 12; m++) {
	        if (m == month) {
	        	output += '<option value="' + m + '" selected>' + this.names[m] + '</option>';
	        }
	        else {
	        	output += '<option value="' + m + '">' + this.names[m] + '</option>';
	        }
	    }
	
	    output += '</select></td><td><select name="year" onchange="javascript:self.calendar.changeYear(this.value);" style="visibility:hidden;">';
	    
	    for (y = this.getStartYear(); y <= this.getEndYear(); y++) {
	    	if (y == year) {
	    		output += '<option value="' + y + '" selected>' + y + '</option>';
	    	}
	        else {
	        	output += '<option value="' + y + '">' + y + '</option>';
	        }
	    }
	
	    output += '</select></td></tr></table></td></tr><tr><td colspan="2" align="center" valign="middle">';
	
	    firstDay = new Date(year, month, 1);
	    startDay = firstDay.getDay() -1 ;
	    if (startDay < 0)
			startDay = 6;
	
	    output += '<table align="center" cellspacing="0" cellpadding="0" border="0"><tr>';
	
	    for (i = 0; i < 6; i++)
	        output += '<td style="text-align:center;vertical-align:middle;width:50px;height:30px;padding:0px;">' + this.dow[i] +'</td>';
	
		// Sunday...
	    output += '<td style="text-align:center;vertical-align:middle;width:50px;height:30px;padding:0px;">' + this.dow[i] +'</td>';
	
	    output += '</tr><tr>';
	
	    var column = 0;
	    var lastMonth = month - 1;
	    if (lastMonth == -1) lastMonth = 11;
	    
	    var daysForMonth = getDaysForMonth(year, lastMonth);
	    
	    for (i = 0; i < startDay; i++, column++)
	        output += '<td style="text-align:center;vertical-align:middle;width:50px;height:30px;padding:0px;">' + (daysForMonth - startDay + i + 1) + '</td>';
	    
	    daysForMonth = getDaysForMonth(year, month);
	    
		for (i = 1; i <= daysForMonth; i++, column++) {
			if (i == this.day && month == this.current.getMonth() && year == this.y2k(this.current.getYear())) {
				output += '<td style="text-align:center;vertical-align:middle;width:50px;height:30px;padding:0px;font-weight:bold;" class="calendarheader">' + '<a href="javascript:self.calendar.changeDay(' + i + ');">' + i + '</a>' +'</td>';
			}
			else {
				output += '<td style="text-align:center;vertical-align:middle;width:50px;height:30px;padding:0px;font-weight:bold;">' + '<a href="javascript:self.calendar.changeDay(' + i + ');">' + i + '</a>' +'</td>';
			}
			if (column == 6) {
				output += '</tr><tr>';
				column = -1;
			}
		}
	
	    if (column > 0) {
	        for (i = 1; column <= 6; i++, column++) {
	        	output += '<td style="text-align:center;vertical-align:middle;width:50px;height:30px;padding:0px;">' + i + '</td>';
	        }
	    }
	    
	    output += '</tr></table></td></tr>';
	    
	    output += '<tr><td colspan="2" align="center" valign="middle" style="text-align:center;padding:5px;font-weight:bold;"><a href="javascript:self.calendar.hide()">Schließen</a></td></tr>';
	
	    output += '</table>';
	
	    return output;
	}
	
	this.bug = function(show) {
		
		var shimWindow = document.getElementById('shim');
		
		if(show) {
			
			var theWindow = this.window;
			
			window.setTimeout(function() {
				
				shimWindow.style.zIndex = theWindow.style.zIndex - 1;
				shimWindow.style.width = parseInt(theWindow.offsetWidth) + 'px';
				shimWindow.style.height = parseInt(theWindow.offsetHeight) + 'px';
				shimWindow.style.top = parseInt(theWindow.style.top) + 'px';
				shimWindow.style.left = parseInt(theWindow.style.left) + 'px';
				
				theWindow.getElementsByTagName('select')[0].style.visibility = 'visible';
				theWindow.getElementsByTagName('select')[1].style.visibility = 'visible';
				
				shimWindow.style.visibility = 'visible';
			}, 400);
		}
		else {
			shimWindow.style.visibility = 'hidden';
		}
	}
	
	self.calendar = this;
	closeWindows();
	
	this.names = new makeArray('Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember');
	this.dow = new makeArray('Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So');
	
	this.datfield = datfield;
	this.today = new Date();
	this.current = this.today;
	
	var datfieldValue = document.getElementById(this.datfield).value;
	if(datfieldValue != '') {
		
		var checkedDate = checkDate(datfieldValue, this.getStartYear(), this.getEndYear());
		if(checkedDate != null) {
			this.current = checkedDate;
		}
	}

	this.day = this.current.getDate();
	this.month = this.current.getMonth();
	this.year = this.y2k(this.current.getYear());
	this.window = document.getElementById('calendar');
	this.target = document.getElementById(this.datfield).parentNode;
	
	if(this.window.style.zIndex < this.target.style.zIndex + 2) {
		this.window.style.zIndex = this.target.style.zIndex + 2;
	}
	this.window.style.top = absTop(this.target) + 'px';
	
	this.window.style.left = absLeft(this.target.offsetParent) + 'px';
	
	// Only for IE 6 and the 'shim' element...
	if(navigator.appVersion.indexOf('MSIE 6') != -1) {
		this.window.style.display = 'block';
	}
	else {
		Effect.Appear(this.window, { duration: 0.3 });
	}

	this.reload();
}

function AgeCalculator(birthday, now) {
	
	this.calculate = function() {
		
		var years = -1;
		
		if(this.birthdayDate && this.nowDate != null) {
			
			var first = this.nowDate.getYear();
			var second = this.birthdayDate.getYear();
			
			first = (first < 1000) ? first + 1900 : first;
			second = (second < 1000) ? second + 1900 : second;
			
			years = first - second;
			if((this.nowDate.getMonth() < this.birthdayDate.getMonth()) || (this.nowDate.getMonth() == this.birthdayDate.getMonth() && this.nowDate.getDate() < this.birthdayDate.getDate())) {
				years--;
			}
		}
		
		return years;
	}
	
	this.birthdayDate = checkDate(birthday);
	this.nowDate = now ? checkDate(now) : new Date();
}

function getDaysForMonth(year, month) {
	
	if(month == 1) {
		
		if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
	    	
			return 29;
		}
	    else {
	    	
	    	return 28;
	    }
	}
	else if(month >= 0 && month < 12) {
		
		var days = new makeArray(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
		
		return days[month];
	}
	
	return 30;
}

function checkDate(dateValue, startYear, endYear) {
	
	var date = null
	
	startYear = startYear || new Date().getYear() - 100;
	endYear = endYear || new Date().getYear() + 30;
	
	startYear = (startYear < 1000) ? startYear + 1900 : startYear;
	endYear = (endYear < 1000) ? endYear + 1900 : endYear;
	
	try {
		var dateParts = dateValue.split('.');
		if(dateParts.length == 3) {
			if(!isNaN(dateParts[2] = parseInt(dateParts[2], 10)) && (dateParts[2] = (dateParts[2] < 1000) ? dateParts[2] + 1900 : dateParts[2]) >= startYear && dateParts[2] <= endYear
				&& !isNaN(dateParts[1] = parseInt(dateParts[1], 10)) && dateParts[1] >= 1 && dateParts[1] <= 12
				&& !isNaN(dateParts[0] = parseInt(dateParts[0], 10)) && dateParts[0] >= 1 && dateParts[0] <= getDaysForMonth(dateParts[2], dateParts[1] - 1)
				) {
				var checkedDate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
				if(!isNaN(checkedDate.getTime())) {
					date = checkedDate;
				}
			}
		}
	}
	catch(e) {
		// Do nothing...
	}
	
	return date;
}

function bugMultiSelect(show) {
	
	var multiSelectWindow = document.getElementById('multiSelect');
	var shimWindow = document.getElementById('shim');

	if(show && multiSelectWindow.style.visibility == 'visible') {
		shimWindow.style.zIndex = multiSelectWindow.style.zIndex - 1;
		shimWindow.style.width = parseInt(multiSelectWindow.offsetWidth) + 'px';
		shimWindow.style.height = parseInt(multiSelectWindow.offsetHeight) + 'px';
		shimWindow.style.top = parseInt(multiSelectWindow.style.top) + 'px';
		shimWindow.style.left = parseInt(multiSelectWindow.style.left) + 'px';
		shimWindow.style.visibility = 'visible';
	}
	else {
		shimWindow.style.visibility = 'hidden';
	}
}

function showMultiSelect(maxWidth, maxHeight, target, offset) {

	//var multiSelectLabel = multiSelectValues[2];
	var multiSelectHeaders = multiSelectValues[3];
	var multiSelectRows = multiSelectValues[4];
	var window = document.getElementById('multiSelect');
	var output = '';

	window.style.width = '0px';
	window.style.height = '0px';

	if(target == null) {
		target = document.getElementById(multiSelectCurrentField);
	}
	
	if(offset == null) {
		offset = 0;
	}

	closeWindows();

	output += '<div class="form_x">';
	output += '<table id="multiSelectTable" width="100%" align="center" border="0" cellpadding="0" cellspacing="0" class="formbody">';
	output += '<tr>';
	output += '<td>';
	output += '<table width="100%" align="center" border="0" cellpadding="0" cellspacing="0">';
	
	output += '<tr>';
	output += '<td class="page_message_title"><a class="plainlink" href="javascript:hideMultiSelect();"><span class="message_text">Schließen</span></a></td>';
	for(var u = 0; u < multiSelectHeaders.length; u++) {
			output += '<td style="padding-left:0px;" nowrap="nowrap" class="page_message_title"><b>' + multiSelectHeaders[u] + '</b></td>'
	}
	output += '</tr>';
	
	for(var i = 0; i < multiSelectRows.length; i++) {
		output += '<tr>';
		output += '<td class="page_message_content"><a class="plainlink" href="javascript:fillMultiSelect(' + i + ');hideMultiSelect();"><span class="message_text">Auswählen</span></a></td>';
		for(var j = 0; j < multiSelectRows[i].length; j++) {
			output += '<td style="padding-left:0px;" nowrap="nowrap"  class="page_message_content">' + multiSelectRows[i][j] + '</td>';
		}
		output += '</tr>';
	}
	
	output += '</table>';
	output += '</td>';
	output += '</tr>';
	output += '</table>';
	output += '</div>';
	
	window.style.zIndex = target.style.zIndex + 2;
	window.style.top = (absTop(target) + offset) + 'px';
	window.style.left = (absLeft(target) + offset) + 'px';
	window.innerHTML = output;	
	window.style.width = Math.min(parseInt(document.getElementById('multiSelectTable').offsetWidth) + 25, maxWidth) + 'px';
	window.style.height = Math.min(parseInt(document.getElementById('multiSelectTable').offsetHeight) + 25, maxHeight) + 'px';
	window.style.visibility = 'visible';
	
	bugMultiSelect(true);
}

function hideMultiSelect() {
	
	var multiSelectWindow = document.getElementById('multiSelect');
	if(multiSelectWindow != null) {
		bugMultiSelect(false);
		multiSelectWindow.style.visibility = 'hidden';
		multiSelectWindow.innerHTML = '';
	}
}

function showHelp(basePath, table, prefix, column, target) {

	var element = document.getElementById('helpdiv');

	if(element != null) {
		
		element.style.display = 'none';
		
		element.style.zIndex = target.style.zIndex + 2;
		element.style.top = absTop(target) + 30 + 'px';
		
		element.style.left = absLeft(target) + 30 + 'px';
		
		element.innerHTML = '';
		
		var httpObject = getHTTPObject();
		
		if(httpObject != null) {
			
			var queryString = '?table=' + table + '&prefix=' + prefix + '&column=' + column;
			httpObject.open('GET', basePath + 'help.php' + queryString);
			
			httpObject.onreadystatechange = function() {
	
				try {
					if(httpObject.readyState == 4) {
						if(httpObject.status == 200) {
							element.innerHTML = trim(httpObject.responseText);
							if(element.innerHTML != '')
								element.style.display = 'block';
						}
					}
				}
				catch(e) {
					location.reload();
				}
			};
			httpObject.send(null);
		}
	}
}

function getLocalGuid() {
	
	return global.generate_local_guid();
}

function submitCustomAction(control, actionCount) {
	
	actionCount = actionCount ? actionCount : 0;
	
	if(control.selectedIndex > actionCount) {
		
		if(control.value != '') {
			
			var doIt = function() { return true; };
			
			if(customActionScripts[control.selectedIndex - actionCount - 1] != '') {
				eval('doIt = function() { ' + customActionScripts[control.selectedIndex - actionCount - 1] + ' }');
			}
			
			if(doIt()) {
				document.getElementById('action').value = 'customaction';
				document.getElementById('customaction').value = control.value;
				control.form.method = customActionMethods[control.selectedIndex - actionCount - 1];
				control.disabled = true;
				control.form.submit();
				try {
					window.setTimeout(function() {
						try {
							var customaction_guid = document.getElementById('customaction_guid');
							customaction_guid.value = getLocalGuid();
							control.selectedIndex = 0;
							control.disabled = false;
						}
						catch(innerE) {
							// Do nothing...
						}
					}, 1000);
				}
				catch(e) {
					// Do nothing...
				}
			}
			else {
				control.selectedIndex = 0;
			}
		}
	}
	else {
		
		location.href = control.value;
	}
}

function submitOnEnter(event) {
	
	if(eval('typeof doAction') == 'function')
		return doActionOnEnter(event, eval('doAction'));
	
	event = event || window.event;
	
	if(event.keyCode == 13) {
	    var autocomplete = document.getElementById('autocomplete');
	    if(autocomplete && autocomplete.style.display == 'none') {
	    	var target = event.target || event.srcElement;
	    	target.form.submit();
    		event.returnValue = false;
		}
	}

	return true;
}

function doActionOnEnter(event, callback) {
	
	event = event || window.event;
	
	if(event.keyCode == 13) {
	    var autocomplete = document.getElementById('autocomplete');
	    if(autocomplete && autocomplete.style.display == 'none') {
	    	callback();
    		event.returnValue = false;
		}
	}

	return true;
}

function imposeMaxLength(obj, maxLen)
{
	if(obj.value.length > maxLen) {
		obj.value = obj.value.substring(0, maxLen);
	}
}

function findField(field, tag) {
	
	var node = document.getElementById(field);
	
	if(node != null)
		return node;
	
	tag = tag != null ? tag : "*";
	
	var allTags = document.body.getElementsByTagName(tag);
	var ids = [];
	var tag = null;
	for (var i = 0; i < allTags.length; i++) {
	    tag = allTags[i];
	    if (tag.id) {
	    	ids.push(tag.id);
	    }   
	}
	
	var value = null;
	var found = null;
	for(i = 0; i < ids.length; i++) {
		value = ids[i];
		found = value.search(field);
		if(found > 0 && value[found - 1] == '_' && found + field.length == value.length) {
			break;
		}
	}

	return document.getElementById(value);
}

function showPreview(path, guid, action, str, width, height, target) {
	
	var element = document.getElementById('preview_div');

	if(element != null) {
		
		element.style.zIndex = target.style.zIndex + 2;
		element.style.top = absTop(target) + 30 + 'px';
		
		element.style.left = absLeft(target) + 30 + 'px';
		
		element.innerHTML = 'Bild wird geladen...';
		element.style.display = 'block';
		
		var httpObject = getHTTPObject();
	
		if(httpObject != null) {
			
			var queryString = '?guid=' + guid + '&action=' + action + '&field=' + str;
			httpObject.open('GET', path + queryString);
			
			httpObject.onreadystatechange = function() {
	
				try {
					if(httpObject.readyState == 4) {
						if(httpObject.status == 200) {
							element.innerHTML = '<img src=' + path + queryString + ' width=' + width + ' height=' + height + ' />';
						}
						else {
							element.innerHTML = 'Bild konnte nicht geladen werden!';
						}
					}
				}
				catch(e) {
					location.reload();
				}
			};
			httpObject.send(null);
		}
	}
}

function toggleTbody(id) {
	
	var tbody = document.getElementById(id);
	if (tbody && typeof tbody.className == 'string') {
		if (tbody.className == 'off') {
			tbody.className = 'on';
		} 
		else {
			tbody.className = 'off';
		}
	}
	
	return false;
}

function showFieldMessage(id, text, style) {
	
	removeFieldMessage(id);
	
	if(!style) {
		
		style = 'color:#ff0000;font-weight:bold;';
	}
	
	var field = document.getElementById(id);
	
	if(field) {
	
		var element = document.createElement('div');
		var parentElement = document.getElementById(id + "_field_container");
		parentElement = parentElement || field.parentNode;
		
		element.setAttribute('style', style);
		element.innerHTML = text;
		if(parentElement.tagName.toUpperCase() == 'DIV') {
			
			element.className = 'form_error_text';

			parentElement = document.getElementById(id + "_container");
			var containerElement = document.createElement('div');
			containerElement.setAttribute('id', id + '_message');
			containerElement.style.display = 'none';

			containerElement.appendChild(element);
			element = containerElement;
		}
		else {
			element.setAttribute('id', id + '_message');
			element.style.paddingTop = '6px';
			element.style.display = 'none';
		}
		parentElement.appendChild(element);
		
		if(navigator.appVersion.indexOf('MSIE 6') != -1) {
			element.style.display = 'block';
		}
		else {
			Effect.BlindDown(element, { duration: 0.5 });
		}
	}
}

function hideFieldMessage(id) {
	
	var element = document.getElementById(id + '_message');
	
	if(element) {
		
		if(navigator.appVersion.indexOf('MSIE 6') != -1) {
			element.style.display = 'none';
		}
		else {
			Effect.BlindUp(element, {duration:0.5});
		}
		
		window.setTimeout('removeFieldMessage(\'' + id + '\')', 500);
	}
}

function removeFieldMessage(id) {
	
	var element = document.getElementById(id + '_message');
	
	if(element) {
		
		element.parentNode.removeChild(element)
	}
}

function closeWindows() {
	
	document.getElementById('autocomplete').style.display = 'none';
	document.getElementById('helpdiv').style.display = 'none';
	document.getElementById('select_div').style.display = 'none';
	document.getElementById('preview_div').style.display = 'none';
	
	if(self.calendar != null && self.calendar.hide != null) {
		self.calendar.hide();
	}
	hideMultiSelect();
}

function windowUnload() {

	closeWindows();
}

var multiSelectCurrentTable = null;
var multiSelectCurrentField = null;
var multiSelectValues = null;

window.onunload = windowUnload;
