var Frontide = {
// !Environment
	Environment: Class.create({
		initialize: function(parent) {
			this.parent			= parent;
			this.btype			= $('top').className.split(' ')[0];
			this.anchor			= location.hash.replace(/(^\/#\/|^\/#|^#\/|^#|^\/)/, '');
			this.first			= $($$('#navigation-menu li a').first());
			this.linksenabled	= false;
		},
		activateLinks: function() {
			$$('a').invoke('removeClassName', 'active');
			$$('a[href=/#/' + this.anchor + ']', 'a[rev=' + this.btype + ']', 'a[name=' + this.btype + ']').invoke('addClassName', 'active');

			// anchorize FORMS
			$$('form').each(function(el, index) {
				el.target = 'upload';
				el.insert({ 'top': '<input type="hidden" name="ajax" value="true" />' });
				el.stopObserving().observe('submit', function(ev) {
					var base = new RegExp(window.location.protocol + '//' + window.location.host + '/');
					window.location.href = '/#/' + el.action.replace(base, '');
				})
			});
		},
		prepareLinks: function() {
			// anchorize LINKS
			this.btype = $('top').className.split(' ')[0];
			this.anchor = location.hash.replace(/(^\/#\/|^\/#|^#\/|^#|^\/)/, '');
			this.activateLinks();
			$$('a:not(.noanchorize):not(.invisible)').each((function(link) {
				var href = link.readAttribute('href');
				if (href.startsWith('mailto:') || href.startsWith('http:') || href.startsWith('www.'))
					return;
				if (href.replace(/^\//, '').substr(0, 1) != '#' && !link.rev.length && !link.hash.length) {
					link.parent	= this;
					link.rev = link.href.replace(/^\//, '');
					link.writeAttribute({ 'href': '/#/' + href });
					link.observe('click', function() {
						if (this.parent.linksenabled) {
							this.parent.activateLinks();
							this.parent.parent.content.load(this.rev.replace(/^\//, ''), this.parent.parent.content.build.bind(this.parent.parent.content));
							if ($$('.mod_subscribe').first().visible())
								new Effect.Fade($$('.mod_subscribe').first(), { duration: .5 });
						}
					});
				}
			}).bind(this));
		},
		anchorize: function(callback) {
			if (Options.javascript.ajax) {
				// reinitialization
				this.btype	= $('top').className.split(' ')[0];
				this.anchor	= location.hash.replace(/(^\/#\/|^\/#|^#\/|^#|^\/)/, '');
				
				// anchorize URL
				var path = location.pathname.replace(/(^\/)/, '');
				if (!/#/.test(location.href) && path.length) {
					window.location.href = '/#/' + path;
					this.parent.content.load(path, callback);
				} else this.parent.content.load("/" + this.anchor, callback);

				// anchorize LINKS
				this.prepareLinks();

			} else if (location.hash.replace(/^\//, '')[0] == '#')
				window.location.href = this.anchor.replace(/(^\/#\/|^\/#|^#\/|^#|^\/)/, '');
		}
	}),

// !Content
	Content: Class.create({
		initialize: function(parent) {
			this.parent			= parent;
			this.type			= $('top').className.split(" ");
			//this.loader			= $($$('.loader').first());
			//this.loader.bar		= this.loader.down(0);
			this.menu			= $('navigation-menu');
			this.newsletter		= $($$('.mod_subscribe').first());
			this.active			= $($$('a.active').first());
			this.container		= $($$('.content').first());
			this.stage			= $($$('.stage').first());
			this.stage.img		= this.stage.select('img').first();
			this.stage.resize	= function() {
				var vs	= document.viewport.getDimensions();
				var vm	= vs.width / vs.height;
				var is	= this.img.getDimensions();
				var im	= is.width / is.height;

				if (vm < im)
					this.img.setStyle({ width: 'auto', height: '100%' });
				else if (vm >= im)
					this.img.setStyle({ width: '100%', height: 'auto' });
				else this.img.setStyle({ width: '100%', height: '100%' });
			}
		},
		parseContent: function(transport, callback) {
			/* DEPRECATED
			// getting CONTENT CONTAINER
			var cs	= ['<!-- FRONTIDE START -->', '<!-- FRONTIDE END -->'];
			var ci	= [transport.responseText.indexOf(cs[0]) + cs[0].length, transport.responseText.indexOf(cs[1]) - 1];
			var c	= transport.responseText.slice(ci[0], ci[1]);

			// getting DOCUMENT TITLE
			var ts	= ['<title>', '</title>'];
			var ti	= [transport.responseText.indexOf(ts[0]) + ts[0].length, transport.responseText.indexOf(ts[1])];
			var t	= transport.responseText.slice(ti[0], ti[1]);

			// getting BODY CLASS NAME
			var bs	= ['<body class="', '"'];
			var bi	= [transport.responseText.indexOf(bs[0]) + bs[0].length, transport.responseText.indexOf(bs[1], transport.responseText.indexOf(bs[0]) + bs[0].length)];
			var b	= transport.responseText.slice(bi[0], bi[1]);

			callback({ bodyclasses: b, content: c, title: t });
			*/

			var req = {
				bodyclasses: transport.getResponseHeader ? transport.getResponseHeader('class') : $('top').className,
				content: transport.responseText,
				title: transport.getResponseHeader ? transport.getResponseHeader('title') : document.title
			}
			if (transport.responseText)
				callback(req);
		},
		load: function(url, callback, opts) {
			// DISABLE LINKS
			this.parent.environment.linksenabled = false;
			var parseContent = this.parseContent;

			// GET HTML PAGE,
			new Ajax.Request(url, Object.extend({
				method: 'post',
				parameters: { 'ajax': true },
				onInteractive: (function(request) {
					//var percent = Math.round((request.responseText.length / request.getResponseHeader("Content-Length")) * 100);
					//this.loader.bar.update(percent + '% geladen');
				}).bind(this),
				onSuccess: (function(transport) {
					parseContent(transport, callback);
				}).bind(this)
			}, opts));
		},
		build: function(args) {
			this.type = args.bodyclasses.split(" ");

			// AUSBLENDEN
			new Effect.Parallel([
				new Effect.Fade(this.container, { sync: true }),
				new Effect.Fade(this.stage, { sync: true })
			], {
				duration: Options.animation.duration,
				afterFinish: (function() {
					// EINBLENDEN
					document.title		= args.title;
					$('top').className	= args.bodyclasses;

					this.container.update(args.content);
					this.parent.environment.prepareLinks();
					this.prepare(this.type[0]);
					this.view(this.type[0], this.type[2] || "appear", 0);

				}).bind(this),
				queue: { scope: 'content', position: 'end' }
			});
		},
		prepare: function(type) {
			// changing Links active
			//$($$('a.active')[0]).removeClassName('active');
			//$($$('a[name=' + type + ']')).invoke('addClassName', 'active');
			this.wrapper	= this.container.select('.wrapper').first();

			// site specific jobs
			switch (type) {
				case "home":
					// VORBEREITEN
/*
					this.wrapper.insert({ top: '<div class="img-stage" style="display: none;"><img src="" alt="" /></div>' });
					var items	= new Array();
					var stage	= this.container.select('.img-stage').first();
					var imgs	= this.container.select('.mod_article').each(function(article) {
						var txt = article.select('.ce_text').first().setStyle({ display: 'none' }).removeClassName('block').insert({ bottom: '<br /><br />' });
						var img = article.select('.ce_image').each(function(i) {
							var ir = i.remove();
							txt.insert({ bottom: ir });
							ir.observe('click', function() {
								if (stage.down('img').src != this.down('img').src) {
									stage.hide();
									stage.down('img').src = this.down('img').src;
									new Effect.Appear(stage, { duration: Options.animation.duration });
								}
							}).setStyle({ cursor: 'pointer' });
						});
						items.push(txt);
					});
					var heads	= this.container.select('.ce_headline').invoke('setStyle', { cursor: 'pointer' });
						heads.invoke('observe', 'mouseover', function() { this.addClassName('active'); });
						heads.invoke('observe', 'mouseout', function() { this.removeClassName('active'); });
						heads.invoke('observe', 'click', function() {
							items.findAll(function(item) {
								if(item.visible())
									Effect.SlideUp(item, { duration: Options.animation.duration, afterFinish: (function() {
										var head = item.previous(0);
											head.removeClassName('active').observe('mouseout', function() { head.removeClassName('active'); });
									}).bind(this) });
							});
	
							if (!this.next(0).visible()) {
								this.addClassName('active').stopObserving('mouseout');
								Effect.SlideDown(this.next(0), { duration: Options.animation.duration });
							} else Effect.SlideUp(this.next(0), { duration: Options.animation.duration });
							
							if (stage.visible()) {
								new Effect.Fade(stage, { duration: Options.animation.duration });
								stage.down('img').src = '';
							}
						});
*/
					break;
				case "stores":
					/*this.cnt = function(menu) {
						var stores = $$('.mod_article').invoke('hide');
						this.container.show();
						Effect.multiple(stores, Effect.Appear, {
							duration: Options.animation.duration * 2.5,
							delay: menu ? Options.animation.duration * 2.5 : 0,
							afterFinish: (function() {
								this.parent.environment.linksenabled = true;
							}).bind(this)
						});
					}*/
					break;
				case "brands":
					this.wrapper.insert({ top: '<div id="brand_selector"></div>' });
					var prev	= $('brand_selector').hide();
					var items	= this.container.select('li').each(function(i) {
						i.prev	= prev;
						i.span	= (s = i.down('span')) ? s.remove().innerHTML : '';
						i.msg	= '<span class="brand">' + i.innerHTML + '</span><span class="store">' + i.span + '</span>';
						i.observe('mouseover', function() {
							this.addClassName('hover');
							this.prev.update(this.msg);
							this.prev.show(); //new Effect.Appear(this.prev, { duration: Options.animation.duration, queue: { scope: 'prev', position: 'end' }});
						});
						i.observe('mouseout', function() {
							this.removeClassName('hover');
							this.prev.hide();
						});
					});
					break;
				case "team":
					// VORBEREITEN
					this.wrapper.insert({ top: '<div id="team_member"></div>' });
					var prev	= $('team_member').absolutize();
					var items	= this.wrapper.select('.mod_article:not([class~=vorstellung])');
					var active	= items.first().down(0);
						items.each((function(item, index) {
							item.index	= index;
							item.prev	= prev;
							item.head	= item.down(0);
							item.head.p	= item;
							item.text	= item.head.next(0).remove().innerHTML;

							item.head.observe('mouseover', function() { this.addClassName('active'); });
							item.head.observe('mouseout', function() { this.removeClassName('active'); });
							item.head.observe('click', function() {
								if (this != active) {
									active.removeClassName('active').observe('mouseout', function() { this.removeClassName('active'); });
									active = this;

									this.stopObserving('mouseout').addClassName('active');

									new Effect.Parallel([
										new Effect.DropOut(this.p, { sync: true }),
										//new Effect.SlideUp(this.p, { sync: true }),
										new Effect.Fade(this.p.prev, { sync: true })
									], {
										duration: Options.animation.duration,
										afterFinish: (function() {
											var wrapper	= this.p.up(0);
											this.p		= this.p.remove();
											
											wrapper.insert({ top: this.p });
											this.p.prev.update(this.p.text);

											new Effect.Parallel([
												new Effect.SlideDown(this.p, { sync: true }),
												new Effect.Appear(this.p.prev, { sync: true })
											], {
												duration: Options.animation.duration
											});
										}).bind(this)
									});
								}
							});
						}).bind(this));
						active.stopObserving('mouseout').addClassName('active');
						prev.update(items.first().text).show();
					break;
				case "blog":
					break;
				default:
					break;
			}
		},
		view: function(type, fade, menu) {
			//this.stage.img.src = '/media/pic/Backgrounds/loading.jpg';
			var img			= new Image();
				img.onload	= (function() {

					// HINTERGRUNDBILD TAUSCHEN
					this.stage.img.src = img.src;
					this.stage.resize();
		
					// STAGE EINBLENDEN
					switch (fade) {
						case "downFade":
							new Effect.Move(this.stage, {
								x: 0,
								y: 0,
								mode: 'absolute',
								duration: Options.animation.duration * 3,
								queue: { scope: 'content', position: 'end' },
								beforeStart: (function() {
									this.stage.setStyle({ top: '-' + this.stage.getHeight() + 'px' });
									this.stage.show();
								}).bind(this)
							})
							break;
						case "downBounce":
							new Effect.Move(this.stage, {
								x: 0,
								y: 0,
								mode: 'absolute',
								duration: Options.animation.duration * 4.5,
								transition: Effect.Transitions.spring,
								queue: { scope: 'content', position: 'end' },
								beforeStart: (function() {
									this.stage.setStyle({ top: '-' + this.stage.getHeight() + 'px' });
									this.stage.show();
								}).bind(this)
							})
							break;
						case "leftFade":
							new Effect.Move(this.stage, {
								x: 0,
								y: 0,
								mode: 'absolute',
								duration: Options.animation.duration * 3,
								queue: { scope: 'content', position: 'end' },
								beforeStart: (function() {
									this.stage.setStyle({ left: '-' + this.stage.getWidth() + 'px' });
									this.stage.show();
								}).bind(this)
							})
							break;
						case "leftBounce":
							new Effect.Move(this.stage, {
								x: 0,
								y: 0,
								mode: 'absolute',
								duration: Options.animation.duration * 4.5,
								transition: Effect.Transitions.spring,
								queue: { scope: 'content', position: 'end' },
								beforeStart: (function() {
									this.stage.setStyle({ left: '-' + this.stage.getWidth() + 'px' });
									this.stage.show();
								}).bind(this)
							})
							break;
						case "rightFade":
							new Effect.Move(this.stage, {
								x: 0,
								y: 0,
								mode: 'absolute',
								duration: Options.animation.duration * 3,
								queue: { scope: 'content', position: 'end' },
								beforeStart: (function() {
									this.stage.setStyle({ left: this.stage.getWidth() + 'px' });
									this.stage.show();
								}).bind(this)
							})
							break;
						case "rightBounce":
							new Effect.Move(this.stage, {
								x: 0,
								y: 0,
								mode: 'absolute',
								duration: Options.animation.duration * 4.5,
								transition: Effect.Transitions.spring,
								queue: { scope: 'content', position: 'end' },
								beforeStart: (function() {
									this.stage.setStyle({ left: this.stage.getWidth() + 'px' });
									this.stage.show();
								}).bind(this)
							})
							break;
						case "upFade":
							new Effect.Move(this.stage, {
								x: 0,
								y: 0,
								mode: 'absolute',
								duration: Options.animation.duration * 3,
								queue: { scope: 'content', position: 'end' },
								beforeStart: (function() {
									this.stage.setStyle({ top: this.stage.getHeight() + 'px' });
									this.stage.show();
								}).bind(this)
							})
							break;
						case "upBounce":
							new Effect.Move(this.stage, {
								x: 0,
								y: 0,
								mode: 'absolute',
								duration: Options.animation.duration * 4.5,
								transition: Effect.Transitions.spring,
								queue: { scope: 'content', position: 'end' },
								beforeStart: (function() {
									this.stage.setStyle({ top: this.stage.getHeight() + 'px' });
									this.stage.show();
								}).bind(this)
							})
							break;

						case "appear":
							this.stage.setOpacity(0).show();
							this.stage.resize();
							new Effect.Opacity(this.stage, {
								from: 0,
								to: 1,
								duration: Options.animation.duration * 2,
								queue: { scope: 'content', position: 'end' }
							});
							break;
					}

					if (menu)
						Effect.multiple(this.menu.select('li'), Effect.Morph, {
							style: 'left: 10px;',
							duration: Options.animation.duration * 2.5
						});

					if (this.cnt) {
						this.cnt(menu);
						delete this.cnt;
					} else {
						// CONTENT EINBLENDEN
						new Effect.Appear(this.container, {
							duration: Options.animation.duration * 2.5,
							delay: menu ? Options.animation.duration * 2.5 : 0,
							queue: { scope: 'content', position: 'end' },
							afterFinish: (function() {
								this.parent.environment.linksenabled = true;
								this.parent.environment.prepareLinks();
							}).bind(this)
						});
					}

				}).bind(this);
				
				img.onerror	= (function() {
					// HINTERGRUNDBILD TAUSCHEN
					this.stage.img.src = '/media/pic/Backgrounds/nothing.png';
					this.stage.img.alt = '';
					this.stage.show();

					// CONTENT EINBLENDEN
					new Effect.Appear(this.container, {
						duration: Options.animation.duration * 2.5,
						queue: { scope: 'content', position: 'end' },
						beforeStart: (function() {
						// MENU EINBLENDEN
						if (menu)
							Effect.multiple(this.menu.select('li'), Effect.Morph, {
								style: 'left: 20px;',
								duration: Options.animation.duration * 2.5
							});
						}).bind(this),
						afterFinish: (function() {
							this.parent.environment.linksenabled = true;
							this.parent.environment.prepareLinks();
						}).bind(this)
					});
				}).bind(this);

				img.src		= '/media/pic/Backgrounds/' + type + '.jpg';
		}
	}),

// !Core
	Core: Class.create({
		initialize: function(env) {
			if (Options.javascript.enabled) {
				this.content		= new Frontide.Content(this);
				this.environment	= new Frontide.Environment(this);
				this.upload			= $('upload');

				// prepare iFrame
				this.upload.observe('load', (function() {
					if (this.upload.contentDocument)	var d = this.upload.contentDocument;
					else if (this.upload.contentWindow)	var d = this.upload.contentWindow.document;
					else								var d = window.frames['upload'].document;
	
					this.content.parseContent({
						'responseText': d.body.innerHTML
					}, this.content.build.bind(this.content));
				}).bind(this));

				this.environment.anchorize(this.start.bind(this));
			} else $$('.noscript').invoke('show').invoke('removeClassName', 'noscript');
		},
		start: function(args) {
			var type = args.bodyclasses.split(" ")[0];
			$$('.noscript').invoke('hide').invoke('removeClassName', 'noscript');
			new Effect.Parallel([
				new Effect.Appear($($$('.bar')[0]), { sync: true }),
				new Effect.Appear($($$('.navigation')[0]), { sync: true })
			], { duration: Options.animation.duration });

			document.title		= args.title;
			$('top').className	= args.bodyclasses;

			this.content.stage.resize();
			this.content.stage.hide();
			this.content.container.update(args.content);
			this.content.menu.select('li').invoke('setStyle', { left: '-280px' });
			this.content.prepare(type);
			this.content.view(type, 'appear', true);
			this.content.newsletter.select('.submit').first().observe('click', (function() {
				this.content.newsletter.down('form').request({
					method: 'post',
					onCreate: function() {
						$$('.notification').first().update('Ihre Email wird &uuml;bertragen.');
					},
					onSuccess: function(transport) {
						var ns	= ['<span class="notification">', '</span>'];
						var ni	= [transport.responseText.indexOf(ns[0]) + ns[0].length, transport.responseText.indexOf(ns[1], transport.responseText.indexOf(ns[0]) + ns[0].length)];
						var n	= transport.responseText.slice(ni[0], ni[1]);
						$$('.notification').first().update(n);
					}
				});
			}).bind(this)).type = 'button';
			this.content.newsletter.hide().removeClassName('noscript');

			// resizing stage image
			Event.observe(window, 'resize', (function() {
				this.content.stage.resize();
			}).bind(this));
		}
	})
}
