function popupOpen() {		// parameter.reihenfolge: URL, WIDTH, HEIGHT
	var w,h,url,aw,ah;
	var a=popupOpen.arguments;
	if (a.length==0) return;
	url=a[0];
	if (a.length>1) {
		w=a[1]; h=a[2];
	}
	else {
		w=500; h=400
	}
	win=window.open(url,'win_front','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,width='+w+',height='+h);
	if (screen) {
		aw=screen.availWidth;
		ah=screen.availHeight;
		win.moveTo(((aw/2)-(w/2)),((ah/2)-(h/2)));
	}
	win.focus();
}

function openPicture() {		// parameter.reihenfolge: URL, WIDTH, HEIGHT
	var w,h,url,aw,ah;
	var a=openPicture.arguments;
	if (a.length==0) return;
	url=a[0];
	if (a.length>1) {
		w=a[1]; h=a[2];
	}
	else {
		w=500; h=400
	}
	win_pic=window.open(url,'win_pic','toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,width='+w+',height='+h);
	if (screen) {
		aw=screen.availWidth;
		ah=screen.availHeight;
		win_pic.moveTo(((aw/2)-(w/2)),((ah/2)-(h/2)));
	}
	win_pic.focus();
}
// Flash-Detection
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion() {
	var version, axo, e;
	try {
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {}

	if (!version){
		try {
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			version = "WIN 6,0,21,0";
			axo.AllowScriptAccess = "always";
			version = axo.GetVariable("$version");

		} catch (e) {	}
	}
	if (!version) {
		try {
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {}
	}
	if (!version) {
		try {
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) { }
	}
	if (!version) {
		try {
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	if (version && version!=-1) {
		if( /([^ ]*) ([0-9]*),(.*)/.exec(version) ) {
			version=parseInt(RegExp.$2);
		}
	}	
	return version;
}
function GetSwfVer(){
	var flashVer = -1;	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var descArray = navigator.plugins["Shockwave Flash" + swVer2].description.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var flashVer = tempArrayMajor[0];
		}
	}
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

/// ADB-Navigation
var adb_nav_activ_id;
function showADBNav( ul_id ) {
	if (adb_nav_activ_id && adb_nav_activ_id != ul_id) {
		document.getElementById(adb_nav_activ_id).style.display='none';
		adb_nav_activ_id=false;
	}
	if (ul_id && ul_id != adb_nav_activ_id) {
		document.getElementById( ul_id ).style.display='block';
		adb_nav_activ_id = ul_id;
	}
}

/// Galery
function changeGalleryPic(l,g,url) {
	if (typeof old_g_link == "undefined") old_g_link="g_"+g+"_0";
	if (old_g_link==l.id) return true;
	document.getElementById(old_g_link).className="gal";
	l.className="gal_sel";
	old_g_link=l.id;	
	document.getElementById("gallery_"+g).src=url;
} 


/// AJAX
var http_request = false;
var reload_url = location.href;

function BrowserIsCompatible() {
	if (!window.RegExp) return false;
	var AGENTS = ["opera","msie","safari","firefox","netscape","mozilla"];
	var agent = navigator.userAgent.toLowerCase();
	for (var i = 0; i < AGENTS.length; i++) {
		var agentStr = AGENTS[i];
		if (agent.indexOf(agentStr) != -1) {
			var versionExpr = new RegExp(agentStr + "[ \/]?([0-9]+(\.[0-9]+)?)");
			var version = 0;
			if (versionExpr.exec(agent) != null) {
				version = parseFloat(RegExp.$1);
			}
			if (agentStr == "opera") return version >= 9;

			if (agentStr == "safari") return version >= 125;
			if (agentStr == "msie") return (version >= 5.5 &&agent.indexOf("powerpc") == -1);
			if (agentStr == "netscape") return version > 7;
		}
	}
	return document.getElementById;
}
function requestObject(){
	try{
		if(typeof ActiveXObject!="undefined"){
			return new ActiveXObject("Microsoft.XMLHTTP")
		}
		else if (window.XMLHttpRequest){
			var out=new XMLHttpRequest();
			out.overrideMimeType('text/xml');
			return out;
		}
	}
	catch(a){ }return null
}
function makeGetRequest(url) {
	http_request = requestObject();
	http_request.onreadystatechange = alertContents;
	http_request.open('GET', url, true);
	http_request.send(null);
}
function alertContents() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var alert_box=false;
			try {
				if (http_request.responseText.indexOf("id='alert_box'") != -1) {
					var rt=http_request.responseText;
					var p1=rt.indexOf('>', rt.indexOf("id='alert_box'"));
					var p2=rt.indexOf('</div>');
					var t=rt.substring(p1,p2)
					alert(t.replace("<([^<>\s]*)(\s[^<>]*)?>"," "));
					
				}
				//debug(http_request.responseText);
			}
			catch(e) {
				alert("fehler: "+e);
			}
			
			if (alert_box) {
				debug(alert_box);
			}
			location.href = reload_url;
			//document.getElementById('container').innerHTML = http_request.responseText;
		}
		else if (http_request.status == 0) {
			// IE: abfangen
		}
		else {
			alert('Anforderung konnte nicht verarbeitet werden, HTTP-Fehler '+http_request.status);
		}
	}
}

