window.gorilla = (function(w,d){
	function getId(id) {
		return d.getElementById(id);
	};

	function getElementsByClassName(className, tag) {
		if (this.getElementsByClassName) {
			return Array.prototype.slice.call(this.getElementsByClassName(className));
		}
		if (!tag)
			tag = '*';
		var results = [];
		var elements = this.getElementsByTagName(tag);
		className = new RegExp('(?:^|\\s)'+className+'(?:\\s|$)');
		for (var i = 0; i < elements.length; i++) {
			if (className.test(elements[i].className)) {
				results.push(elements[i]);
			}
		}
		return results;
	};

	var slideshows = {};

	function slideshow(id) {
		this.id = id;
		if (slideshows[id]) {
			slideshows[id].terminate();
		}
		slideshows[id] = this;
		this.setup();
	};

	function slideshowitem(parent, slideshow, index) {
		this.parentElm = parent;
		this.slideshow = slideshow;
		this.index = index;
		this.setup();
	};

	slideshowitem.prototype = {
		thumbfx: null,
		parentElm: null,
		thumbElm: null,
		slideElm: null,
		colorElm: null,
		monochromeElm: null,
		finishFunc: null,
		outTimeout: 0,
		showing: false,
		allVisible: false,
		slideshow: null,
		index: 0,
		setup: function() {
			function calcColor(x) {
				var start = {r: 153, g: 153, b: 153};
				var end = {r: 89, g: 186, b: 0};
				var r = {};
				for (var i in start) {
					r[i] = Math.round((start[i]-end[i])*x+end[i]);
				}
				return 'rgb('+r.r+','+r.g+','+r.b+')';
			};
			var me = this;
			me.thumbElm = getElementsByClassName.call(me.parentElm, 'thumb', 'div')[0];
			me.thumbElm.onmouseover = function() {
				clearTimeout(me.outTimeout);
				if (!me.showing)
					me.showhalf();
				me.showing = true;
			};
			me.thumbElm.onmouseout = function() {
				me.outTimeout = setTimeout(function() {
					me.hidehalf();
					me.showing = false;
				}, 10);
			};
			me.thumbElm.onclick = function(event) {
				me.slideshow.select(me.index);
			};
			me.slideElm = getElementsByClassName.call(me.parentElm, 'slide', 'div')[0];
			var cover = getElementsByClassName.call(me.slideElm, 'cover', 'div')[0];
			if (cover && cover.previousSibling.tagName == 'A') {
				cover.style.cursor = 'pointer';
				cover.onclick = function(event) {
					var a = cover.previousSibling;
					if (a.href != '') {
						if (a.target == '_blank')
							w.open(a.href);
						else
							w.location.href = a.href;
					}
				};
			}
			me.colorElm = me.thumbElm.getElementsByTagName('em')[0];
			me.monochromeElm = getElementsByClassName.call(me.thumbElm, 'monochrome', 'div')[0];
			me.thumbfx = new secoya.fx({
				from: 0,
				to: 1,
				duration: 0.5,
				type: secoya.fx.power,
				callback: function(x) {
					me.thumbElm.style.left = x*77 + 'px';
					lightCore.setOpacity(me.monochromeElm, x*100);
					var color = calcColor(x);
					this.value = x;
					if (me.colorElm) {
						me.colorElm.style.color = color;
						if (!w.core && w.Cufon)
							Cufon.replace(me.colorElm, {fontFamily: 'ApexNewHeavy', color: color});
					}
				},
				finish: function() {
					me.hiding = false;
					me.showing = false;
					if (me.finishFunc) {
						me.finishFunc();
						me.finishFunc = null;
					}
				}
			});
		},
		runthumb: function(from, to) {
			this.thumbfx.kill();
			if (isNumber(this.thumbfx.value))
				from = this.thumbfx.value;
			this.thumbfx.from = from;
			this.thumbfx.to = to;
			this.thumbfx.start();
		},
		show: function() {
			var me = this;
			if (!me.allVisible) {
				me.allVisible = true;
				me.runthumb(1, 0);
				(new secoya.fx({
					from: 0,
					to: 100,
					duration: 0.5,
					callback: function(x) {
						lightCore.setOpacity(me.slideElm, x);
					}
				})).start();
				me.slideElm.style.zIndex = 3;
			}
		},
		hide: function() {
			var me = this;
			me.allVisible = false;
			me.runthumb(0, 1);
			me.slideElm.style.zIndex = 2;
		},
		showhalf: function() {
			if (!this.allVisible)
				this.runthumb(1, 0.5);
		},
		hidehalf: function() {
			if (!this.allVisible)
				this.runthumb(0.5, 1);
		}
	};

	slideshow.prototype = {
		items: [],
		index: 0,
		id: null,
		thumbCover: null,
		fadefx: null,
		running: !w.core,
		autoRunTimeout: 0,
		setup: function() {
			var top = getId(this.id), me = this;
			if (top) {
				if (!w.core) {
					top.onmouseover = function() {
						me.stop();
					};
					top.onmouseout = function() {
						me.run();
					};
				}
				this.thumbCover = document.createElement('div');
				this.thumbCover.className = 'thumbCover';
				top.appendChild(this.thumbCover);
				var items = getElementsByClassName.call(top, 'item', 'div');
				for (var i = 0; i < items.length; i++) {
					var item = new slideshowitem(items[i], this, i);
					this.items.push(item);
					if (i)
						item.hide();
					else
						item.show();
				}
				if (this.running)
					this.run();
			}
		},
		select: function(index) {
			if (index != this.index) {
				for (var i = 0; i < this.items.length; i++)
					this.items[i].slideElm.style.zIndex = 1;
				this.items[this.index].hide();
				this.index = index;
				this.items[index].show();
			}
		},
		terminate: function() {
			this.stop();
			this.items = [];
			if (this.thumbCover && this.thumbCover.parentNode)
				this.thumbCover.parentNode.removeChild(this.thumbCover);
			slideshows[this.id] = null;
		},
		run: function() {
			var me = this;
			this.autoRunTimeout = setInterval(function(){
				var index = me.index;
				index++;
				if (index >= me.items.length)
					index = 0;
				me.select(index);
			}, 10000);
		},
		stop: function () {
			clearInterval(this.autoRunTimeout);
		}
	};

	return {
		video: (function() {
			var videoIndex = 0;
			function tag() {
				return secoya.dom.createElement.apply(secoya.dom, arguments);
			};
			function createControls(objectTag) {
				var parent = objectTag.parentNode;
				var domBuffer, domPosition, domProgress, domControls;
				var playing = false, fullscreen = false, buffering = false, playIntervalId;
				function stopTracking() {
					playing = false;
				};
				function startTracking() {
					playing = true;
					clearInterval(playIntervalId);
					playIntervalId = setInterval(function(){
						var duration = objectTag.getDuration();
						var time = objectTag.getCurrentTime();
						var x = time/duration;
						x -= x*(5/domProgress.offsetWidth);
						domPosition.style.width = x*100+'%';
						if (!playing)
							clearInterval(playIntervalId);
					},500);
				};
				function getFullscreenOffset() {
					var p = parent;
					var top = 0, left = 0;
					while (p && p != d.body) {
						top += p.offsetTop;
						left += p.offsetLeft;
						p = p.offsetParent;
					}
					var scroll = d.documentElement.scrollTop;
					if (!scroll)
						scroll = d.body.scrollTop;
					if (!scroll)
						scroll = 0;
					scroll += 20;
					top -= scroll;
					left -= (d.body.offsetWidth-800)/2;
					return {top: top, left: left};
				};
				var originalWidth, originalHeight, offset, aspect;
				function toggleFullscreen() {
					fullscreen = !fullscreen;
					var fxCallback = function(x) {
						parent.style.left = -offset.left*x+'px';
						parent.style.top = -offset.top*x+'px';
						var w = x*(800-originalWidth)+originalWidth;
						objectTag.style.width = parent.style.width = w+'px';
						objectTag.style.height = parent.style.height = w*aspect+'px';
					};
					if (fullscreen) {
						parent.style.zIndex = 22;
						originalWidth = objectTag.offsetWidth;
						originalHeight = objectTag.offsetHeight;
						aspect = originalHeight / originalWidth;
						offset = getFullscreenOffset();
						if (d.addEventListener) {
							d.addEventListener('keyup', toggleFullscreen, true);
						} else if (d.attachEvent) {
							d.attachEvent('onkeyup', toggleFullscreen);
						}
						d.body.appendChild(tag('div', {id: 'video_overlay', onclick: toggleFullscreen}));
						(new secoya.fx({
							from: 0,
							to: 1,
							duration: 0.04,
							type: secoya.fx.power,
							callback: fxCallback
						})).start();
					} else {
						if (d.removeEventListener) {
							d.removeEventListener('keyup', toggleFullscreen, true);
						} else if (d.detachEvent) {
							d.detachEvent('onkeyup', toggleFullscreen);
						}
						var e = getId('video_overlay');
						if (e)
							e.onclick = null;
						(new secoya.fx({
							from: 1,
							to: 0,
							duration: 0.04,
							type: secoya.fx.power,
							callback: fxCallback,
							finish: function() {
								if (e)
									e.parentNode.removeChild(e);
								parent.style.zIndex = 18;
							}
						})).start();
					}
				};
				var bufferInterval, bufferAnimateInterval;
				function trackBuffer() {
					buffering = true;
					clearInterval(bufferInterval);
					clearInterval(bufferAnimateInterval);
					bufferInterval = setInterval(function() {
						var
							total = objectTag.getVideoBytesTotal(),
							start = objectTag.getVideoStartBytes(),
							loaded = objectTag.getVideoBytesLoaded();
						if (total > 0) {
							domBuffer.style.left = 100*start/total+'%';
							domBuffer.style.width = 100*loaded/total+'%';
							if (loaded+start >= total) {
								clearInterval(bufferInterval);
								clearInterval(bufferAnimateInterval);
							}
						}
					}, 500);
					var position = 0;
					bufferAnimateInterval = setInterval(function(){
						position = (position - 1) % 21;
						domBuffer.style.backgroundPosition = position+'px 0';
					}, 100);
				};
				domControls = tag('div', {className: 'controls'},null,[
					tag('div', {className: 'playpause', onclick: function() {
						if (playing)
							objectTag.pauseVideo();
						else
							objectTag.playVideo();
					}}),
					domProgress = tag('div', {className: 'progress', onclick: function(event) {
						var x = event.layerX, w = this.offsetWidth;
						objectTag.seekTo(x/w * objectTag.getDuration(), true);
					}}, null, [
						domBuffer = tag('div', {className: 'buffer'}),
						domPosition = tag('div', {className: 'position'}),
						tag('div', {className: 'overlay'}),
						tag('div', {className: 'overlayEnd'})
					]),
					tag('div', {className: 'fullscreen', onclick: toggleFullscreen})
				]);
				parent.parentNode.appendChild(tag('div', {className: 'object_placeholder', style: {width: parent.offsetWidth+'px', height: parent.offsetHeight+'px'}}));
				parent.appendChild(domControls);
				try {
					objectTag.addEventListener('onStateChange', 'window.gorilla.video['+videoIndex+']');
				} catch (e) {
					//console.log(objectTag);
				};
				w.gorilla.video[videoIndex++] = function(state) {
					switch (state) {
						case 1: // playing
							startTracking();
							break;
						case -1: // unstarted
						case 0: // ended
						case 2: // paused
						case 5: // video cued
							stopTracking();
							break;
						case 3: // buffering
							trackBuffer();
							stopTracking();
							break;
					}
				};
			};
			secoya.video.embed.addLoadListener('*', function(objectTag, id, params){
				createControls(objectTag);
				var videoId = params.url.match(/[\?&]v=([^&]+)/);
				if (videoId)
					objectTag.cueVideoById(videoId[1]);
			}, true);
			return [];
		})(),
		slideshow: function(id) {
			new slideshow(id);
		},
		headers: function() {
			var h = [
				'#slideshow h1',
				'#slideshow h3',
				'#spots h3',
				'#splash h1',
				'#titleheader h1',
				'#text h2'
			], replace = function(all, id, tag) {
				id = getId(id);
				if (id) {
					tag = id.getElementsByTagName(tag);
					var em;
					for (var i = 0; i < tag.length; i++) {
						var elm = tag[i];
						if (elm.firstChild && elm.firstChild.tagName == 'A')
							elm = elm.firstChild;
						if (elm.childNodes.length >= 3) {
							em = d.createElement('em');
							em.appendChild(elm.replaceChild(em, elm.childNodes.item(2)));
						}
					}
				}
				return all;
			}, reg = /^#([a-z]+) ([a-z0-9]+)$/;
			for (var i = 0; i < h.length; i++) {
				h[i].replace(reg, replace);
			}
		},
		gallery: (function(){
			var elm = null;
			var fx = new secoya.fx({
				from: 0,
				to: 471,
				type: secoya.fx.power,
				duration: 0.6,
				callback: function(x) {
					elm.scrollLeft = x;
				}
			});
			function runFx(id, step) {
				if (fx.running)
					fx.resetToEnd();
				elm = getId(id);
				if (elm) {
					fx.to = (fx.from = elm.scrollLeft) + step;
					fx.start();
				}
			};
			return {
				next: function(id) {
					runFx(id, 471);
				},
				previous: function(id) {
					runFx(id, -471);
				}
			};
		})(),
		menu: function() {
			function run(li, from, to) {
				if (li.fx) {
					li.fx.kill();
					var p = parseFloat(li.style.top);
					if (!isNaN(p))
						from = p;
				}
				li.fx = new secoya.fx({
					from: from,
					to: to,
					duration: 0.1,
					type: secoya.fx.power,
					callback: function(x) {
						li.style.top = x + 'px';
					},
					finish: function() {
						li.fx = null;
					}
				});
				li.fx.start();
			};
			function over(event) {
				run(this.parentNode, 0, -9);
			};
			function out(event) {
				run(this.parentNode, -9, 0);
			};
			function setup(a) {
				if (a.addEventListener) {
					a.addEventListener('mouseover', over, false);
					a.addEventListener('mouseout', out, false);
				} else if (a.attachEvent) {
					a.attachEvent('onmouseover', function(event){
						over.call(a, event);
					});
					a.attachEvent('onmouseout', function(event){
						out.call(a, event);
					});
				} else {
					a.onmouseover = over;
					a.onmouseout = out;
				}
			};
			var h = getId('header');
			var ul = h.getElementsByTagName('ul')[0];
			if (ul) {
				ul = ul.getElementsByTagName('a');
				for (var i = 0; i < ul.length; i++) {
					if (ul[i].parentNode.className.indexOf('selected') == -1)
						setup(ul[i]);
				}
			}
		}
	};
})(window, document);
