/*
 +-----------------------------------------------------------------------+
 | js/common.js                                                          |
 |                                                                       |
 | This file is part of the Phusion Webengine                            |
 | Copyright (C) 2008-2009, Roman Gruber                                 |
 | Licensed under the GNU GPL                                            |
 |                                                                       |
 | PURPOSE:                                                              |
 |   Provides severall functions used in specific way                    |
 |                                                                       |
 | TODO:                                                                 |
 |   log() does not runs in new opened windows or iframes                |
 |                                                                       |
 +-----------------------------------------------------------------------+
 | Author: Roman Gruber <roman@phusion.ch>                               |
 +-----------------------------------------------------------------------+
*/

function customerrorhandler(desc,page,line,chr)  {
	var text = "Error description: "+desc+", Line number: "+line+ ", Page address: "+page;
	log(text, "Javascipt Error");
	return false;
}

window.onerror=customerrorhandler;

function shuffle(o){
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
}


function getX(e){
	var x = 0;
	while(e){
		x += e.offsetLeft;
		e = e.offsetParent;
		}
		return parseInt(x, 10);
}

function getY(e){
	var y = 0;
	while(e){
		y += e.offsetTop;
		e = e.offsetParent;
		}
		return parseInt(y, 10);
}



function getpos(obj) {
	var oobj = obj;
	var curleft = curtop = curscrolltop = curscrollleft = 0;
	if (obj.offsetParent) {
		do{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}while (obj = obj.offsetParent);
	}

	obj = oobj;
	if (obj.parentNode) {
		do{
			if(obj.scrollTop){
				curscrolltop += parseInt(obj.scrollTop, 10);
			}
			if(obj.scrollLeft){
				curscrollleft += parseInt(obj.scrollLeft, 10);
			}
		}while (obj = obj.parentNode);
	}

	var retarr = new Array();
	retarr[0] = curtop;
	retarr[1] = curleft;
	retarr[2] = curscrolltop;
	retarr[3] = curscrollleft;
	return retarr;
}

