// helper functions

	var doVideoFallback = function() {

		jQuery('video').each(function() {
			var support = false;
			jQuery(this).children('source').each(function() {
				if(support == false) {
					var type = jQuery(this).attr('type');
					try {
						support = !!document.createElement('video').canPlayType(type);
						if(support == "" || support == "no") {
							support = false;
						}
					} catch (e) {
						// Do nothing
					}
				}
			} )
			if(support == false) {
				jQuery(this).children('source').remove();
				jQuery(this).children().insertBefore(this);
				jQuery(this).remove();
			}
		});

		jQuery('audio').each(function() {
			var support = false;
			jQuery(this).children('source').each(function() {
				if(support == false) {
					var type = jQuery(this).attr('type');
					try {
						support = !!document.createElement('audio').canPlayType(type);
						if(support == "" || support == "no") {
							support = false;
						}
					} catch (e) {
						// Do nothing
					}
				}
			} )
			if(support == false) {
				jQuery(this).children('source').remove();
				jQuery(this).children().insertBefore(this);
				jQuery(this).remove();
			}
		});

	};
	
	var base64_decode = function(data) {
		var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];
		if (!data) {
			return data;
		}
		data += '';
		do {  // unpack four hexets into three octets using index points in b64
			h1 = b64.indexOf(data.charAt(i++));
			h2 = b64.indexOf(data.charAt(i++));
			h3 = b64.indexOf(data.charAt(i++));
			h4 = b64.indexOf(data.charAt(i++));
			bits = h1<<18 | h2<<12 | h3<<6 | h4;
			o1 = bits>>16 & 0xff;
			o2 = bits>>8 & 0xff;
			o3 = bits & 0xff;
			if (h3 == 64) {
				tmp_arr[ac++] = String.fromCharCode(o1);
			} else if (h4 == 64) {
				tmp_arr[ac++] = String.fromCharCode(o1, o2);
			} else {
				tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
			}
		} while (i < data.length);
		dec = tmp_arr.join('');
		return dec;
	}

	function setCookie( name, value, expires, path, domain, secure ) {
		var today = new Date();
		today.setTime(today.getTime());
		if ( expires ) {
			expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );
		document.cookie = name + "=" +escape( value ) +
			( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
			( ( path ) ? ";path=" + path : "" ) +
			( ( domain ) ? ";domain=" + domain : "" ) +
			( ( secure ) ? ";secure" : "" );
	}

	var getCookie = function(c_name) {
		if(document.cookie.length>0) {
			c_start = document.cookie.indexOf(c_name + "=");
			if(c_start!=-1) {
				c_start = c_start + c_name.length+1;
				c_end = document.cookie.indexOf(";",c_start);
				if(c_end==-1) {
					c_end = document.cookie.length;
				}
				return unescape(document.cookie.substring(c_start,c_end));
			}
		}
		return "";
	};

// global features object
var features = {
	_private: {
		items: [],
		defaultInterval: 3 /* sec */,
		autoInterval: null,
		current: null,
		previous: null,
		firstRound: false,
		z: 100,
		activateCurrent: function() {
			var item = features._private.items[features._private.current];
			$(item.goSwitch).addClass("active");
			if(features._private.previous) {
				$(features._private.previous.goSwitch).removeClass("active");
			}
			item.totalWidth = item.getWidth();
			item.totalHeight = item.getHeight();
			try {
				item.style.clip = "rect(0 0px "+this.totalHeight+"px 0)";
			} catch(e) {}
			item.setStyle("z-index",features._private.z++);
			item.setStyle("opacity",0);
			if(features._private.firstRound===true) {
				item.setStyle("opacity",1);
			}else{
				item.animate({
					duration: 0.3,
					method: "fadeout",
					morph: {
						opacity: 1,
						fn: function(i) {
							this.style.clip = "rect(0 "+(this.totalWidth*i)+"px "+this.totalHeight+"px 0)";
						}
					}
				});
			}
			var offsetTop = 70;
			$$("div#"+item.getId()+" .buildup").each(function(el){
				if(!el.totalHeight) {
					$$("div#"+el.getId()+" span").each(function(e){
						el.totalWidth = e.getWidth();
					});
					el.totalHeight = el.getHeight();
					el.setStyle("width",el.totalWidth+"px");
					el.setStyle("height",el.totalHeight+"px");
					el.setStyle("position","absolute");
					el.setStyle("float","none");
					el.setStyle("right","0px");
					el.setStyle("top",offsetTop+"px");
				}
				el.setStyle("opacity",0);
				el.setStyle("clip","rect(0 "+this.totalWidth+"px "+this.totalHeight+"px "+this.totalWidth+"px)");
				el.animate({
					duration: 0.3
				},{
					duration: 0.4,
					method: "fadeout",
					morph: {
						opacity: 1,
						fn: function(i) {
							this.style.clip = "rect(0 "+this.totalWidth+"px "+this.totalHeight+"px "+(this.totalWidth*(1-i))+"px)";
						}
					}
				});
				offsetTop+= el.totalHeight+5;
			});
			features._private.previous = item;
			features._private.firstRound = false;
		}
	},
	init: function() {
		if(!$("features")) {
			return false;
		}
		var bar = "";
		var i = -1;
		$$("div#features .item").each(function(item){
			i++;
			features._private.items.push(item);
			item.goSwitch = "features-goswitch-"+i;
			bar+= (i==0 ? "" : " &nbsp;|&nbsp; ")+
				'<a id="features-goswitch-'+i+'" href="javascript:void(features.go('+i+'))">'+
				(item.title ? item.title : 'Thema '+(i+1))+'</a>';
				item.title = "";
		});
		$("featuresbar").setHtml(
			bar+'&nbsp;'+
			'<span class="playstop"><a id="features-play" href="javascript:void(features.play())">Play</a>'+
			' | <a id="features-stop" href="javascript:void(features.stop())">Stop</a></span>'
		);
		features._private.current = 0;
		features._private.items[0].setStyle("z-index",features._private.z++);
		$("features-goswitch-0").addClass("active");
		features._private.previous = features._private.items[0];
		features._private.init = true;
		features._private.firstRound = true;
		return true;
	},
	play: function(interval /*sec*/) {
		if(features._private.autoInterval) {
			features.stop();
		}
		$("features-play").addClass("active");
		$("features-stop").removeClass("active");
		if(!interval || interval<=0) {
			interval = features._private.defaultInterval;
		}
		features._private.defaultInterval = interval;
		features._private.autoInterval = window.setInterval("features.next()",interval*1000);
		features._private.current = -1;
		features.next();
		if(features._private.items.length===1) features.stop();
		return true;
	},
	stop: function() {
		if(features._private.autoInterval) {
			$("features-play").removeClass("active");
			$("features-stop").addClass("active");
			window.clearInterval(features._private.autoInterval);
			features._private.autoInterval = null;
			return true;
		}
		return false;
	},
	next: function() {
		features._private.current++;
		if(features._private.current>features._private.items.length-1) {
			features._private.current = 0;
		}
		features._private.activateCurrent();
	},
	prev: function() {
		features._private.current--;
		if(features._private.current<0) {
			features._private.current = features._private.items.length-1;
		}
		features._private.activateCurrent();
	},
	go: function(k) {
		if(features._private.current===k) {
			return true;
		}
		if(features._private.autoInterval) {
			features.stop();
			features.play();
		}
		features._private.current = k;
		features._private.activateCurrent();
	}
};

var sidebar = {
	_private: {
		current: "o-ton"
	},
	go: function(pane) {
		if(sidebar._private.current===pane) {
			return false;
		}
		switch(pane) {
			case "o-ton":
				$("side-link-facebook").removeClass("selected");
				$("side-link-o-ton").addClass("selected");
				$("side-facebook").removeClass("selected");
				$("side-o-ton").addClass("selected");
				break;
			case "facebook":
				$("side-link-o-ton").removeClass("selected");
				$("side-link-facebook").addClass("selected");
				$("side-o-ton").removeClass("selected");
				$("side-facebook").addClass("selected");
				break;
		}
		sidebar._private.current = pane;
	}
};

var imgpostbox = {
	last: null,
	init: function() {
		imgpostbox.resize();
		if($("imgpostboxfirst")) {
			$("imgpostboxfirst").addClass("selected");
			if(
				$("imgpostboxfirst").childNodes[0]
				&& $("imgpostboxfirst").childNodes[0].childNodes[0]
				&& $("imgpostboxfirst").childNodes[0].childNodes[0].className==="movieindicator"
			) {
				imgpostbox.video($("imgpostboxfirst").href.replace(/^[^']+'([^']+).*$/,"$1"),$("imgpostboxfirst"));
			}else{
				imgpostbox.last = $("imgpostboxfirst");
			}
		}
	},
	resize: function() {
		var box = $("imgpostbox");
		if(!box) {
			return;
		}
		var img = $("imgpostboximg");
		img.setStyle("width","");
		img.setStyle("height","");
		img.width = "";
		img.height = "";
		try {
			img.removeAttribute("width");
			img.removeAttribute("height");
		}catch(e){}
		var boxwidth = box.getWidth()-2;
		var boxheight = box.getHeight()-2;
		var imgwidth = img.getWidth();
		var imgheight = img.getHeight();
		var ratio = imgwidth/imgheight;
		var width = boxwidth;
		var height = Math.ceil(boxwidth/ratio);
		if(height>boxheight) {
			height = boxheight;
			width = Math.ceil(boxheight*ratio);
		}
		img.setStyle("max-width","none");
		img.width = width;
		img.height = height;
		img.setStyle("width",width+"px");
		img.setStyle("height",height+"px");
	},
	change: function(a) {
		if(imgpostbox.last) {
			imgpostbox.last.removeClass("selected");
		}
		a.addClass("selected");
		$("imgpostboximg").setStyle("opacity",1);
		if(!Ice.isUndefined($("videopostbox")) && $("videopostbox")) {
			$("videopostbox").animate({
				duration: 0.15,
				morph: {opacity: 0}
			},{
				duration: 0,
				morph: {fn: function() {
					$("videopostbox").remove();
					$("imgpostboximg").src = a.href;
					imgpostbox.resize();
					$("imgpostboximg").animate({
						duration: 0.15,
						morph: {opacity: 1}
					});
				}}
			});
		}else{
			$("imgpostboximg").animate({
				duration: 0.15,
				morph: {opacity: 0}
			},{
				duration: 0,
				morph: {fn: function() {
					this.src = a.href;
					imgpostbox.resize();
					this.animate({
						duration: 0.15,
						morph: {opacity: 1}
					});
				}}
			});
		}
		imgpostbox.last = a;
		return false;
	},
	video: function(encoded,a) {
		if($("imgpostbox")) {
			a = $(a);
			if(imgpostbox.last) {
				imgpostbox.last.removeClass("selected");
			}
			var html = base64_decode(encoded);
			var videopostbox = $({
				tag: "div",
				id: "videopostbox"
			});
			videopostbox.addTo("postboxwrapper");
			if(!imgpostbox.last) {
				videopostbox.setHtml(html);
			}else{
				$("videopostbox").setStyle("opacity",0);
				$("imgpostboximg").animate({
					duration: 0.15,
					morph: {opacity: 0}
				},{
					duration: 0,
					morph: {fn: function() {
						videopostbox.setHtml(html);
						$("videopostbox").animate({
							duration: 0.15,
							morph: {opacity: 1}
						},{
							duration: 0,
							morph: {fn: function() {
								$$("#videopostbox video").each(function(video) {
									if(video.play) {
										video.play();
									}
								});
							}}
						});
					}}
				});
			}
			doVideoFallback();
			if(imgpostbox.last) {
				a.addClass("selected");
			}
			imgpostbox.last = a;
		}
		return false;
	}
};

var results = {
	filter: function(type,url) {
		switch(type) {
			case false:
				setCookie("filter","",false,"/");
				break;
			case "c":
			case "s":
				setCookie("filter",type,false,"/");
				break;
			default: return false;
		}
		if(Ice.isUndefined(url)) {
			window.location.reload();
		}else if(Ice.isString(url)) {
			window.location.href = url;
		}
	},
	injectUrl: function(url) {
		if(Ice.isNode(url) && url.href) {
			url = url.href;
		}
		setCookie("filter","",false,"/");
		setCookie("area","",false,"/");
		setCookie("navInjectUrl",url,false,"/");
		return true;
	},
	useArea: function(slug) {
		setCookie("area",slug,false,"/");
	}
};

$do(function(){
	// load features items if available
	if(features.init()) {
		features.play(6);
	}
	// highlight selected menu item
	var hightlight_found = false;
	$$("div.menu a").each(function(item){
		if(item.href===window.location.href) {
			if(hightlight_found) {
				return;
			}
			hightlight_found = true;
			item.addClass("selected");
			var ai = $({tag: "div"});
			ai.setClass("activeindicator");
			ai.setStyle("left",(item.getWidth()/2-4)+"px");
			ai.setStyle("bottom","-5px");
			ai.addAfter(item);
		}
	});
	if(!hightlight_found) {
		window.injectUrl = getCookie("navInjectUrl");
		if(window.injectUrl) {
			$$("div.menu a").each(function(item){
				if(window.injectUrl===item.href) {
					if(hightlight_found) {
						return;
					}
					hightlight_found = true;
					item.addClass("selected");
					var ai = $({tag: "div"});
					ai.setClass("activeindicator");
					ai.setStyle("left",(item.getWidth()/2-4)+"px");
					ai.setStyle("bottom","-5px");
					ai.addAfter(item);
				}
			});
		}
	}
});

var doLoad = function() {
	// everything is already loaded, including images
	imgpostbox.init();
};
