if ((!window.console || !window.console.log)) {
	window.console = window.console || {};
	if (window.opera && window.opera.postError) {
		window.console.log = function() {
			window.opera.postError( $A(arguments).join("\n") );
		};
	} else {
		window.console.log = function() {};
	}
}

if (Prototype.Browser.Gecko) {
	Element.addMethods( {setOpacity: function(element, value) {
	    element = $(element);
	    element.style.opacity = (value === '') ? '' : (value < 0.00001) ? 0 : value;
	    return element;
	  }
	});
}



Number.prototype.parseColor = function() {
	return (arguments[0] || this);
};


var Cookie = {

	options: {
		domain: false,
		path: false,
		duration: false,
		secure: false
	},

	/*
	Property: set
		Sets a cookie in the browser.

	Arguments:
		key - the key (name) for the cookie
		value - the value to set, cannot contain semicolons
		options - an object representing the Cookie options. See Options below. Default values are stored in Cookie.options.

	Options:
		domain - the domain the Cookie belongs to. If you want to share the cookie with pages located on a different domain, you have to set this value. Defaults to the current domain.
		path - the path the Cookie belongs to. If you want to share the cookie with pages located in a different path, you have to set this value, for example to "/" to share the cookie with all pages on the domain. Defaults to the current path.
		duration - the duration of the Cookie before it expires, in days.
					If set to false or 0, the cookie will be a session cookie that expires when the browser is closed. This is default.
		secure - Stored cookie information can be accessed only from a secure environment.

	Returns:
		An object with the options, the key and the value. You can give it as first parameter to Cookie.remove.

	Example:
		>Cookie.set('username', 'Harald'); // session cookie (duration is false), or ...
		>Cookie.set('username', 'JackBauer', {duration: 1}); // save this for 1 day

	*/

	set: function(key, value, options){
		options = {
			domain: options&&options.domain || this.options.domain,
			path: options&&options.path || this.options.path,
			duration: options&&options.duration || this.options.duration,
			secure: options&&options.secure || this.options.secure
		};
		value = encodeURIComponent(value);
		if (options.domain) value += '; domain=' + options.domain;
		if (options.path) value += '; path=' + options.path;
		if (options.duration){
			var date = new Date();
			date.setTime(date.getTime() + options.duration * 24 * 60 * 60 * 1000);
			value += '; expires=' + date.toGMTString();
		}
		if (options.secure) value += '; secure';
		document.cookie = key + '=' + value;
		return true;
	},

	/*
	Property: get
		Gets the value of a cookie.

	Arguments:
		key - the name of the cookie you wish to retrieve.

	Returns:
		The cookie string value, or false if not found.

	Example:
		>Cookie.get("username") //returns JackBauer
	*/

	get: function(key){
		var value = document.cookie.match('(?:^|;)\\s*' + RegExp.escape(key) + '=([^;]*)');
		return value ? decodeURIComponent(value[1]) : false;
	}

};

// re-execute dom:loaded functions when back button is used
window.onunload = function(){};

var normalColor, hoverColor, hoverDuration, fadeDuration, bgDuration, imageDuration, subnavDuration, projectHoverDuration;
	