function scriptname(path) {
	var sn = path.replace(/\?.*/, "");
	sn = sn.replace(/.*\//, "");
	return sn;
}

function toolpic_show(url, obj){
	this.pos = getpos(obj);
	var top = this.pos[0];
	var left = this.pos[1];
	var div = document.createElement("div");
	div.style.border = "1px solid black";
	div.style.position = "absolute";
	div.style.top = top+20;
	div.style.left = left;
	div.id = "admin_edit_img_div";
	div.innerHTML = "<img src='"+url+"'>";
	document.getElementById("main").appendChild(div);
	setopacity("admin_edit_img_div", 9);
}

function toolpic_hide(){
	var div = document.getElementById("admin_edit_img_div");
	document.getElementById("main").removeChild(div);
}


function browser_has_flash(){
	<!-- this comment tag is to hide the enclosed code from old browsers.

	//Look for a version of Internet Explorer that supports ActiveX (i.e., one that's
	//running on a platform other than Mac or Windows 3.1) or a browser that supports
	//the plugin property of the navigator object and that has Flash Player 2.0
	//installed.

	if ((navigator.appName == "Microsoft Internet Explorer" &&
		navigator.appVersion.indexOf("Mac") == -1 &&   navigator.appVersion.indexOf("3.1") == -1) ||

		(navigator.plugins && navigator.plugins["Shockwave Flash"])
						   || navigator.plugins["Shockwave Flash 2.0"]){

		return true;
	}
	else {
		return false;
	}

	// Close the comment tag. -->
}

function change_lang(language){
	var la = "lang=" + language;
	lang = language;
	
	for (var id in loaded_containers){
		match = id.match(/^\d*$/);
		if (match == null){
			loaded_containers[id] = loaded_containers[id].replace(/lang\=../g, la);
			//alert(loaded_containers[id] + " - " + id);
			if(document.getElementById(id)){
				ajaxFunction(loaded_containers[id], id);
			}
		}
	}
	log("language changed to: \""+lang+"\"", "info")
}


var translateobj;
function translation(text, category){
	this.text = text;
	this.category = category;
}

translation.prototype={
	init:function(){
		if(document.getElementById("translate_div")){
			return;
		}
		this.div = document.createElement("div");
		this.div.style.backgroundColor = "#000000";
		this.div.style.position = "absolute";
		this.div.style.overflow = "auto";
		this.div.style.padding = "20";
		this.div.style.width = 600;
		this.div.style.height = 400;
		this.div.id = "translate_div";

		this.opts = new Array();
		this.opts["text"] = this.text;
		this.opts["category"] = this.category;
		this.trans_xml = getxml("post:func/xmlgettranslate.php", this.opts);

		try{ //Internet Explorer 
			this.xmldoc=new ActiveXObject("Microsoft.XMLDOM"); 
			this.xmldoc.async="false"; 
			this.xmldoc.loadXML(this.trans_xml);
		}catch(e){
			try{ //Firefox, Mozilla, Opera, etc.
				this.parser=new DOMParser();
				this.xmldoc=this.parser.parseFromString(this.trans_xml,"text/xml");
			}catch(e){
				alert(e.message);
				return;
			}
		}
		this.innerhtml = "<div style='width:100%; height:20; cursor:move;' onmousedown=\"dragstart(document.getElementById('translate_div'))\"></div>";
		this.innerhtml += "<h1 style='color:white;'>Manuelle Übersetzung</h1>";
		if(this.xmldoc.getElementsByTagName("indent")[0].childNodes[0].nodeValue != "empty"){
			this.indent = xmldoc.getElementsByTagName("indent")[0].childNodes[0].nodeValue;
		}else{
			this.indent = "";
		}
		if(this.xmldoc.getElementsByTagName("category")[0].childNodes[0].nodeValue != "empty"){
			this.category = xmldoc.getElementsByTagName("category")[0].childNodes[0].nodeValue;
		}else{
			this.category = "";
		}
		if(this.xmldoc.getElementsByTagName("id")[0].childNodes[0].nodeValue != "empty"){
			this.id = xmldoc.getElementsByTagName("id")[0].childNodes[0].nodeValue;
		}else{
			this.id = "";
		}
		this.text = this.xmldoc.getElementsByTagName("text")[0].childNodes[0].nodeValue;
		this.innerhtml += "<span style='color:white;'>Text: "+this.text+"</span><br>";
		this.innerhtml += "<span style='color:white;'>Kategorie: "+this.category+"</span><br>";
		this.innerhtml += "<span style='color:white;'>id: "+this.id+"</span><br>";

		this.innerhtml += "<input name='translate_input' type='hidden' id='translate_text' value='"+this.text+"'>";
		this.innerhtml += "<input name='translate_input' type='hidden' id='translate_category' value='"+this.category+"'>";
		this.innerhtml += "<input name='translate_input' type='hidden' id='translate_id' value='"+this.id+"'>";

		this.langs = this.xmldoc.getElementsByTagName("lang");
		for(var i=0;i<this.langs.length;i++){
			this.l = this.langs[i].childNodes[0].nodeValue;
			if(this.xmldoc.getElementsByTagName(this.l)){
				if(this.xmldoc.getElementsByTagName(this.l)[0].childNodes[0].nodeValue != "empty"){
					this.cont = this.xmldoc.getElementsByTagName(this.l)[0].childNodes[0].nodeValue;
				}else{
					this.cont = "";
				}
				this.innerhtml += "<span style='color:white;'>"+this.l+": </span><br>";
				this.innerhtml += "<textarea name='translate_input' style='width:540; height:200;' type='text' id='translate_"+this.l+"'>"+this.cont+"</textarea><br><br>";
			}
		}

		this.innerhtml += "<button id='translate_button_ok' onClick=\"translateobj.start();\">OK</button>&nbsp;";
		this.innerhtml += "<button id='translate_button_cancel' onClick=\"document.getElementById('main').removeChild(document.getElementById('translate_div'));\">Abbrechen</button>";

		this.div.innerHTML = this.innerhtml;
		document.getElementById("main").appendChild(this.div);
		setopacity("translate_div", 8);
	},

	start:function(){
		document.getElementById("translate_button_ok").disabled = "disabled";
		this.infos = document.getElementsByName("translate_input");
		var opts = new Array();
		for(i=0;i<this.infos.length;i++){
			opts[this.infos[i].id] = escape(this.infos[i].value);
		}
		this.trans_edit_xml = getxml("post:func/xmlsettranslate.php", opts)

		alert(this.trans_edit_xml);
		document.getElementById("translate_button_ok").disabled = "";
	}
}

function getwindowsize() {
	var width = 0;
	var height = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		width = window.innerWidth;
		height = window.innerHeight;
	}else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		width = document.documentElement.clientWidth;
		height = document.documentElement.clientHeight;
	}else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		width = document.body.clientWidth;
		height = document.body.clientHeight;
	}
	var retarr = new Array();
	retarr["height"] = parseInt(height, 10);
	retarr["width"] = parseInt(width, 10);
	return retarr;
}


var event_visible = 0;

function event_toogle(){
	if(event_visible == 0){
		event_slide_in();
	}else if(event_visible == 1){
		event_slide_out();
	}
}

function event_slide_in(){
	if(event_visible == 0){
		var icon = document.getElementById("event_slide_icon");
		icon.src = "img/icons/arrow_right.gif";
		var site_width = 1000;
		var aim = 600;
		var numberofsteps = 40;
		var element = document.getElementById("current");
		var size = getwindowsize();
		if(size["width"] < site_width){
			var left = site_width;
		}else{
			var left = ((size["width"]-site_width)/2)+site_width;
		}
		setopacity("current", 9.5);
		element.style.left = left;
		for(i=0; i<numberofsteps; i++){
			setTimeout("move('current', 'left', '-9')", 30*i);
		}
		event_visible = 1;
	}
}