var max_trace_depth=1;

function debug(msg) {
	if (debug.arguments.length==2) {
		msg="<textarea rows=10 cols=20 style='width:600px;height:360px'>"+msg.escapeHTML()+"</textarea>";
	}
	try {
		//throw new Exception();
		if (typeof w == "undefined" || w.closed) {
			w=window.open('','w','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=640,height=400');
			w.moveTo(screen.availWidth-640, 0);
		}
		w.document.write(msg+"<br>");
	}
	catch (e) {
		try{ $('debug_container').innerHTML += msg+"<br>"; }
		catch(e) {
			var div=document.createElement('div');
			div.id='debug_container';
			div.innerHTML=msg+'<br />';
			document.body.appendChild(div);
		}
	}
}

function trace(o) {
	var out="";
	var nofunctions = (trace.arguments.length>1 && trace.arguments[1]);
	var do_return  = (trace.arguments.length>2 && trace.arguments[2]);
	
	try {
		for (z in o) {
			try {
				if (o[z]!="" && o[z]!=null)
					if (z=="innerHTML" || z=="outerHTML") out+=z+" = [..HTML-Code..]; <br>\n";
					if (typeof o[z] == "function" && nofunctions) {
						//out += z+": [..Function..]<br>\n";
						continue;
					}
					if (typeof o[z] == "object") {
						out += z+" : {<div style='margin-left: 20px'>";
						if (++tracedepth>max_trace_depth || z.indexOf('parent')!=-1 || z.indexOf('own')!=-1) out += " [ object ] ";
						else out += trace(o[z], nofunctions, true);
						tracedepth--;
						out += "</div>}<br>";
					}
					else out+=z+" = "+o[z]+"; <br>";
			}
			catch(e) {
				out+="<i>Fehler in "+z+": "+e+"</i><br />\n";
			}
		}
	}
	catch(ee) {
		out+="<b>Fatal Error in tracing: "+ee+"</b>";
	}
	if (do_return) return out;
	else debug(out)
}

///////////////////////////////////////
///////////// Galerien ///////////////

function getBrowser() {
	if (!window.RegExp) return false;
	var ret={ name:'', version: 0 };
	var AGENTS = ["opera","msie","safari","firefox","netscape","mozilla"];
	var agent = navigator.userAgent.toLowerCase();
	for (var i = 0; i < AGENTS.length; i++) {
		var agentStr = AGENTS[i];
		if (agent.indexOf(agentStr) != -1) {
			var versionExpr = new RegExp(agentStr + "[ \/]?([0-9]+(\.[0-9]+)?)");
			var version = 0;
			if (versionExpr.exec(agent) != null) {
				ret.version = parseFloat(RegExp.$1);
				ret.name=agentStr;
				return ret;
			}
		}
	}
	return ret;
}

var Blender=Class.create();

Blender.prototype = {
	USE_SAFARI_HACK: (getBrowser().name=='safari' && getBrowser().version<500) ,
	initialize: function (pics, el_top, el_bottom) {
		//debug(navigator.userAgent, true);
		//trace(getBrowser());
		this.pictures=pics.clone();
		this.layer=[el_bottom, el_top];
		this.next_layer=1;
		this.cur_img = new Image();
		this.first_execution=true;
		this.cur_pic_index=-1;
		
		this.autoplay=true;
		
		this.pics_loaded=0;
		
		this.cur_target='';
		delay=5000; // Wartezeit zwischen den Bildern
		this.fading=false;
		
		this.trans_paras={
			duration: 1, 
			afterFinish: this.preloadNextImage.bind(this),
			beforeSetup: this.setImage.bind(this)
		};
		this.preloadNextImage();
	},
	newPictureList:function(pics) {
		this.pictures=pics.clone();
	},
	setImage: function(a) {
		$(this.cur_target).src=this.next_img.src;
		this.cur_img.src = this.next_img.src;
	},
	queue: function() {
		if (this.first_execution) {
			this.first_execution=false;
			this.fadeIn();
		}
		else {
			clearTimeout(this.tid);
			if (this.autoplay) {
				this.tid=setTimeout(this.fadeIn.bind(this), delay);
			}
		}
	},
	
	fadeIn: function() {
		this.cur_target = this.layer[this.next_layer];
		var top = this.layer[1];
		
		if (this.next_layer==1) {
			var paras=Object.clone(this.trans_paras);
			paras.from=0.001;
			paras.to=1;
			this.next_layer=0;
		}
		else {
			var paras=Object.clone(this.trans_paras);
			paras.from=1;
			paras.to=0.001;
			this.next_layer=1;
		}
		
		new Effect.Fade(top, paras);
		this.fading=true;
	},
	preloadNextImage: function(a) {
		this.fading=false;
		
		this.cur_pic_index = this.cur_pic_index+1 >= this.pictures.length ? 0 : this.cur_pic_index+1;
		
		this.next_img = new Image();
		if (this.USE_SAFARI_HACK) {
			this._tid_counter=0;
			this._tid_counter_2=0;
			this._tid2=setInterval(function(obj){if(obj.next_img.complete || ++obj._tid_counter_2>8){ clearInterval(obj._tid2); obj.queue();  } }, 500, this);
		}
		else {
			Element.observe(this.next_img,'load', this.queue.bind(this));
			Element.observe(this.next_img,'error', this.queue.bind(this));
		}
		this.next_img.src = this.pictures[ this.cur_pic_index ];
	}
}