document.observe('dom:loaded', function() {
	var body = $(document.body);
	
	var fade = false; // seite nicht überfaden
	fade = typeof noFade == "undefined" || !noFade ? $("fadeContent") : false; // nur content bereich faden
	//fade = typeof noFade == "undefined" || !noFade ? body : false; // gesamte Seite faden
	
	var fadeBg = true;
	
	// Dauer der Übergänge
	imageDuration = .5;
	hoverDuration = .2;
	fadeDuration = 1.0;
	bgDuration = 1.0;
	subnavDuration = 0.5;
	projectHoverDuration = .2;

	if (fade) {
		fade.setStyle( {opacity: 0.0} );
		new Effect.Morph( fade, {
			style: {opacity: 1.0},
			duration: fadeDuration 
		} );
	}
	
	// sichtbare Unternavigation merken
	if (fadeBg && fade!= body) {
		var bg = Cookie.get('lastbg');
		
		var newBg = body.getStyle('backgroundColor');
		Cookie.set('lastbg', newBg, {path: '/', duration: 1});
		
		if (bg) {
			body.setStyle( { backgroundColor: bg} );

			new Effect.Morph( body, {
				style: { backgroundColor: newBg},
				duration: bgDuration
			} );
		}
	}
	
	normalColor = $('logo').getStyle('color');
	hoverColor = '#000000';
	var nav1 = $('nav1');
	if (nav1) {
		var tmp = nav1.getElementsBySelector('a.active');
		if (tmp[0]) {
			hoverColor = tmp[0].getStyle('color');
		}
	} else {
		return;
	}
	
	// Project scrolling
	var prev = $('prev_project');
	var next = $('next_project');
	if (prev) {
		var content = $('pages');
		var pages = content.select('.projectpage');
		content.scrollTop = 0;
		var page = 1;
		content.queue = Effect.Queues.get('projectprevnext');
		var sub = Math.max(0, Math.round(content.offsetHeight / content.down().offsetHeight)-1);
		
		var prevPage = function(event) {
			event.stop();
			if (page <= 1) {
				return;
			}
			content.queue.each(function(e) { e.cancel() });
			--page;
			
			new Effect.Tween(content, content.scrollTop, (page-1)*content.down().offsetHeight, {queue: {position: 'end', scope: content.queue}}, 'scrollTop');
		};

		var nextPage = function(event) {
			event.stop();
			if (page >= pages.length-sub) {
				return;
			}
			content.queue.each(function(e) { e.cancel() });
			++page;
			
			new Effect.Tween(content, content.scrollTop, (page-1)*content.down().offsetHeight, {queue: {position: 'end', scope: content.queue}}, 'scrollTop');
		};
		
		prev.observe('click', prevPage);
		next.observe('click', nextPage);
		
		var scrollPage = function(event) {
			var delta = (-event.wheelDelta || event.detail) <0 ? -1:1;
			event.stop();
			if (delta > 0) {
				nextPage(event);
			} else {
				prevPage(event);
			}
		};
		
		content.observe('DOMMouseScroll', scrollPage);
		content.observe('mousewheel', scrollPage);
	}
	
	var elements = $A(document.getElementsByTagName("a"));
	
	// FadeIn Links und LinkBorder bei Projekten
	elements.each( function(el) {
		if (!el.effectQueue) {
			var uniqueQueueName = (el.id ? el.id : Math.round(1000000000 * Math.random()));
			el.effectQueue = Effect.Queues.get('link_'+uniqueQueueName);
		}
		
		el = $(el);
		
		if (!el || !el.firstDescendant || (el.descendantOf(nav1) && !el.up(1).hasClassName('nav2'))) {
			return;
		}
		
		// projektbilder bekommen Rahmen
		var project = el.firstDescendant();
		project = project && project.hasClassName && project.hasClassName("projektbild") && project.tagName == "SPAN" ? project : null;
		
		if (project) {
			project.setStyle( { opacity: 0.0} );
		}
		
		if (!el.hasClassName('active')) {
			el.setStyle( { color: normalColor} );
		} else {
			el.setStyle( { color: hoverColor} );
		}

		xb.addEvent( el, 'mouseenter', function() {
			if (el.hiding) {
				return;
			}
			
			queue = el.effectQueue;
			queue.each(function(e) { e.cancel() });
			
			var effects = [];
			
			if (!el.hasClassName("active")) {
				effects.push( new Effect.Morph( el, { sync: true, style: { color: hoverColor } } ) );
			}
			
			if (project) {
				effects.push( new Effect.Morph( project, { sync: true, style: { opacity: 0.5 } } ) );
			}
			
			new Effect.Parallel( effects, {
				queue: {position: 'end', scope: queue},
				duration: projectHoverDuration
			} );
		}, false);

		xb.addEvent( el, 'mouseleave', function(ev) {
			ev = Event.extend(ev);
			if (el.parentNode.parentNode == nav1 && ev.relatedTarget) {
				var e = ev.relatedTarget;
				while (e) {
					if (e == el.parentNode) {
						return;
					}
					e = e.parentNode;
				}
			}
			queue = el.effectQueue;
			queue.each(function(e) { e.cancel() });
			
			var effects = [];
			
			if (!el.hasClassName("active")) {
				effects.push( new Effect.Morph( el, { sync: true, style: { color: normalColor } } ) );
			}
			
			if (project) {
				effects.push( new Effect.Morph( project, { sync: true, style: { opacity: 0.0 } } ) );
			}
			
			new Effect.Parallel( effects, {
				queue: {position: 'end', scope: queue},
				duration: projectHoverDuration
			} );
		}, false);
		
		if (fade) {
			el.observe( 'click', function(ev) {
				if (el.hasAttribute('onclick') || el.getAttribute('href').match(/^https?:\/\//)) {
					return;
				}
				fade.setStyle( {opacity: 1.0} );
				new Effect.Morph( fade, {
					style: {opacity: 0.0},
					duration: fadeDuration/2,
					afterFinish: function() {
						Cookie.set('lastbg', body.getStyle('backgroundColor'), {path: '/', duration: 1});
						location = el.href;
					}
				} );
				ev.stop();
			});
		}
	});
	
	var activeNav = null;
	var curNav = null;
	
	var navQueue = Effect.Queues.get('Navigation');
	
	var delay = null;
	
	if (nav1) {
		nav1.select('ul').each( function(ul) {
			ul.observe('mouseover', function() {
				window.clearTimeout(delay);
			});
		});
	}
	
	var navs = [];
	
	// FadeIn Subnavigation
	if (nav1) {
		elements = nav1.childElements();
		elements.each( function(el) {
			// get ul
			var ul = el.childElements();
			if (ul.length < 2) {
				return;
			}
			var a = ul[0];
			ul = ul[1];
			navs.push(ul);
			
			ul.show = function() {
				if (curNav == ul && !navQueue.length) {
					return;
				}
				navQueue.each(function(e) { e.cancel(); });
				
				var hideEffects = [];
				navs.each(function(ul) {
					hideEffects = hideEffects.concat(ul.hideEffects());
				});
				
				// not really a hide effect ;)
				hideEffects.push( new Effect.Morph( ul.previous(), { sync: true, style: {color: hoverColor} } ) );
				
				new Effect.Parallel( hideEffects, {
					queue: {position: 'end', scope: navQueue},
					duration: hoverDuration,
					afterFinish: function() {
						curNav = ul;
						ul.setStyle( {zIndex: 3, display: 'block', opacity: 1} );
						var effects = [];
	
						ul.select('a').each(function(a) {
							effects.push( new Effect.Morph( a, { sync: true, style: {color: a.hasClassName('active')?hoverColor:normalColor}, beforeStart: function() {
								a.setStyle( {color: body.getStyle('backgroundColor')});
								a.hiding = false;
							} } ) );
						});
						
						navs.each(function(nav) {
							if (nav != ul) {
								nav.setStyle({display: "none", zIndex: 2});
							}
						});
						
						new Effect.Parallel( effects, {
							queue: {position: 'end', scope: navQueue},
							duration: hoverDuration
						});
					}
				} );
			};
			
			ul.hide = function() {
				if (ul != activeNav && activeNav) {
					activeNav.show();
					return;
				}
				navQueue.each(function(e) { e.cancel(); });
				
				var hideEffects = [];
				navs.each(function(ul) {
					hideEffects = hideEffects.concat(ul.hideEffects());
				});
				
				new Effect.Parallel( hideEffects, {
					queue: {position: 'end', scope: navQueue},
					duration: hoverDuration,
					afterFinish: function() {
						ul.setStyle( {zIndex: 2, display: 'none'} );
						if (curNav == ul) {
							curNav = null;
						}
					}
				} );
			};
			
			ul.hideEffects = function() {
				if (ul.getStyle('display') == 'none' || ul.getStyle('opacity') == 0.0) {
					return [];
				}
				
				var hideEffects = [];
				var bgColor = body.getStyle('backgroundColor');
				ul.select('a').each(function(a) {
					if (a.getStyle('color') != bgColor) {
						hideEffects.push( new Effect.Morph( a, { sync: true, style: {color: bgColor}, beforeStart: function() {
							a.hiding = true;
						} } ) );
					}
				});
				
				hideEffects.push( new Effect.Morph( a, { sync: true, style: { color: normalColor} } ) );
				return hideEffects;
			};
			
			if (!el.hasClassName('active')) {
				ul.setStyle({display: 'none', opacity: 0});
			} else {
				curNav = activeNav = ul;
				return;
			}
			
			xb.addEvent(a, 'mouseenter', function() {
				window.clearTimeout(delay);
				delay = ul.show.delay(subnavDuration);
			});
			
			xb.addEvent(el, 'mouseleave', function() {
				window.clearTimeout(delay);
				delay = ul.hide.delay(subnavDuration);
			});
		});
	}
});