function event_slide_out(){
	if(event_visible == 1){
		var icon = document.getElementById("event_slide_icon");
		icon.src = "img/icons/arrow_left.gif";
		var distance = 400;
		var numberofsteps = 40;
		var element = document.getElementById("current");

		for(i=0; i<numberofsteps; i++){
			setTimeout("move('current', 'right', '9')", 30*i);
		}
		setTimeout("event_visible = 0;", 30*i);
	}
}

function nav_top_sub_show(id){
	if(document.getElementById('sub_'+id)){
		document.getElementById('sub_'+id).style.visibility = 'visible';
	}
}

function nav_top_sub_hide(id){
	if(document.getElementById('sub_'+id)){
		document.getElementById('sub_'+id).style.visibility = 'hidden';
	}
}

function init(){
	if(navigator.userAgent){
		log("navigator.userAgent: "+navigator.userAgent, "init");
	}
	draginit();
	if(detect_browser() == "ie"){
		if(detect_ie_version() <= 6){
			alert("Ihr Internet Explorer ist zu alt um diese Seite richtig darzustellen. Bitte installieren Sie Internet Explorer 7 oder neuer.");
		}
	}
}

var last_log_entry;
function log(text, level){
	var now = new Date();
	var gmt = now.toGMTString();
	var msg = "";
	if(level != null){
		msg += " - " + level;
	}
	if(log.caller){
		if(log.caller.arguments.callee.name){
			msg += " - " + log.caller.arguments.callee.name+"();";
		}
	}
	msg += " - " + text;
	msg += "\n";

	if(document.getElementById("dbg")){
		var dbg = document.getElementById("dbg");
	}else if(opener){
		if(opener.document.getElementById("dbg")){
			var dbg = opener.document.getElementById("dbg");
		}else if(opener.opener){
			if(opener.opener.document.getElementById("dbg")){
				var dbg = opener.opener.document.getElementById("dbg");
			}else if(opener.opener.opener){
				if(opener.opener.opener.document.getElementById("dbg")){
					var dbg = opener.opener.opener.document.getElementById("dbg");
				}else{
					//not possible to log
					//alert("not possible to log: level:4");
					return;
				}
			}else{
				//not possible to log
				//alert("not possible to log: level:3");
				return;
			}
		}else{
			//not possible to log
			//alert("not possible to log: level:2");
			return;
		}
	}else{
		//not possible to log
		//alert("not possible to log: level:1");
		return;
	}

	if(msg != last_log_entry){
		dbg.value += gmt + msg;
		dbg.scrollTop = dbg.scrollHeight;
	}

	last_log_entry = msg;
}

function detect_log(){
//
}


function toogle_log(){
	if(document.getElementById("dbg_div")){
		var dbg = document.getElementById("dbg_div");
	}else if(opener){
		if(opener.document.getElementById("dbg_div")){
			var dbg = opener.document.getElementById("dbg_div");
		}
	}else if(opener.opener){
		if(opener.opener.document.getElementById("dbg_div")){
			var dbg = opener.opener.document.getElementById("dbg_div");
		}
	}
	
	if(dbg.style.visibility == "hidden"){
		dbg.style.visibility = "visible";
		dbg.style.opacity = 0.8;
	}else{
		dbg.style.visibility = "hidden";
	}
}

function registerObjectEventHandler(element, eventtype, listener, func, captures){
	var ref = function(event){ listener.handleEvent(event, func);}

	if(element.addEventListener){
		element.addEventListener(	eventtype,
									ref,
									captures);
	}else if(element.attachEvent){
		element.attachEvent(	"on"+eventtype,
								ref);
	}
	return ref;
}

function removeObjectEventHandler(element, eventtype, ref, captures){
	if(ref){
		if(element.removeEventListener){
			element.removeEventListener(eventtype, ref, captures);
		}else if(element.attachEvent){
			element.detachEvent("on"+eventtype, ref);
		}
	}
}

function new_window(type, addr){
	this.opts = "";
	if(type == "browse"){
		this.opts = "width=655px,height=450px,dependent=yes,location=no,menubar=no,scrollbars=no,status=no,toolbar=no";
	}else if(type == "fm"){
		this.opts = "width=930px,height=600px,dependent=yes,location=no,menubar=no,scrollbars=no,status=no,toolbar=no";
	}else if(type == "imp"){
		this.opts = "width=800px,height=550px,dependent=yes,location=no,menubar=no,scrollbars=no,status=no,toolbar=no";
	}

	mywindow = window.open(addr, "", opts);
	mywindow.focus();
}