function initGalleries() {
	var galls = $$(".c_pic_random");
	if (galls.length==0) return;
	galls.each(function(g){
		var blender = Try.these(function(){
			return new Blender( $w(g.down('.picture_array').innerHTML), g.down(".img_oben"), g.down(".img_unten"));
		}, function(){ return false; });
		
		if (!blender) { 
			return;
		}
	});
}
Event.observe(window, "load", initGalleries);

/////////////////////////////
/// Checkbox-Magic

function doCBSwitch(el_id) {
	if ($("cb_block_"+el_id).visible()) {
		$("cb_block_"+el_id).hide();
		$("cb_switch_"+el_id).update(" + "+$("cb_switch_"+el_id).innerHTML.replace(/^[\W]+/,''));
	}
	else {
		$("cb_block_"+el_id).show();
		$("cb_switch_"+el_id).update(" &ndash; "+$("cb_switch_"+el_id).innerHTML.replace(/^[\W]+/,''));
	}
}

// wird von Ajax-JSON Antwort gefüllt
checkBox_Add={};

cb_inputTPL = new Template('<div><input class="check" type="checkbox" id="EL_#{cb_id}_#{index}" name="EL_#{cb_id}[]" value="#{index}" checked="checked" />&nbsp;<label for="EL_#{cb_id}_#{index}">#{label}</label></div>');

function addCBOption(cb_id) {
	var other_value=$("cb_add_"+cb_id).getValue().strip();
	if (other_value.length < 3) return;

	// other options?
	var exists=false;
	$$("#cb_block_"+cb_id+" input[type=checkbox]").each( function(cb_element){
		if (exists!=false) return;
		var cbVal=cb_element.next("label").innerHTML.toLowerCase();
		if(cbVal.strip() == other_value.toLowerCase()) {
			exists=cb_element;
			if (!exists.checked) exists.checked=true;
		}
	});
	if (exists != false) return;
	
	var form_values=$("cb_add_"+cb_id).up("form").serialize(true);
	var request_vars={
		node_id: form_values.source_node_id,
		lang_id: form_values.lang_id,
		element_id: cb_id,
		cmd: "elemental",
		subcmd: "cb_add_option",
		fieldname: other_value
	}
	var base_url = document.URL.replace(/(.*\/index.php(5?))(.*)/, "$1");
	var label = $("cb_other_add_"+cb_id).down("label");
	label.setStyle({backgroundPosition: "40px 0px"});
	new Ajax.Request(base_url, {
		method: "post",
		parameters: request_vars,
		onException: function(instance, e) {
			debug("Exception: "+e);
			label.setStyle({backgroundPosition: "-40px 0px"});
		},
		onSuccess: function (data) {
			eval(data.responseText);
			var tpl_data={cb_id: cb_id, index: checkBox_Add.ncb_id, label: checkBox_Add.label};
			new Insertion.Before("cb_other_add_"+cb_id, cb_inputTPL.evaluate( tpl_data ));
			$("cb_add_"+cb_id).value="";
			label.setStyle({backgroundPosition: "-40px 0px"});
		}
	});
}
function cbAddEvent(ev) {
	if (ev.keyCode==Event.KEY_RETURN) {
		Event.stop(ev);
		/*if (Prototype.Browser.Opera) {
			ev.target.form.onsubmit=function(evn){
				evn.target.onsubmit=function(e){	return true	};
				return false;
			};
		}*/
		var cb_id=Event.element(ev).id;
		addCBOption(cb_id.substr(cb_id.lastIndexOf('_')+1));
	}
}

