// JavaScript Erweiterungen
Array.prototype.contains = function(value) {
	for(var i=0; i<this.length; i++)
		if(this[i]==value) return true;
	return false;
}
if(!Array.prototype.push) {
	Array.prototype.push = function() {
		for(var i=0;i<arguments.length;i++){
			this[this.length]=arguments[i]
		};
		return this.length;
	}
}
if( !Function.prototype.apply ) {
	Function.prototype.apply = function(thisObj, params) {
		if(!thisObj) thisObj = window;
		if(!params) params = [];
		var args = [];
		for( var i = 0; i < params.length; i++ )
			args[ args.length ] = "params[" + i + "]";
		thisObj.__method__ = this;
		var returnValue = eval( "thisObj.__method__(" + args.join( "," ) + ");" );
		thisObj.__method__ = null;
		return returnValue;
	};
}
if( !document.getElementsByClassName ) {
	document.getElementsByClassName = function(regexp) {
		var elements = document.getElementsByTagName("*");
		var result = [];
		for(var i=0, j=elements.length; i<j; i++) {
			if(elements[i].className) {
				var ok = regexp.exec(elements[i].className);
				if(ok) result.push(elements[i]);
			}
		}
		return result;
	}
}

// Against IE memoryleaks...
// http://laurens.vd.oever.nl/weblog/items2005/closures/
Function.prototype.closure = function(obj) {
  // Init object storage.
  if (!window.__objs) {
    window.__objs = [];
    window.__funs = [];
  }

  // For symmetry and clarity.
  var fun = this;

  // Make sure the object has an id and is stored in the object store.
  var objId = obj.__objId;
  if (!objId)
    __objs[objId = obj.__objId = __objs.length] = obj;

  // Make sure the function has an id and is stored in the function store.
  var funId = fun.__funId;
  if (!funId)
    __funs[funId = fun.__funId = __funs.length] = fun;

  // Init closure storage.
  if (!obj.__closures)
    obj.__closures = [];

  // See if we previously created a closure for this object/function pair.
  var closure = obj.__closures[funId];
  if (closure)
    return closure;

  // Clear references to keep them out of the closure scope.
  obj = null;
  fun = null;

  // Create the closure, store in cache and return result.
  return __objs[objId].__closures[funId] = function ()
  {
    return __funs[funId].apply(__objs[objId], arguments);
  };
};

// written by Dean Edwards, 2005
// with input from Tino Zijdel - crisp@xs4all.nl
// http://dean.edwards.name/weblog/2005/10/add-event/
// slightly modified
function addEvent(element, type, handler) {
	if (element.addEventListener) {
		if(type=='domcontentloaded') type='DOMContentLoaded';
		element.addEventListener(type, handler, false);
	} else {
		if (!handler.$$guid) handler.$$guid = addEvent.guid++;
		if (!element.events) element.events = {};
		var handlers = element.events[type];
		if (!handlers) {
			handlers = element.events[type] = {};
			if (element['on' + type]) handlers[0] = element['on' + type];
			element['on' + type] = handleEvent;
		}
		handlers[handler.$$guid] = handler;
	}
}
addEvent.guid = 1;

function removeEvent(element, type, handler) {
	if (element.removeEventListener)
		element.removeEventListener(type, handler, false);
	else if (element.events && element.events[type] && handler.$$guid)
		delete element.events[type][handler.$$guid];
}

function handleEvent(event) {
	event = event || fixEvent(window.event);
	var returnValue = true;
	var handlers = this.events[event.type];
	for (var i in handlers)	{
		if (!Object.prototype[i]) {
			this.$$handler = handlers[i];
			if (this.$$handler(event) === false) returnValue = false;
		} 
	}
	if (this.$$handler) this.$$handler = null;
	return returnValue;
}

function fixEvent(event) {
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
}
fixEvent.preventDefault = function() {
	this.returnValue = false;
}
fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
}

// This little snippet fixes the problem that the onload attribute on the body-element will overwrite
// previous attached events on the window object for the onload event
if (!window.addEventListener) {
	document.onreadystatechange = function() {
		if (window.onload && window.onload != handleEvent)
		{
			addEvent(window, 'load', window.onload);
			window.onload = handleEvent;
		}
	}
}

// onDOMContentLoaded - Taken from http://dean.edwards.name/weblog/2006/06/again/
// for Internet Explorer (using conditional comments)
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
    if (this.readyState == "complete") {
        document.ondomcontentloaded({ "type": "domcontentloaded", "preventDefault": fixEvent.preventDefault, "stopPropagation": fixEvent.stopPropagation });
    }
};
/*@end @*/