function hasclass(element,cls){
	return element.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function addclass(element,cls){
	if (!this.hasclass(element,cls)) element.className += " "+cls;
}

function removeclass(element,cls){
	if (hasclass(element,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		element.className=element.className.replace(reg,' ');
	}
}

function change_active(element,cls,level){
	var all = document.getElementsByTagName("*");
	var pattern = new RegExp("(^|\\s)"+cls+"(\\s|$)");
	for (i = 0, j = 0; i < all.length; i++) {
		if ( pattern.test(all[i].className) ) {
			if(all[i] != element){
				if(level != null){
					if(hasclass(all[i], "lv"+level)){
						if(hasclass(all[i], "dblactive") || hasclass(all[i], "reactive")){
						}else if(hasclass(all[i], "active")){
							addclass(all[i],"was_active");
						}
						removeclass(all[i],cls);
						removeclass(all[i],"dblactive");
						removeclass(all[i],"reactive");
						removeclass(all[i],"dblreactive");
					}
				}else{
					if(hasclass(all[i], "dblactive") || hasclass(all[i], "reactive")){
						}else if(hasclass(all[i], "active")){
						addclass(all[i],"was_active");
					}
					removeclass(all[i],cls);
					removeclass(all[i],"dblactive");
					removeclass(all[i],"reactive");
					removeclass(all[i],"dblreactive");
				}
			}
		}
	}

	if(hasclass(element, "active") && !hasclass(element, "reactive") && !hasclass(element, "dblactive") && !hasclass(element, "dblreactive")){
		removeclass(element,"active");
		removeclass(element,"dblactive");
		addclass(element,"dblactive active");
		
	}else if(hasclass(element, "was_active")){
		addclass(element,"reactive active");
		removeclass(element,"was_active");
	}else if(hasclass(element, "reactive active")){
		removeclass(element,"reactive");
		removeclass(element,"active");
		addclass(element,"dblreactive active");
	}else if(hasclass(element, "dblreactive active")){
		removeclass(element,"dblreactive");
		removeclass(element,"active");
		addclass(element,"reactive active");
	}else if(hasclass(element, "dblactive active")){
		removeclass(element,"dblactive");
		removeclass(element,"active");
		addclass(element,"active");
	}else{
		addclass(element,"active");
	}




}


function loadcssfile(path){
	var cssfiles = document.getElementsByTagName("link");
	for(var i=0;i<cssfiles.length;i++){
		if(basename(cssfiles[i].href) == basename(path)){
			return;
		}
	}

	var ele = document.createElement("link");
	ele.setAttribute("type", "text/css");
	ele.setAttribute("rel", "stylesheet");
	ele.setAttribute("href", path);
	//document.getElementsByTagName("head")[0].appendChild(ele);
	document.getElementById("head").appendChild(ele);
	log("additional css file loaded: "+path, "info");
}

function progess(){
	var i = 0;
	for (var key in load){
		if(document.getElementById(key)){
			i++;
		}
	}
 
	loaded++;
	log(loaded+"/"+i+" Modules loaded");
	var percent = Math.round((100/i)*loaded);
	preloader.innerHTML = "<table style='width:100%; height:100%; vertical-align:middle; text-align:center;'><tr><td></td><td style='width:200px;'><span>"+percent+"%</span><br><div style='border:1px solid black; height:15px; width:200px; background-color:white;'><div style='height:15px; width:"+(percent*2)+"px; background-color:green;'></div></div><br><input type='button' value='Weiter' onClick='document.body.removeChild(preloader);'></td><td></td></tr></table>";
	if(loaded == i){
		if(document.getElementById(preloader.id)){
			this.fadeobj = new fade(null, preloader.id);
			fadeobj.onfinish("document.body.removeChild(preloader);");
			this.fadeobj.fade_speed = 60;
			this.fadeobj.colortolucency();
		}
		setTimeout("if(document.getElementById(preloader.id)){document.body.removeChild(preloader);} log('+----------------------------------+', 'init'); log('| Website initialization finished! |', 'init'); log('+----------------------------------+', 'init');", 1000);
	}
}

var topbg = "";
var topimg = "";
function change_imgs(img, level){
	if(img != null && level != null){
		if(level == 1){
			if(bg != ""){
				topbg = bg;
			}
			if(img != ""){
				topimg = img;
			}
		}
	}else{
		window.scrollTo(0, 0);
	}
	
	imgdiv = document.getElementById("img");

	if(img != ""){
		if(img.match(/\.flv$/)){
			var obj = "<object id='flowplayer' style='height:206px; width:900px; float:left;' data='third_party/flowplayer/flowplayer-3.1.5.swf' type='application/x-shockwave-flash'><param name='movie' value='third_party/flowplayer/flowplayer-3.1.5.swf' /><param name='allowfullscreen' value='false' /><param name='flashvars' value=\"config={'clip':'/web_eng_example/"+img+"', 'plugins':{'controls':null}}\" /></object>";
			imgdiv.innerHTML = obj;
		}else{
			imgdiv.style.backgroundImage = "url("+img+")";
//			imgdiv.innerHTML = "";
		}
	}
}

var way = new Array();
var waypoint = 0;
function colorfade(){
	way[0] = "B2F0FF";
	way[1] = "E5E5E5";

	document.body.style.backgroundColor = "#"+way[0].substr(0, 2)+way[0].substr(2, 2)+way[0].substr(4, 2);
	setInterval("colorfade_run();", 250);
}

function colorfade_run(){
	var current = new RGBColor(document.body.style.backgroundColor);
	current = current.toHex();
	var cur = new Array();
	cur[0] = current.substr(1, 2);
	cur[1] = current.substr(3, 2);
	cur[2] = current.substr(5, 2);

	//var parts = way[waypoint].split(" -> ");

	if(waypoint == (way.length-1)){
		var next = 0;
	}else{
		var next = waypoint+1;
	}

	var start = new Array();
	var end = new Array();
	start[0] = way[waypoint].substr(0, 2);
	start[1] = way[waypoint].substr(2, 2);
	start[2] = way[waypoint].substr(4, 2);
	end[0] = way[next].substr(0, 2);
	end[1] = way[next].substr(2, 2);
	end[2] = way[next].substr(4, 2);

	for(var xy = 0;xy<3;xy++){
		if(parseInt(end[xy], 16) > parseInt(start[xy], 16)){
			if(parseInt(start[xy], 16) <= parseInt(cur[xy], 16) && parseInt(end[xy], 16) > parseInt(cur[xy], 16)){
				cur[xy] = parseInt(cur[xy], 16)+1;
				cur[xy] = cur[xy].toString(16);
				document.body.style.backgroundColor = "#"+cur[0]+cur[1]+cur[2];
			}
		}else if(parseInt(end[xy], 16) < parseInt(start[xy], 16)){
			if(parseInt(start[xy], 16) >= parseInt(cur[xy], 16) && parseInt(end[xy], 16) < parseInt(cur[xy], 16)){
				cur[xy] = parseInt(cur[xy], 16)-1;
				cur[xy] = cur[xy].toString(16);
				document.body.style.backgroundColor = "#"+cur[0]+cur[1]+cur[2];
			}
		}
	}

	if(parseInt(cur[0], 16) == parseInt(end[0], 16) && parseInt(cur[1], 16) == parseInt(end[1], 16) && parseInt(cur[2], 16) == parseInt(end[2], 16)){
		if(waypoint == (way.length-1)){
			waypoint = 0;
		}else{
			waypoint++;
		}
	}
}

function RGBColor(color_string){
    this.ok = false;

    // strip any leading #
    if (color_string.charAt(0) == '#') { // remove # if any
        color_string = color_string.substr(1,6);
    }

    color_string = color_string.replace(/ /g,'');
    color_string = color_string.toLowerCase();

    // before getting into regexps, try simple matches
    // and overwrite the input
    var simple_colors = {
        aliceblue: 'f0f8ff',
        antiquewhite: 'faebd7',
        aqua: '00ffff',
        aquamarine: '7fffd4',
        azure: 'f0ffff',
        beige: 'f5f5dc',
        bisque: 'ffe4c4',
        black: '000000',
        blanchedalmond: 'ffebcd',
        blue: '0000ff',
        blueviolet: '8a2be2',
        brown: 'a52a2a',
        burlywood: 'deb887',
        cadetblue: '5f9ea0',
        chartreuse: '7fff00',
        chocolate: 'd2691e',
        coral: 'ff7f50',
        cornflowerblue: '6495ed',
        cornsilk: 'fff8dc',
        crimson: 'dc143c',
        cyan: '00ffff',
        darkblue: '00008b',
        darkcyan: '008b8b',
        darkgoldenrod: 'b8860b',
        darkgray: 'a9a9a9',
        darkgreen: '006400',
        darkkhaki: 'bdb76b',
        darkmagenta: '8b008b',
        darkolivegreen: '556b2f',
        darkorange: 'ff8c00',
        darkorchid: '9932cc',
        darkred: '8b0000',
        darksalmon: 'e9967a',
        darkseagreen: '8fbc8f',
        darkslateblue: '483d8b',
        darkslategray: '2f4f4f',
        darkturquoise: '00ced1',
        darkviolet: '9400d3',
        deeppink: 'ff1493',
        deepskyblue: '00bfff',
        dimgray: '696969',
        dodgerblue: '1e90ff',
        feldspar: 'd19275',
        firebrick: 'b22222',
        floralwhite: 'fffaf0',
        forestgreen: '228b22',
        fuchsia: 'ff00ff',
        gainsboro: 'dcdcdc',
        ghostwhite: 'f8f8ff',
        gold: 'ffd700',
        goldenrod: 'daa520',
        gray: '808080',
        green: '008000',
        greenyellow: 'adff2f',
        honeydew: 'f0fff0',
        hotpink: 'ff69b4',
        indianred : 'cd5c5c',
        indigo : '4b0082',
        ivory: 'fffff0',
        khaki: 'f0e68c',
        lavender: 'e6e6fa',
        lavenderblush: 'fff0f5',
        lawngreen: '7cfc00',
        lemonchiffon: 'fffacd',
        lightblue: 'add8e6',
        lightcoral: 'f08080',
        lightcyan: 'e0ffff',
        lightgoldenrodyellow: 'fafad2',
        lightgrey: 'd3d3d3',
        lightgreen: '90ee90',
        lightpink: 'ffb6c1',
        lightsalmon: 'ffa07a',
        lightseagreen: '20b2aa',
        lightskyblue: '87cefa',
        lightslateblue: '8470ff',
        lightslategray: '778899',
        lightsteelblue: 'b0c4de',
        lightyellow: 'ffffe0',
        lime: '00ff00',
        limegreen: '32cd32',
        linen: 'faf0e6',
        magenta: 'ff00ff',
        maroon: '800000',
        mediumaquamarine: '66cdaa',
        mediumblue: '0000cd',
        mediumorchid: 'ba55d3',
        mediumpurple: '9370d8',
        mediumseagreen: '3cb371',
        mediumslateblue: '7b68ee',
        mediumspringgreen: '00fa9a',
        mediumturquoise: '48d1cc',
        mediumvioletred: 'c71585',
        midnightblue: '191970',
        mintcream: 'f5fffa',
        mistyrose: 'ffe4e1',
        moccasin: 'ffe4b5',
        navajowhite: 'ffdead',
        navy: '000080',
        oldlace: 'fdf5e6',
        olive: '808000',
        olivedrab: '6b8e23',
        orange: 'ffa500',
        orangered: 'ff4500',
        orchid: 'da70d6',
        palegoldenrod: 'eee8aa',
        palegreen: '98fb98',
        paleturquoise: 'afeeee',
        palevioletred: 'd87093',
        papayawhip: 'ffefd5',
        peachpuff: 'ffdab9',
        peru: 'cd853f',
        pink: 'ffc0cb',
        plum: 'dda0dd',
        powderblue: 'b0e0e6',
        purple: '800080',
        red: 'ff0000',
        rosybrown: 'bc8f8f',
        royalblue: '4169e1',
        saddlebrown: '8b4513',
        salmon: 'fa8072',
        sandybrown: 'f4a460',
        seagreen: '2e8b57',
        seashell: 'fff5ee',
        sienna: 'a0522d',
        silver: 'c0c0c0',
        skyblue: '87ceeb',
        slateblue: '6a5acd',
        slategray: '708090',
        snow: 'fffafa',
        springgreen: '00ff7f',
        steelblue: '4682b4',
        tan: 'd2b48c',
        teal: '008080',
        thistle: 'd8bfd8',
        tomato: 'ff6347',
        turquoise: '40e0d0',
        violet: 'ee82ee',
        violetred: 'd02090',
        wheat: 'f5deb3',
        white: 'ffffff',
        whitesmoke: 'f5f5f5',
        yellow: 'ffff00',
        yellowgreen: '9acd32'
    };
    for (var key in simple_colors) {
        if (color_string == key) {
            color_string = simple_colors[key];
        }
    }
    // emd of simple type-in colors

    // array of color definition objects
    var color_defs = [
        {
            re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
            example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
            process: function (bits){
                return [
                    parseInt(bits[1]),
                    parseInt(bits[2]),
                    parseInt(bits[3])
                ];
            }
        },
        {
            re: /^(\w{2})(\w{2})(\w{2})$/,
            example: ['#00ff00', '336699'],
            process: function (bits){
                return [
                    parseInt(bits[1], 16),
                    parseInt(bits[2], 16),
                    parseInt(bits[3], 16)
                ];
            }
        },
        {
            re: /^(\w{1})(\w{1})(\w{1})$/,
            example: ['#fb0', 'f0f'],
            process: function (bits){
                return [
                    parseInt(bits[1] + bits[1], 16),
                    parseInt(bits[2] + bits[2], 16),
                    parseInt(bits[3] + bits[3], 16)
                ];
            }
        }
    ];

    // search through the definitions to find a match
    for (var i = 0; i < color_defs.length; i++) {
        var re = color_defs[i].re;
        var processor = color_defs[i].process;
        var bits = re.exec(color_string);
        if (bits) {
            channels = processor(bits);
            this.r = channels[0];
            this.g = channels[1];
            this.b = channels[2];
            this.ok = true;
        }

    }

    // validate/cleanup values
    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);

    // some getters
    this.toRGB = function () {
        return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
    }
    this.toHex = function () {
        var r = this.r.toString(16);
        var g = this.g.toString(16);
        var b = this.b.toString(16);
        if (r.length == 1) r = '0' + r;
        if (g.length == 1) g = '0' + g;
        if (b.length == 1) b = '0' + b;
        return '#' + r + g + b;
    }

    // help
    this.getHelpXML = function () {

        var examples = new Array();
        // add regexps
        for (var i = 0; i < color_defs.length; i++) {
            var example = color_defs[i].example;
            for (var j = 0; j < example.length; j++) {
                examples[examples.length] = example[j];
            }
        }
        // add type-in colors
        for (var sc in simple_colors) {
            examples[examples.length] = sc;
        }

        var xml = document.createElement('ul');
        xml.setAttribute('id', 'rgbcolor-examples');
        for (var i = 0; i < examples.length; i++) {
            try {
                var list_item = document.createElement('li');
                var list_color = new RGBColor(examples[i]);
                var example_div = document.createElement('div');
                example_div.style.cssText =
                        'margin: 3px; '
                        + 'border: 1px solid black; '
                        + 'background:' + list_color.toHex() + '; '
                        + 'color:' + list_color.toHex()
                ;
                example_div.appendChild(document.createTextNode('test'));
                var list_item_value = document.createTextNode(
                    ' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex()
                );
                list_item.appendChild(example_div);
                list_item.appendChild(list_item_value);
                xml.appendChild(list_item);

            } catch(e){}
        }
        return xml;

    }
}


function windowbox(width, height, id, content, title){
	this.width = width;
	this.height = height;
	this.id = id;
	this.content = content;
	this.title = title;
	this.wb = document.createElement("div");
	this.wb.className = "wb";
	this.wb.id = this.id;
	this.wb.style.width = this.width;
	this.wb.style.height = this.height;
	this.wb.style.left = (window.innerWidth/2)-(parseInt(this.width, 10)/2)+"px";
	this.wb.style.top = (window.innerHeight/2)-(parseInt(this.height, 10)/2)+"px";
	this.wb.innerHTML = "<table style='width:100%; height:20px;'><tr><td><span><b>"+this.title+"</b></span></td><td style='width:20px; text-align:right;'><img src='../img/icons/close.png' style='cursor:pointer;' id='windowbox_close' onClick=\"document.getElementById('"+this.id+"').style.visibility = 'hidden';\"></td></tr></table>";
	this.wb.innerHTML += "<div id='"+this.id+"_content'>"+this.content+"</div>";

	document.body.appendChild(this.wb);
	this.content = document.getElementById(this.id+"_content");
	setopacity(this.id, 9);
}

windowbox.prototype={
	show:function(){
		this.wb.style.visibility = "visible";
	},

	hide:function(){
		this.wb.style.visibility = "hidden";
	},

	close:function(){
		document.body.removeChild(this.wb);
	},

	change_content:function(c){
		this.content.innerHTML = c;
	},

	handleEvent:function(event, func){
		eval(func);
	}
}

function basename(path){
	if(path.match(/\//)){
		var parts = path.split(/\//);
		return parts[parts.length-1];
	}else{
		return path;
	}
}

function dirname(path){
	if(path.match(/\//)){
		var parts = path.split(/\//);
		var ret = "";
		for(var i=0;i<parts.length-1;i++){
			ret += parts[i]+"/";
		}
		return ret.substr(0, ret.length-1);
	}else{
		return path;
	}
}

function detect_browser(){
	this.agent = navigator.userAgent;
	if(this.agent.match(/MSIE/)){
		return "ie";
	}else if(this.agent.match(/Firefox/) && this.agent.match(/Gecko/)){
		return "firefox";
	}else if(this.agent.match(/Opera/) && this.agent.match(/Presto/)){
		return "opera";
	}else if(this.agent.match(/Safari/)){
		return "safari";
	}else{
		return "other";
	}
}

function detect_ie_version(){
	this.agent = navigator.userAgent;
	if(this.agent.match(/MSIE/)){
		this.version = this.agent.search(/MSIE\ [0-9,\.]+/);
		return parseInt(this.agent.slice((this.version+5), (this.version+6)), 10);
	}
}

function form_onstart(form, hash){
	this.file_upload = false;
	this.form = form;
	this.hash = hash;
	this.filled = true;
	this.return_value = false;

	this.elements = new Array();
	for(var i=0;i<this.form.length;i++){
		if(this.form[i].type != "submit" && this.form[i].type != "reset"){
			if(this.form[i].getAttribute("mandatory", false) == "1" && this.form[i].value == ""){
				this.form[i].style.background = "#FF4C4C url(img/icons/inactive.gif) scroll right no-repeat";
				this.filled = false;
			}else{
				this.form[i].style.background = "#66E500 url(img/icons/check.gif) scroll right no-repeat";
			}
		}
	}

	for(var i=0;i<this.form.length;i++){
		if(this.form[i].type == "submit" || this.form[i].type == "reset"){
			this.form[i].disabled = "disabled";
		}
		if(this.form[i].type != "submit" && this.form[i].type != "reset"){
			if(this.form[i].type == "text"){
				this.elements[this.form[i].name] = this.form[i].value;
			}else if(this.form[i].type == "checkbox"){
				if(this.form[i].checked){
					this.elements[this.form[i].name] = "1";
				}else{
					this.elements[this.form[i].name] = "0";
				}
			}else if(this.form[i].type == "hidden"){
				this.elements[this.form[i].name] = this.form[i].value;
			}else if(this.form[i].type == "file"){
				//fileupload
				this.file_upload = true;
			}else{
				this.elements[this.form[i].name] = this.form[i].value;
			}
		}
	}

	if(this.filled){
		var i = false;
		this.table = this.form.firstChild;
		while(i == false){
			if(this.table.nodeName == "TABLE" || this.table.nodeName == "table"){
				i=true;
			}else{
				this.table = this.table.nextSibling;
			}
		}
		this.pos = getpos(this.table);
		this.div = document.createElement("div");
		this.div.style.position = "absolute";
		this.div.style.backgroundColor = "white";
		this.div.style.top = this.pos[0] + "px";
		this.div.style.left = this.pos[1] + "px";
		this.div.style.width = this.table.offsetWidth + "px";
		this.div.style.height = this.table.offsetHeight + "px";
		this.div.id = "div_"+this.hash;
		this.div.innerHTML = "<table style='width:100%; height:100%; vertical-align:middle; text-align:center;'><tr><td><img src='img/icons/load.gif'><br><button onclick=\"form_onabort('"+this.hash+"');\">Cancel</button></td></tr></table>";
		this.form.appendChild(this.div);
		setopacity(this.div.id, 8);
		return true;
	}else{
		for(var i=0;i<this.form.length;i++){
			this.form[i].disabled = "";
		}
		alert("Sie haben nicht alle obligatorischen Felder ausgefuellt.");
		return false;
	}
}

function form_onabort(hash){
	this.hash = hash;
	this.form = document.getElementById("form_"+this.hash);
	this.div = document.getElementById("div_"+this.hash);
	this.iframe = document.getElementById("iframe_"+this.hash);
	this.form.removeChild(this.div);
	this.iframe.src = "about:blank";
}

function form_oncomplete(hash, retval){
	this.retval = retval;
	this.hash = hash;
	this.form = document.getElementById("form_"+this.hash);
	this.div = document.getElementById("div_"+this.hash);
	this.form.removeChild(this.div);

	for(var i=0;i<this.form.length;i++){
		this.form[i].disabled = "";
	}

	if(this.retval == "0"){
		for(var i=0;i<this.form.length;i++){
			if(this.form[i].type != "submit" && this.form[i].type != "reset" && this.form[i].type != "hidden"){
//				this.form[i].value = "";
				this.form[i].style.background = "";
			}
		}
		this.form.reset();
		alert("Ihre Daten wurden erfolgreich abgeschickt. Danke fuer Ihre Anfrage.");
	}else if(this.retval == "4"){
		alert("Die Sicherheitpruefung wurde falsch ausgefuellt.");
		for(var i=0;i<this.form.length;i++){
			if(this.form[i].name == "captcha"){
				this.form[i].style.background = "#FF4C4C url(img/icons/inactive.gif) scroll right no-repeat";
				this.form[i].focus();
				this.form[i].select();
			}
		}
	}else if(this.retval == "61" || this.retval == "62"){
		alert("Die angehängte Datei ist zu gross.");
	}else if(this.retval == "64"){
		alert("Sie haben keine Datei angehängt.");
	}else{
		alert("Ihre Daten konnten nicht abgeschickt werden.");
	}
}

function countdown(id, callback){
	if(document.getElementById(id)){
		this.element = document.getElementById(id);
		this.value = parseInt(this.element.innerHTML, 10);
		if(this.value > 0){
			this.element.innerHTML = this.value--;
			setTimeout("countdown('"+id+"', '"+callback+"')", 1000);
		}
	}
}

function addslashes(str) {
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\0/g,'\0');
	str=str.replace(/\\\\/g,'\\');
	return str;
}

function goto_anchor(i){
	var id = 'anchor_'+i;
	var header = document.getElementById(id);
	if(header){
		header.scrollIntoView(true);
		header.style.backgroundColor = "yellow";
		var fadeobj = new fade(null, id);
		fadeobj.fade_speed = 60;
		fadeobj.onfinish("document.getElementById('"+id+"').style.backgroundColor = ''; setopacity('"+id+"', '10');");
		fadeobj.colortolucency();
	}else{
		window.scrollTo(0, 0);
	}
}

function login(){
	var id = "login_"+strrand(20);
	var size = getwindowsize();
	var div = document.createElement("div");
	div.id = id;
	div.style.position = "fixed";
	div.style.top = (size["height"]/2)-90+"px";
	div.style.left = (size["width"]/2)-80+"px";

	document.body.appendChild(div);
	return id;
}

function strrand(length) {
	if(!length){
		length = 10;
	}
    var characters = "0123456789abcdefghijklmnopqrstuvwxyz";
    var string = "";
    for (var p=0;p<length;p++) {
        string += characters[Math.floor(Math.random()*characters.length)];
    }
    return string;
}
