var huh = (function() {
	var win = window;
	var doc = win.document;
	var loc = win.location;
	var encode = encodeURIComponent;
	var decode = decodeURIComponent;

	function create(tagname, dom, attributes) {
		return secoya.dom.createElement.apply(secoya.dom, arguments);
	};

	function getId(id) {
		return doc.getElementById(id);
	};

	(function() {
		if (typeof XMLHttpRequest === 'undefined') {
			win.XMLHttpRequest = function() {
				var t = [
					'Msxml2.XMLHTTP.6.0',
					'Msxml2.XMLHTTP.3.0',
					'Msxml2.XMLHTTP',
					'Microsoft.XMLHTTP'
				];
				var result = null;
				for (var i = 0; i < t.length && !result; i++) {
					try {
						result = new ActiveXObject(t[i]);
					} catch (e) {}
				}
				if (!result) {
					throw new Error('XMLHttpRequest not supported');
				}
				return result;
			};
		}
	})();

	function runScripts(parent) {
		if (typeof parent === 'string')
			parent = getId(parent);
		if (parent) {
			var scripts = parent.getElementsByTagName('script');
			var script;
			while (scripts.length) {
				script = scripts[0];
				if (!script.getAttribute('src')) {
					try {
						eval(script.innerHTML);
					} catch (e) {}
				}
				if (script.parentNode) {
					script.parentNode.removeChild(script);
				}
			}
		}
	};

	function Ajax(url, type, callback) {
		var request = new XMLHttpRequest();
		request.open(type, url, true);
		request.onreadystatechange = function(event) {
			if (request.readyState == 4)
				callback.call(this, request.responseText);
		};

		this.send = function(data) {
			if (typeof data === 'object') {
				var list = [];
				for (var i in data) {
					list.push(encode(i)+'='+encode(data[i]));
				}
				data = list.join('&');
			} else {
				data = null;
			}
			request.send(data);
		};

		this.abort = function() {
			request.abort();
		};
	};

	function getTitle(html) {
		return html.substring(html.indexOf('<title>')+7, html.indexOf('</title>')).decodeEntities();
	};

	function getClassName(html) {
		var startStr = '<body class="';
		var start = html.indexOf(startStr);
		var end = html.indexOf('"', start+startStr.length);
		return html.substring(start+startStr.length, end);
	};

	function getHTMLBody(html) {
		var start = html.indexOf('<body');
		start = html.indexOf('>', start);
		var end = html.indexOf('</body>');
		return html.substring(start+1, end);
	};

	function clickLink(event) {
		event = event || win.event;
		var href = this.getAttribute('href');
		var host = loc.protocol+'//'+loc.hostname;
		if (href && href.indexOf(host) == 0)
			href = href.substring(host.length);
		if (href && href.substring(0, 1) == '/') {
			huh.menu.navigate(href, true);
			if (event.preventDefault)
				event.preventDefault();
			event.cancelBubble = true;

			return false;
		}
	};

	function transformLinks(parent) {
		if (!parent)
			parent = d;
		lightCore.decodeEmails(parent);
		var links = parent.getElementsByTagName('a');
		for (var i = 0; i < links.length; i++) {
			if (!links[i].ignore) {
				if (links[i].addEventListener) {
					links[i].addEventListener('click', clickLink, true);
				} else {
					links[i].onclick = clickLink;
				}
			}
		}
	};

	return {
		initialize: function() {
			if (!core) {
				transformLinks(doc);
				for (var i in this) {
					if (this[i].initialize) {
						this[i].initialize();
					}
				}
			}
		},

		gallery: function(id) {
			function get(sub) {
				return getId(id+'_'+sub);
			};
			var
				gallery = get('gallery'),
				preview = get('preview'),
				content = get('content'),
				navigation = get('navigation'),
				image = get('image'),
				description = get('description'),
				thumbs = get('thumbs'),
				images = get('images'),
				next = get('next'),
				previous = get('previous'),
				fullscreen = get('fullscreen'),
				thumb_prev = get('thumb_prev'),
				thumb_next = get('thumb_next'),
				title = get('title'),
				date = get('date'),
				links = images.getElementsByTagName('a'),
				linkIndex = 0,
				thumbIndex = 0;

			function showImage(index) {
				if (index >= links.length) {
					index = links.length -1;
				}
				if (index < 0) {
					index = 0;
				}
				linkIndex = index;
				if (links[index]) {
					var url = links[index].getElementsByTagName('img')[0];
					if (url) {
						url = url.src.replace(/\/thumb\./, '/version1.');
						create('img', {onload: function(){
							secoya.dom.removeChildren(image);
							image.appendChild(this);
						}, src: url, alt:''});
					}
				}
			};

			function scrollThumbs(index) {
				if (index > links.length - 5) {
					index = links.length - 5;
				}
				if (index < 0) {
					index = 0;
				}
				thumbIndex = index;
				images.style.marginLeft = -index*72+'px';
			};

			function showFullscreen() {
				var
					overlay,
					container,
					image,
					indexNode, // nodeType 3
					fullLinkIndex = 0,
					fullThumbIndex = 0,
					fullLinks = [],
					parent = getId('page'),
					fullThumbs;

				function showFullImage(index) {
					if (index >= fullLinks.length)
						index = fullLinks.length - 1;
					if (index < 0)
						index = 0;
					fullLinkIndex = index;
					if (fullLinks[index]) {
						image.src = fullLinks[index].href;
					}
					indexNode.nodeValue = fullLinkIndex+1+' / '+fullLinks.length;
				};
				function scrollFullThumbs(index) {
					if (index > fullLinks.length - 10) {
						index = fullLinks.length - 10;
					}
					if (index < 0) {
						index = 0;
					}
					fullThumbIndex = index;
					fullThumbs.style.marginLeft = -index*74+'px';
				};

				overlay = create('div', {id:'fullscreen_overlay', onclick:function(){
					overlay.onclick = null;
					showImage(fullLinkIndex);
					(new secoya.fx({
						from: 100,
						to: 0,
						duration: 0.5,
						type: secoya.fx.power,
						callback: function(value) {
							lightCore.setOpacity(container, value);
						},
						finish: function() {
							parent.removeChild(overlay);
							parent.removeChild(container);
						}
					})).start();
				}});
				container = create('div', {id:'fullscreen'});
				container.appendChild(create('h4')).appendChild(date.firstChild.cloneNode(true));
				container.appendChild(create('h2')).appendChild(title.firstChild.cloneNode(true));
				image = container.appendChild(create('div', {className: 'image'}));
				image.appendChild(create('div', {className:'previous'})).appendChild(create('a', {onclick:function(){
					showFullImage(fullLinkIndex-1);
				}}));
				image.appendChild(create('div', {className:'next'})).appendChild(create('a', {onclick:function(){
					showFullImage(fullLinkIndex+1);
				}}));
				image = image.insertBefore(create('img', {src:'/image', alt:''}), image.firstChild);
				indexNode = container.appendChild(create('div', {className:'index'})).appendChild(doc.createTextNode(''));
				container.appendChild(create('div', {className:'description'})).innerHTML = description.innerHTML;
				fullThumbs = container.appendChild(create('div', {className:'thumbs'}));
				fullThumbs.appendChild(create('a', {className:'previous', href:'#', onclick:function(event){
					event = event || win.event;
					if (event.preventDefault)
						event.preventDefault();
					scrollFullThumbs(fullThumbIndex-1);
					return false;
				}}));
				fullThumbs.appendChild(create('a', {className:'next', href:'#', onclick: function(event){
					event = event || win.event;
					if (event.preventDefault)
						event.preventDefault();
					scrollFullThumbs(fullThumbIndex+1);
					return false;
				}}));
				fullThumbs = fullThumbs.appendChild(create('div', {className:'images'}));
				for (var i = 0; i < links.length; i++) {
					var url = links[i].getElementsByTagName('img')[0];
					var a;
					if (url) {
						url = url.src;
						a = fullThumbs.appendChild(create('a', {href: url.replace(/\/thumb\./, '/version0.'), imageIndex: i, onclick:function(event){
							event = event || win;
							if (event.preventDefault)
								event.preventDefault();
							showFullImage(this.imageIndex);
							return false;
						}}));
						a.appendChild(create('img', {src: url, alt:''}));
						fullLinks.push(a);
					}
				}
//				fullLinks = fullThumbs.getElementsByTagName('a');
				fullThumbs.style.width = fullLinks.length*74+'px';
				parent.appendChild(overlay);
				parent.appendChild(container);
				showFullImage(linkIndex);
				(new secoya.fx({
					from: 0,
					to: 100,
					type: secoya.fx.power,
					duration: 0.5,
					callback: function(value) {
						lightCore.setOpacity(container, value);
					},
					finish: function() {
						lightCore.clearOpacity(container);
					}
				})).start();
			};

			showImage(0);
			next.onclick = function(event){
				event = event || window.event;
				if (event.preventDefault)
					event.preventDefault();
				showImage(linkIndex+1);
				return false;
			};
			previous.onclick = function(event){
				event = event || window.event;
				if (event.preventDefault)
					event.preventDefault();
				showImage(linkIndex-1);
				return false;
			};
			fullscreen.onclick = function(event) {
				event = event || window.event;
				if (event.preventDefault)
					event.preventDefault();
				showFullscreen();
				return false;
			};
			thumb_prev.ignore = thumb_next.ignore = next.ignore = previous.ignore = fullscreen.ignore = true;
			images.style.width = links.length*72+'px';
			thumb_prev.onclick = function(event){
				event = event || win.event;
				if (event.preventDefault)
					event.preventDefault();
				scrollThumbs(thumbIndex-1);
				return false;
			};
			thumb_next.onclick = function(event){
				event = event || win.event;
				if (event.preventDefault)
					event.preventDefault();
				scrollThumbs(thumbIndex+1);
				return false;
			};
			(function(){
				var f = function(event) {
					event = event || window.event;
					showImage(this.thumbIndex);
					if (event.preventDefault)
						event.preventDefault();
					return false;
				};
				for (var i = 0; i < links.length; i++) {
					links[i].thumbIndex = i;
					links[i].onclick = f;
					links[i].ignore = true;
				}
			})();

			navigation.onclick = description.onclick = thumbs.onclick = function(event) {
				event = event || win.event;
				if (event.stopPropagation)
					event.stopPropagation();
				event.cancelBubble = true;
			};
			if (core)
				preview.onclick = thumbs.onclick;

			var contentVisible = false;

			var previewFx;
			var contentFx = new secoya.fx({
				from: 0,
				to: 0,
				duration: 0.8,
				type: secoya.fx.power,
				callback: function(value) {
					content.style.height = value+'px';
				},
				finish: function() {
					if (contentVisible) {
						preview.style.height = 'auto';
						previewFx.to = preview.clientHeight;
						previewFx.start();
					} else {
						contentVisible = !contentVisible;
						content.style.height = preview.style.height = '';
						gallery.className = contentVisible ? 'gallery visible' : 'gallery';
					}
				}
			});
			previewFx = new secoya.fx({
				from: 0,
				to: 0,
				duration: 0.8,
				type: secoya.fx.power,
				callback: function(value) {
					preview.style.height = value+'px';
				},
				finish: function() {
					if (!contentVisible) {
						content.style.height = 'auto';
						contentFx.to = content.clientHeight;
						contentFx.start();
					} else {
						contentVisible = !contentVisible;
						content.style.height = preview.style.height = '';
						gallery.className = contentVisible ? 'gallery visible' : 'gallery';
					}
				}
			});
			gallery.onclick = function() {
				if (contentVisible) {
					content.style.height = 'auto';
					contentFx.from = content.clientHeight;
					previewFx.to = preview.clientHeight;
					contentFx.to = previewFx.from = 0;
					contentFx.start();
				} else {
					preview.style.height = 'auto';
					contentFx.to = content.clientHeight;
					previewFx.from = preview.clientHeight;
					contentFx.from = previewFx.to = 0;
					previewFx.start();
				}
			};
		},

		arrangement: {
			toggle: function(elm) {
				function getDescription() {
					var div = elm.getElementsByTagName('div');
					for (var i = 0; i < div.length; i++) {
						if (div[i].className == 'description') {
							return div[i];
						}
					}
					return null;
				};
				var isVisible = elm.className.indexOf('visible') != -1;
				if (!isVisible)
					elm.className += ' visible';
				var div = getDescription();
				var fullHeight = div.clientHeight;
				var fx = new secoya.fx({
					from: isVisible ? fullHeight : 0,
					to: isVisible ? 0 : fullHeight,
					type: secoya.fx.power,
					duration: 1,
					callback: function(value) {
						div.style.height = value + 'px';
					},
					finish: function() {
						if (isVisible) { // no longer visible
							elm.className = 'arrangement';
						}
						div.style.height = '';
					}
				});
				fx.start();
			}
		},
/*
		selector: {
			add: function(elm) {
				if (typeof elm == 'string')
					elm = getId(elm);
				if (elm) {
					secoya.dom.removeChildren(elm);
					var a, i = 5, div = null;
					while (i--) {
						elm.appendChild(create('div', {onclick: function(event) {
							if (div)
								div.className = '';
							div = this;
							div.className = 'selected';
						}}));
					}
				}
			}
		},

		test: function() {
			var s = "<html>\n<head>\n<title>Min &oslash;nske titel</title></head><body class=\"hello world p_abe\"><div>Contents of body!</div></body>";
			console.log(getTitle(s));
			console.log(getClassName(s));
			console.log(getHTMLBody(s));
		},
*/
		menu: (function() {
			var
				flashObject = null,
				flashReady = true,
				contentReady = false,
				div = null,
				className = null,
				title = null,
				lastHash = '',
				ids = {'page': 1, 'splash': 1},
				ajax = null,
				topOffset = 135,
				startHeight = 115;

			function checkHash(hash) {
				if (hash != lastHash) {
					lastHash = hash;
					hash = hash.substring(1);
					if (hash == '')
						hash = loc.pathname;
					if (hash[0] == '/') {
						flashReady = true;
						huh.menu.navigate(hash, true);
					}
				}
			};

			function waitForImages(parent, callback) {
				var imgs = parent.getElementsByTagName('img');
				var loadingCount = imgs.length;
				if (loadingCount) {
					var maxWaitTimeout = setTimeout(function() {
						callback();
					}, 4000);
					function loaded() {
						loadingCount--;
						if (loadingCount <= 0) {
							clearTimeout(maxWaitTimeout);
							callback();
						}
					};
					for (var i = loadingCount-1; i >= 0; i--) {
						if (imgs[i].complete) {
							loadingCount--;
						} else {
							imgs[i].onload = imgs[i].onabort = imgs[i].onerror = loaded;
						}
					}
					if (loadingCount == 0)
						loaded();
				} else {
					callback();
				}
			};

			function animateHide(finishCallback) {
				var p = getId('page');
				var m = getId('main');
				var height = parseInt(lightCore.getStyle(m, 'height'));
				if (!height || isNaN(height))
					height = m.offsetHeight - 21; // padding-bottom: 21px
				var fxOpacity = new secoya.fx({
					from: 100,
					to: 0,
					type: secoya.fx.linear,
					duration: 0.5,
					callback: function(value){lightCore.setOpacity(p, value);},
					finish: function(){if(p.parentNode)p.parentNode.removeChild(p);if(finishCallback)finishCallback();}
				});
				var fxMargin = new secoya.fx({
					from: 0,
					to: topOffset,
					type: secoya.fx.power,
					duration: 0.5,
					callback: function(value){p.style.marginTop=value+'px';}
				});
				var fxHeight = new secoya.fx({
					from: height,
					to: startHeight,
					type: secoya.fx.power,
					duration: 0.5,
					callback: function(value){m.style.height=value+'px';},
					finish: function(){fxOpacity.start();}
				});
				var fxScroll = new secoya.fx({
					from: doc.body.scrollTop ? doc.body.scrollTop : doc.documentElement.scrollTop,
					to: 0,
					type: secoya.fx.power,
					duration: 0.5,
					callback: function(value){
						win.scrollTo(0, value);
					},
					finish: function(){
						win.scrollTo(0,0);
					}
				});
				fxScroll.start();
				fxMargin.start();
				fxHeight.start();
			};

			function animateShow(finishCallback) {
				var m = getId('main');
				var height = parseInt(lightCore.getStyle(m, 'height'));
				if (!height || isNaN(height)) {
					height = m.offsetHeight - 21; // padding-bottom: 21px
				}
				var fxHeight = new secoya.fx({
					from: startHeight,
					to: height,
					type: secoya.fx.circle,
					duration: 0.5,
					callback: function(value){m.style.height=value+'px';},
					finish: function(){m.style.height='';}
				}),
				fxMargin = new secoya.fx({
					from: topOffset,
					to: 0,
					type: secoya.fx.circle,
					duration: 0.5,
					callback: function(value){div.style.marginTop=value+'px'},
					finish: function(){div.style.marginTop='';if(finishCallback)finishCallback();}
				});

				lightCore.setOpacity(div, 0);
				div.style.left = div.style.top = '';
				m.style.height = startHeight+'px';
				div.style.marginTop = topOffset+'px';

				var foldout = function() {
					lightCore.clearOpacity(div);
					fxHeight.start();
					fxMargin.start();
				};

				(new secoya.fx({
					from: 0,
					to: 100,
					type: secoya.fx.linear,
					duration: 0.5,
					callback: function(value){lightCore.setOpacity(div, value);},
					finish: foldout
				})).start();
			};

			function sendToFlash(msg) {
				if (flashObject)
					flashObject.sendToActionScript(msg);
			};

			function checkReady(animate) {
				function getMenuFromClass(className) {
					className = className.match(/^m_([a-z]+)/);
					if (className)
						className = className[1];
					return className;
				};
				if (flashReady && contentReady) {
					doc.title = title;
					if (className) {
						doc.body.className = className;
						var flashClass = getMenuFromClass(className);
						sendToFlash('open '+flashClass);
					}
					contentReady = flashReady = false;
					if (animate)
						animateShow(function(){});
				}
			};

			return {
				initialize: function() {
					setInterval(function() {
						checkHash(loc.hash);
					}, 200);
					var s = getId('splash');
					if (!s) {
						var myLastHash = loc.hash;
						var me = this;
						this.navigate('/', false, function(){
							if (myLastHash) {
								me.navigate(myLastHash.substring(1), false);
							}
						});
						loc.hash = '0';
					}
				},
				registerFlash: function(event) {
					flashObject = event.ref;
					flashObject.onclick = function(ev) {
						ev = ev || window.event;
						if (ev.stopPropagation)
							ev.stopPropagation();
						ev.cancelBubble = true;
						return false;
					};
					var me = this;
					getId('splash').onclick = function(ev) {
						ev = ev || win.event;
						var target = ev.target;
						while (target && target.className != 'container') {
							target = target.parentNode;
						}
						if (!target) {
							if (getId('page') || core) {
								if (core)
									secoya.menu.navigate('/?show=front');
								else
									animateHide(function(){me.navigate('/', true);});
							}
						}
					};
				},
				// invoked by flash
				preload: function(url) {
					flashReady = false;
					contentReady = false;
					var me = this;
					if (ajax)
						ajax.abort();
					if (getId('page')) {
						animateHide(function(){sendToFlash('done');me.navigate(url, true);});
					} else {
						this.navigate(url, true);
					}
				},
				// invoked by flash
				flashready: function() {
					flashReady = true;
					checkReady(true);
				},
				navigate: function(url, removeContent, afterCallback) {
					var host = loc.protocol+'//'+loc.host;
					if (url.indexOf(host) == 0)
						url.substring(host.length);
					lastHash = '#'+url;
					loc.hash = url;
					url = url.split('#', 2);
					contentReady = false;
					ajax = new Ajax(url[0], 'GET', function(html) {
						title = getTitle(html),
						className = getClassName(html),
						div = create('div');

						div.innerHTML = getHTMLBody(html);
						var parent = getId('site');
						var children = div.getElementsByTagName('div');
						for (var i = 0; i < children.length; i++) {
							if (ids[children[i].id]) {
								div = children[i];
								break;
							}
						}
						var replaceMe = getId(div.id);
						if (div.id == 'splash')
							className = null;
						function setup() {
							runScripts(div);
							transformLinks(div);
//							secoya.sifr.initialize();
						};
						if (replaceMe) { // is the div already in dom ?
							parent.replaceChild(div, replaceMe);
							if (removeContent && div.id == 'splash' && document.getElementById('page')) {
								animateHide(null);
							}
							contentReady = flashReady = true;
							setup();
							checkReady(false);
						} else {
							switch (div.id) {
								case 'splash':
									parent.insertBefore(div, parent.firstChild);
									if (removeContent) {
										animateHide(null);
									}
									contentReady = flashReady = true;
									setup();
									checkReady(false);
									break;
								case 'page':
									div.style.left = div.style.top = '-99999em';
									parent.appendChild(div);
									setup();
									waitForImages(div, function() {
										contentReady = true;
										checkReady(true);
									});
									break;
							}
						}
						ajax = null;
						if (afterCallback) {
							afterCallback();
						}
					});
					ajax.send();
				}
			}
		})()
	};
})();

lightCore.registerInit(huh);

/*
function sendToJavaScript(val) {
	var preg = new RegExp('^huh\\.menu\\.(preload|flashready)', 'm');
	var result = val.match(preg);
	if (result) {
		switch (result[1]) {
			case 'preload':
				preg = new RegExp('url=(.*)$');
				result = val.match(preg);
				if (result) {
					huh.menu.preload(result[1]);
				}
				break;
			case 'flashready':
				huh.menu.flashready();
				break;
		}
	}
};

function jsFlashReady() {
	huh.menu.flashready()
};

function jsPreload(url) {
	huh.menu.preload("/?menu=" + url);
};
*/