// Solution for Safari:
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            clearInterval(_timer);
            document.ondomcontentloaded({ "type": "domcontentloaded", "preventDefault": fixEvent.preventDefault, "stopPropagation": fixEvent.stopPropagation });
        }
    }, 10);
}
addEvent(document,'domcontentloaded', function() { window.documentcontentisloaded = true });
addEvent(window,'load',function() { if(!window.documentcontentisloaded && document.ondomcontentloaded) document.ondomcontentloaded({ "type": "domcontentloaded", "preventDefault": fixEvent.preventDefault, "stopPropagation": fixEvent.stopPropagation }); });

// Original script by ppk http://www.quirksmode.org
// modified by Alex Tingle http://blog.firetree.net/2005/07/04/javascript-find-position/
function findPosY(obj) {
    var curtop = 0;
    if(obj.offsetParent)
        while(1) {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
}

function JavaScriptEnhancements() {

	var initdone = false;
	var jsessionid = false;
	
	this.init = function() {
		if(initdone) return false;
		initdone = true;
		
	
		// Links bearbeiten
		var links = document.getElementsByTagName("a");
		for(var i=links.length-1;i>=0;i--) {
			if(links[i].getAttribute("rel")) {
				var relation = getRelation(links[i]);
				var params = getParams(links[i].getAttribute("rel"));
				switch(relation) {
					case 'image':
					case 'flash':
					case 'pdf':
									links[i].onclick = (new Function("return !window.open('"+links[i].getAttribute("href")+"');")).closure(links[i]);
									links[i].setAttribute("title","Link öffnet ein neues Fenster");
									break;
					case 'extern':
									if(!params['width'] && !params['height'] && !params['name']) {
										links[i].onclick = (new Function("return !window.open('"+links[i].getAttribute("href")+"');")).closure(links[i]);
									} else {
										links[i].onclick = (new Function("return !openNewPopupWH('"+links[i].getAttribute("href")+"',"+params['width']+","+params['height']+",'"+params['name']+"');")).closure(links[i]);
									}
									links[i].setAttribute("title","Link öffnet ein neues Fenster");
									break;									
					case 'replace':
									links[i].onclick = function() { return !window.location.replace(this.getAttribute('href')); }.closure(links[i]);
									break;
				}
			}
		}
		
		// Mailadressen
		var spans = document.getElementsByTagName("span");
		for(var m=spans.length-1;m>=0;m--) {
			if(spans[m].className && spans[m].className.match(/mail/)) {
				var params = getParams(spans[m].className);
				var text = spans[m].firstChild.data;
				var maillink = document.createElement("a");
				var href = "mailto:" + (params['email']?params['email'].replace(/%20at%20/,'@'):text.replace(/\u00a0\u0022at\u0022\u00a0/,'@'));
				for(var key in params) {
					if(key!='email' && key!='contains') href += (href.indexOf('?')!=-1?'&':'?') + key + '=' + params[key];
				}
				maillink.href = href;
				var textnode = document.createTextNode(text.replace(/\u00a0\u0022at\u0022\u00a0/,'@'));
				maillink.appendChild(textnode);
				for(var n=0; n<spans[m].childNodes.length; n++) {
					if(spans[m].childNodes[n].nodeType==1)
						maillink.appendChild(spans[m].childNodes[n].cloneNode(true));
				}
				for(n=0;n<spans[m].attributes.length; n++) 
					if(spans[m].attributes[n].nodeName != 'class' && spans[m].attributes[n].nodeName != 'className')
						maillink.setAttribute(spans[m].attributes[n].nodeName, spans[m].attributes[n].nodeValue);
				spans[m].parentNode.replaceChild(maillink,spans[m]);
			}
		}
	}
	
	function isParent(parent,child) {
		var runner = child;
		while(runner.parentNode!=null) {
			runner = runner.parentNode;
			if(runner.getAttribute && runner.getAttribute("id")==parent) return true;
		}
		return false;
	}
	
	function getRelation(obj) {
		var rel=obj.getAttribute("rel");
		if(!rel)return false;
	  return rel.indexOf("(")==-1?rel:rel.substring(0,rel.indexOf("("));
	}
	
	function getParams(attr) {
    if(attr.indexOf("(")==-1||attr.indexOf(")")==-1) return [];
		var pliste = attr.substring(attr.indexOf("(")+1,attr.indexOf(")"))
		var ergebnis = {};
		var parameter = pliste.split(";");
		for(var i=0;i<parameter.length;i++) {
			var nameValue = parameter[i].split("=");
			ergebnis[nameValue[0]]=nameValue[1];
		}
		return ergebnis;
	}

	this.getParameter = function(text) {
		return getParams(text);
	}
	
	function encodeUrl(href) {
		if(jsessionid)
	 		if(href.indexOf("?")!=-1) {
				href=href.substring(0,href.indexOf("?"))+";jsessionid="+jsessionid+href.substring(href.indexOf("?"));
			} else {
				href=href+";jsessionid="+jsessionid;
			}
		return href;
	}
}

var enhancements = new JavaScriptEnhancements();
addEvent(document,'domcontentloaded',enhancements.init);

// openPopup() verwendet eine feste Breite und feste Höhe
// javascript:openPopup('...', '...') ist als href zu setzen
// (s.a. jsUsageOpenPopup.jsp)
function openNewPopup(popurl, fenstername) {
    var hoehe=528, weite=528;
	
	return openPopupWindow(popurl, weite, hoehe, fenstername, true, true, false);
}
function openPopup(popurl, fenstername) {
	openNewPopup(popurl,fenstername);	
}

function openXPopup(popurl, fenstername) {
    var hoehe=555, weite=530;
	return openPopupWindow(popurl, weite, hoehe, fenstername, false, true, false);
}

// javascript:openPopupWH('...', breite, hoehe) ist als href zu setzen
// (s.a. jsUsageOpenPopup.jsp)
function openNewPopupWH(popurl, width, height) {
    return openPopupWindow(popurl, width, height, '_blank');
}
function openPopupWH(popurl, width, height) {
	if(!width||!height) {
		openPopup(popurl,'_blank');
	} else {
    	openNewPopupWH(popurl, width, height);
	}
}

// javascript:openPopupWH('...', breite, hoehe) ist als href zu setzen
// (s.a. jsUsageOpenPopup.jsp)
function openWerbePopupWH(popurl, width, height) {
    return openPopupWindow(popurl, width, height, 'werbung', false, false, false);
  }

// openHilfePopup() verwendet eine feste Breite und feste Höhe für das Hilfe-Popup
// javascript:openHilfePopup('...', '...') ist als href zu setzen
// (s.a. jsUsageOpenPopup.jsp)
function openNewHilfePopup(popurl, fenstername) {
    var weite=320,hoehe=300;
    return openPopupWindow(popurl, weite, hoehe, 'hilfe', true, false, false);
  }
function openHilfePopup(popurl) {
    openHilfePopup(popurl, 'hilfe');
  }
function openHilfePopup(popurl, fenstername) {
    openNewHilfePopup(popurl, 'hilfe');
  }

// javascript:openPopupD('...', breite, hoehe) ist als href zu setzen
// (s.a. jsUsageOpenPopup.jsp)
function openPopupD(popurl, width, height) {
	height = Math.min(600,height);
	width  = Math.min(700,width);
    openPopupWindow(popurl, width, height, "HTMLAntrag");
}

function openWindow(url) {
	window.open(url);
}
function openPopupWindow(popurl, width, height, name) {
	var DEFAULTS = [], NAMES = ['scrollbars','status','resizable','menubar','toolbar','location'];
	DEFAULTS['scrollbars'] = true;
	DEFAULTS['status'] = true;
	DEFAULTS['resizable'] = true;
	DEFAULTS['menubar'] = false;
	DEFAULTS['toolbar'] = false;
	DEFAULTS['location'] = false;
	if(arguments.length > 4) {
		for(var i=0; i<arguments.length-4;i++) {
			DEFAULTS[NAMES[i]] = arguments[4+i];
		}
	}
	if(!name || name == '') name = '_blank';
    var top=20, left=20;

    if (screen) {
	  height = Math.min(height, screen.height-100);
	  width = Math.min(width, screen.width-100);
	  top = Math.round((screen.height - height)/2);
	  left = Math.round((screen.width - width)/2);
	}
	
	// Im IE darf name keine Sonderzeichen enhalten
	name = name.replace(/[_-]/,"");
	
    var result = window.open(popurl, name,
    	"width=" + width + 
		",height=" + height + 
		",top=" + top + 
		",left=" + left + 
		",status=" + (DEFAULTS['status']?"yes":"no") +
		",scrollbars=" + (DEFAULTS['scrollbars']?"yes":"no") +
		",resizable=" + (DEFAULTS['resizable']?"yes":"no") + 
		",menubar=" + (DEFAULTS['menubar']?"yes":"no") + 
		",toolbar=" + (DEFAULTS['toolbar']?"yes":"no") + 
		",location=" + (DEFAULTS['location']?"yes":"no")); 		

	if(result) result.focus();
	return result;
}

// closeWin() ist in onclick eines <a name=... href=...> zu rufen
// (s.a. jsUsageCloseWin.jsp)
function closeWin() {
  if (confirm("M\xf6chten Sie das Fenster wirklich schlie\xdfen?") == true)
  	window.close();
}

// closeWin() ist in onclick eines <a name=... href=...> zu rufen
// (s.a. jsUsageCloseWin.jsp)
function closeWinNoConfirm() {
  window.close();
}


