 // Copyright 2008 Walter Palagi <lepaca [at] animebox [dot] eu >, all rights reserved

//gmaps key ABQIAAAASIEyW6nldTAo40aCBJ1KERRixM3KdulttnwnnxD2aNJuviryyhSuIo8IxgG3vmIZtUsE7h9emx5lMw
//gmaps animebox key ABQIAAAASIEyW6nldTAo40aCBJ1KERSeFxKQ0SY0tlZTzld6l8CGdg0SXhTJezcdcSRNbxMGgQ1ntLX6JZZbLg


if (!window.console){
	console = new Object();
	console.log = function(a){
		alert(a)
	};
}

var Misc = {
	pad: function(n, c){
		var e = n + '';
		while(e.length < c) {
			e = "0" + e;
		}
		return e;
	}
}

var CoreElementInterface = {
	events: [], //[{target: 'self', callback: function(){}}, {target: 'id'}, {target: elmRef}]
	bindEvents: function () {
		this.events.each(function(evt){
			if (evt.target === 'self') {
				this.elm.observe(evt.name, evt.callback);
			} else {
				$(evt.target).observe(evt.name, evt.callback);
			}
		});
	},
	insert: function (tgt, where) {
		$('hidden').update(this.html);
		this.elm = $('hidden').down();
		this.elm.store('obj', this);
		var insertion = new Object();
		if (where) {
			insertion[where] = this.elm;
		} else {
			insertion['bottom'] = this.elm;
		}
		$(tgt).insert(insertion);
		if (this.events.length > 0) {
			this.bindEvents();
		}
	}
}


var ExtendedElementInterface = new Object();

ExtendedElementInterface.effectParameters = {appear: {duration: 1}, fade: {duration: 1}};

(['show', 'appear', 'hide', 'fade', 'morph']).each(function(effect) {
	ExtendedElementInterface[effect] = function(){
		this.elm[effect](this.effectParameters[effect]);
	}
});


var Ring = function () {
	var options = Object.extend({
		items: null,
		start: 0
	}, arguments[0]);
	if (!options.items) {
		this.items = [];
	} else {
		this.items = options.items;
	}
	this.length = this.items.length;
	this.currentIDX = options.start;
};

Ring.prototype =  Object.extend(Object.clone(Enumerable), {
	current: function () {
		return this.items[this.currentIDX];
	},
	next: function () {
		if (this.items.length > 0) {
			if (this.currentIDX >= this.items.length - 1) {
				this.currentIDX = 0;
			} else {
				this.currentIDX++;
			}
		}
	},
	prev: function() {
		if (this.items.length > 0) {
			if (this.currentIDX === 0) {
				this.currentIDX = this.items.length - 1;
			} else {
				this.currentIDX--;
			}
		}
	},
	add: function(item) {
		this.items.push(item);
		this.length = this.items.length;
	},
	reset: function () {
		this.currentIDX = 0;
	},
	_each: function (iterator) {
		for (var i = 0, l = this.items.length; i < l; ++i) {
			iterator(this.items[i]);
		}
	}
});


var Interface = {
	bootup:function(){
		if ($('searchBox')) {
			$('searchBox').observe('click', function(){
				this.value = '';
			});
		}
		ELM = Builder;
		Builder.dump(ELM);
		$(document.body).insert({bottom: '<div id="hidden"></div>'})
		new Effect.Appear($('hb'), {duration:2});
		if (!$('ie6only') && !$('ie7only')) {
			$('player').down('a').writeAttribute('href', null);
			$('player').observe('click', function(evt){
				window.open('http://www.theheadbangers.org/hb2/mp3_player', 'The Headbangers - MP3 Player', 'width=300,height=250,toolbar=no,location=no,menubar=no,scrollbars=no')
			});	
		}
		Interface.changePage($$('ul#menu a.selected')[0].readAttribute('href').replace(/ht.*\//, ''));
	},
	changePage:function(page){
		if (Interface.pageSpecificObject){Interface.pageSpecificObject.unload();}
		switch (page) {
			case 'news':
				Interface.pageSpecificObject = new News();
				break;
			case 'concerti':
				if ($('ie6only')) {
					return;
				}
				Interface.pageSpecificObject = new Concerts();
				break;
			case 'foto':
				if ($('ie6only')) {
					return;
				}
				Interface.pageSpecificObject = new Foto();
				break;
			case 'band':
				Interface.pageSpecificObject = new Theband();
				break;
			case 'musica':
				Interface.pageSpecificObject = new Music();
				break;
			case 'link':
				Interface.pageSpecificObject = new Links();
				break;
			default:
				return;
				break;
		}
	},
	getPageSize: function() {
		// This function from Lightbox 2.0
	  var xScroll, yScroll;

		if (window.innerHeight && window.scrollMaxY) {
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;

		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth;
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}

		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else {
			pageHeight = yScroll;
		}

		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){
			pageWidth = xScroll;
		} else {
			pageWidth = windowWidth;
		}

		return [pageWidth,pageHeight];
	},
	showText:function(src){
		var pos = document.viewport.getScrollOffsets();
		$('logo').insert(
			{before:
				ELM.DIV(
					{id:'overlay', style:'display:none; height:'+(Interface.getPageSize()[1]+2000)+'px;'}
				)
			}
		);
		$('logo').insert(
			{before:
				ELM.DIV({id:'imageContainer', style:'display:none;'},
					ELM.DIV({id:'innerImage', style:'display:block; margin:'+(pos[1]+document.viewport.getHeight()/10)+'px auto;'})
				)
			}
		)
		$('innerImage').update(src)
		$('overlay').observe('click', function(){$('imageContainer').remove(); this.remove()})
		$('imageContainer').observe('click', function(){$('overlay').remove(); this.remove()})
		$('overlay').show();
		new Effect.Appear($('imageContainer'), {duration:0.6});
	}
}

var Foto = function(){
	$$('img.photoThumb').each(
    		function(thumb){
			thumb.up().removeAttribute('href');
        		thumb.observe('click', function(){
				new Slideshow({imageList: $$('img.photoThumb').collect(function(thumb){
					return thumb.src.replace('_thumb.jpg', '.jpg');
				}), startFrom: this.up('div.photoThumb')?this.up('div.photoThumb').previousSiblings().length-1:this.up('a.photoThumb').previousSiblings().length-1});
			});
		}
	);
	new Ajax.Request('/ajax/photo_albums_ac_data', {
		onComplete: this.enableCompletion.bind(this)
	});
}

Foto.prototype = {
	enableCompletion: function(response){
		if (response.responseText) {
			this.completionData = response.responseText.evalJSON().albums;
			$(document.body).insert('<div id="photoChoices" class="autocomplete"></div>');
			var ac = new Autocompleter.Local('searchBox', 'photoChoices', this.completionData);
		}
	}
}

var Dock = Class.create();
Dock.prototype = {
	initialize:function(){
		this.icons = $$('.docked');
		this.h = this.icons[0].getHeight();
		this.w = this.icons[0].getWidth();
		if (this.w < 80) {this.w=82}
		this.l = this.icons.length;
		this.floatingInfo = $('floatingInfo');
		this.dock = $('dock');
		this.dockWidth = this.dock.getWidth();
		$('dock').observe('click', this.clickAction.bind(this));
		$('dock').observe('mousemove', this.moveAction.bind(this));
		$('dock').observe('mouseover', this.overAction.bind(this));
		$(document.body).observe('mouseout', this.outAction.bind(this));
	},
	clickAction:function(evt){
		var elm = evt.findElement('.docked');
		if (elm){
			$$('div.bandinfo').each(function(elm){elm.hide()});
			$(elm.readAttribute('res')).show();
		}
	},
	moveAction:function(evt){
		this.update(evt.pointerX());
	},
	update:function(x){
		x-=20;
		var dist;
		for (var i = 0; i < this.l; ++i){
			dist = Math.abs(x - (this.icons[i].positionedOffset()[0]+this.w/2))
			if (dist < 100){
				this.icons[i].setStyle({
					height: (this.h + 50 - Math.ceil(dist / 100 * 50)) +'px',
					width: (this.w + Math.ceil(this.w/1.666) - Math.ceil(dist / 100 * 50)) +'px',
					marginTop: (Math.ceil(dist / 100 * 50)) + 'px'
				});
				this.floatingInfo.setStyle({
					left:x+'px'
				});
			} else {
				this.reset(this.icons[i]);
			}
		}
	},
	reset:function(elm){
		elm.setStyle({
			height: this.h +'px',
			width: this.w +'px'
		});
	},
	outAction:function(evt){
		var target = evt.relatedTarget;
		if (target && !target.descendantOf('dock') && target.id != 'dock'){
			for (var i = 0; i < this.l; ++i){
				this.reset(this.icons[i]);
			}
			this.floatingInfo.hide();
		}
	},
	overAction:function(evt){
		var elm = evt.element();
		if (elm.hasClassName('docked')){
			var txt = elm.readAttribute('meta').split(' - ');
			txt = '<span style="font-size:12px;">' + txt[0] + '</span>' + '<br />' + '<span style="font-size:10px; font-weight:normal;">' + txt[1] + '</span>' + '<br />';
			this.floatingInfo.update(txt);
			this.floatingInfo.show();
		}
	}
}

var TimedProgressBar = function(progressBarElm, callback){
			this.tgt = $(progressBarElm);
			this.tgt.observe('progbar:restart', this.restart.bind(this));
			this.restart();
			this.callback = callback||null;
		};

TimedProgressBar.prototype = {
	restart:function(){
		var me = this;
		var fx = new Effect.Tween(
			null,
			0,
			100,
			{
				transition:Effect.Transitions.linear,
				fps:30,
				duration:4,
				afterFinish:function(){
					if (me.callback) {
						me.callback();
					}
					me.tgt.fire('progbar:restart');
				}
			},
			function(v){
				me.tgt.down('#progress').setStyle({width:v+'%'});
			}
		);
	}
};

var Ticker = function(tickerElm, tickerItemSel, timedProgressBarElm){
	this.tgt = $(tickerElm);
	this.items = new Ring({items: this.tgt.getElementsBySelector(tickerItemSel)});
	if (this.items.length > 1) {
		this.progressBar = new TimedProgressBar(timedProgressBarElm, this.next.bind(this));
		this.tgt.down('#count').update('1/' + this.items.length);
	} else {
		$(timedProgressBarElm).remove();
	}
	new Effect.Appear(this.items.current(), {duration: 0.5});
};

Ticker.prototype = {
	next:function(){
		var old = this.items.current();
		this.items.next();
		new Effect.Parallel(
			[
				new Effect.Fade(old, {sync:true}),
				new Effect.Appear(this.items.current(), {sync:true})
			],
			{duration:0.5}
		);
		this.tgt.down('#count').update((this.items.currentIDX + 1) + '/' + (this.items.length));
	}
};


var News = function () {
	var req = new Ajax.Request('/ajax/future_concerts', {
			onComplete: this.processTickerData.bind(this)
	});
	$$('a.flyerLink').each(function(elm){
		elm.removeAttribute('href');
	});
	$('content').observe('click', this.clickAction.bind(this));
}

News.prototype = {
	clickAction: function (evt) {
		var elm = evt.findElement('a.flyerLink');
		if (elm){
			new FullscreenImage({url: elm.down('img.flyer').readAttribute('src').split('_')[0]+'.jpg'});
		}
	},
	processTickerData: function(response) {
		if (response.responseText){
			var tickerItemTmplt = new Template(
				'<div class="tickerItem" style="display:none;">' +
					'<img class="flyer" src="#{flyer}" />' +
					'<div>' +
						'<p class="date">#{date}</p>' +
						'<p class="name">#{name}</p>' +
						'<p class="address">#{venue_name} - #{address}</p>' +
					'</div>' +
				'</div>'
			);
			var concertList = response.responseText.evalJSON().concerts;
			if (concertList.length > 0) {
				var tickerItems = [];
				for (var i=0, l=concertList.length; i<l; ++i){
					tickerItems.push(tickerItemTmplt.evaluate(concertList[i]));
				}
				$('content').insert({
					before: '<div id="ticker">' + tickerItems.join('') + '<div id="timedProgressBar"><div id="progress"></div></div><div id="count"></div><div id="tickerBottom"></div></div>'
				});
				$('ticker').observe('click', function(){window.location='concerti';});
				this.ticker = new Ticker('ticker', '.tickerItem', 'timedProgressBar');
			}
		}
	}
};

var Place = function () {
	var options = Object.extend({
		latitude: null,
		longitude: null,
		address: null,
		html: null,
		geocoder: null
	}, arguments[0]);
	if (!options.geocoder && !(options.longitude && options.latitude)) {
		throw 'Place: cannot define a place without a geocoder; please set a geocoder';
	}
	if (!options.html) {
		throw 'Place: HTML fragment needed for balloon';
	}
	this.html = options.html;
	if (options.longitude && options.latitude){
		this.coords = new GLatLng(options.latitude, options.longitude);
		this.marker = new GMarker(this.coords);
		document.fire('place:markerisready', {place:this});
	}
	if (!options.latitude || !options.longitude) {
		//geocode coords from address
		options.geocoder.getLatLng(options.address, this.updateCoords.bind(this))
	}
};

Place.prototype = {
	updateCoords: function (coords, evt) {
		this.coords = coords;
		this.marker = new GMarker(coords);
		document.fire('place:markerisready', {place:this});
	},
	getHTML: function () {
		return this.html;
	},
	getMarker: function () {
		if (!this.marker) {
			throw 'Place: marker not ready yet!'
		} else {
			return this.marker;
		}
	},
	getCoords: function () {
		if (!this.coords) {
			throw 'Place: coords not yet received!'
		} else {
			return this.coords;
		}
	}
};


var HBGMap = function () {
	if (!GBrowserIsCompatible()) {
		throw 'GMap: this browser sucks, sorry.';
	}
	var options = Object.extend({
		mapElm: null,
		initialPosition: null
	}, arguments[0]);
	this.gmap = new GMap2(options.mapElm);
	this.gmap.enableContinuousZoom();
	this.gmap.enableScrollWheelZoom();
	this.gmap.addControl(new GSmallMapControl());
	this.gmap.hideControls();
	options.mapElm.observe('mouseover', this.gmapActions.bindAsEventListener(this, true));
	options.mapElm.observe('mouseout', this.gmapActions.bindAsEventListener(this, false));
	this.initialized = false;
	if (options.initialPosition) {
		this.gmap.setCenter(initialPosition, 13);
		this.initialized = true;
	}
	document.observe('place:markerisready', this.addMarker.bind(this));
};

HBGMap.prototype = {
	gmapActions:function(evt, condition){
		if (condition){
			this.gmap.showControls();
		}
		else {
			this.gmap.hideControls();
		}
	},
	addMarker: function (evt) {
		this.gmap.addOverlay(evt.memo.place.getMarker());
		evt.memo.place.getMarker().bindInfoWindow(evt.memo.place.getHTML());
		if (!this.initialized) {
			this.initialized = true;
			this.gmap.setCenter(evt.memo.place.getMarker().getLatLng(), 13);
			evt.memo.place.getMarker().openInfoWindow(evt.memo.place.getHTML())
		}
	},
	panTo: function (place) {
		this.gmap.panTo(place.getMarker().getLatLng());
		place.getMarker().openInfoWindow(place.getHTML());
	}
};


var Concerts = function () {
	$$('a.flyerLink').each(function(elm){
		elm.removeAttribute('href');
	});
	document.observe('click', this.clickAction.bind(this));
	new Ajax.Request('/ajax/concerts_ac_data', {
		onComplete: this.enableCompletion.bind(this)
	});
	if ($('content').getElementsBySelector('h1').length >= 2) {
		new Ajax.Request('/ajax/future_concerts', {
			onComplete: this.processConcertList.bind(this)
		});
	}
};

Concerts.prototype = {
	enableCompletion: function(response){
		if (response.responseText) {
			this.completionData = response.responseText.evalJSON().concerts;
			$(document.body).insert('<div id="concertChoices" class="autocomplete"></div>');
			var ac = new Autocompleter.Local('searchBox', 'concertChoices', this.completionData);
		}
	},
	processConcertList: function (response) {
		if (response.responseText) {
			var newGigsTmplt = new Template('<p class="concert">#{date} #{name}, #{address}</p>'),
				balloonTmplt = new Template('<div class="balloon"><img class="#{className}" src="#{flyer}" /><p><span class="date">#{date}</span><br /><span class="name">#{name}</span><br /><span class="place">#{venue_name} - #{address}</span></p></div>'),
				concertList = response.responseText.evalJSON().concerts;
			var future = '';
			if (concertList.length > 0) {
				future ='<div id="mapControls">' +
						'<img class="prev" src="/assets/img/prev2.png" />' +
						'<span class="progress"></span>' +
						'<img class="next" src="/assets/img/next2.png" />' +
					'</div>' +
					'<div id="gmap"></div>';
					$('content').down('.concertList').remove();
					$('content').down('h1').insert({after: future});
				if (concertList.length === 1) {
					$('mapControls').remove();
					$('gmap').setStyle({border: '1px solid #AAA'});
				}
				this.gmap = new HBGMap({
					mapElm: $('gmap')
				});
				var geocoder = new GClientGeocoder();
				if ($('mapControls')) {
					this.count = concertList.length;
					document.observe('place:markerisready', this.countDown.bind(this));
				}
				this.places = new Ring({
					items: concertList.collect(function(gig){
						var html = balloonTmplt.evaluate({
							flyer: gig.flyer,
							date: gig.date,
							name: gig.name,
							address: gig.address,
							venue_name: gig.venue_name,
							className: gig.flyerOrVenue
						});
						return new Place({
							address: gig.address,
							html: html,
							latitude: gig.lat,
							longitude: gig.lng,
							geocoder: geocoder
						});
					})
				});
			}
		}
	},
	countDown: function () {
		this.count--;
		if (this.count === 0) {
			$('mapControls').down('.progress').update('1/' + this.places.length);
			this.ready = true;
		}
	},
	clickAction: function (evt) {
		if (evt.findElement('.prev') && this.ready){
			this.places.prev();
			if ($('mapControls')) {
				$('mapControls').down('.progress').update((this.places.currentIDX + 1) + '/' + this.places.length);
			}
			this.gmap.panTo(this.places.current());
		} else if (evt.findElement('.next') && this.ready){
			this.places.next();
			if ($('mapControls')) {
				$('mapControls').down('.progress').update((this.places.currentIDX + 1) + '/' + this.places.length);
			}
			this.gmap.panTo(this.places.current());
 		} else if (evt.findElement('a.flyerLink')) {
	 	 	var elm = evt.findElement('a.flyerLink');
			new FullscreenImage({url: elm.down('img.flyer').readAttribute('src').split('_')[0]+'.jpg'});
		} else if (evt.findElement('.flyer') && evt.findElement('div.balloon')) {
			var src = evt.findElement('img.flyer').readAttribute('src').split('_')[0];
			if (src != 'default') {
				new FullscreenImage({url: src + '.jpg'});
			}
		}
	}
}


var Theband = new Class.create();
Theband.prototype = {
	initialize:function(){
// 		$$('.bandinfo.member').invoke('hide');
// 		$('dock').show();
// 		new Dock();
	}
}


var ImageLoader = function () {
	var options = Object.extend({
			url: null,
			target: null
		}, arguments[0]),
		im = new Image();
	im.src = options.url;
	if (im.complete){
		options.target.src = options.url;
	} else {
		options.target.src = '/assets/img/ajax-loader.gif';
		im.onload = function(){

			options.target.src = this.src;
			this.onload = null;
		}
	}
}

var ImagePresentationInterface = {
	spinner: '/assets/img/ajax-loader.gif',
	makeOverlay: function () {
		var pos = document.viewport.getScrollOffsets();
		$(document.body).insert(
			{top:
				ELM.DIV(
					{id:'overlay', style:'display:none; height:'+(Interface.getPageSize()[1]+2000)+'px;'}
				)
			}
		);
		$('overlay').observe('click', function(){$('imageContainer').remove(); this.remove()})
	},
	makeImageFrame: function () {
		var pos = document.viewport.getScrollOffsets();
		$(document.body).insert({
			top: ELM.DIV({
				id:'imageContainer',
				style:'display:none;'
			}, [
				ELM.P({
					id:'clicktoclose',
					style:'color:white; text-align:center; margin:'+(pos[1]+document.viewport.getHeight()/40)+'px 0 0'
				}, 'Clicca per chiudere l\'immagine'),
				ELM.IMG({
					id:'innerImage',
					src: this.spinner,
					style:'display:block; margin:20px auto;'
				})
			])
		});
	}
}


var FullscreenImage = function () {
	var options = Object.extend({
		url: null
	}, arguments[0]);
	var pos = document.viewport.getScrollOffsets();
	this.makeImageFrame();
	this.makeOverlay();
	$('imageContainer').observe('click', function(){$('overlay').remove(); this.remove()})
	$('overlay').show();
	new Effect.Appear($('imageContainer'), {duration:0.6});
	new ImageLoader({url: options.url, target: $('innerImage')});
}

FullscreenImage.prototype = ImagePresentationInterface;


var FullscreenText = function (txt) {
	var pos = document.viewport.getScrollOffsets();
	this.makeImageFrame();
	this.makeOverlay();
	$('clicktoclose').update('')
	$('innerImage').replace(ELM.DIV({id: 'innerImage'}));
	$('innerImage').update(txt);
	$('imageContainer').observe('click', function(){$('overlay').remove(); this.remove()})
	$('overlay').show();
	new Effect.Appear($('imageContainer'), {duration:0.6});
}

FullscreenText.prototype = ImagePresentationInterface;


var Slideshow = function () {
	var options = Object.extend({
		imageList:[],
		startfrom:0
	}, arguments[0]);
	if (options.imageList.length < 1) {
		throw 'Can\'t make a slideshow out of ' + options.imageList.length + ' images!';
	}
	this.imageList = options.imageList;
	this.currentPhotoIdx = options.startFrom;
	this.makeOverlay();
	$('overlay').setStyle({cursor: 'auto'});
	this.makeImageFrame();
	if (options.startFrom === 0) {
		$('imageContainer').down('.prev').setOpacity(0.5);
	}
	if (options.startFrom === this.imageList.length - 1) {
		$('imageContainer').down('.next').setOpacity(0.5);
	}
	$('overlay').show();
	new Effect.Appear($('imageContainer'), {duration:0.6});
	new ImageLoader({url: this.imageList[options.startFrom], target: $('innerImage')});
	$('imageContainer').observe('click', this.clickAction.bind(this));
};

Slideshow.prototype = Object.extend(Object.clone(ImagePresentationInterface), {
	makeImageFrame: function () {
		var pos = document.viewport.getScrollOffsets();
		$('logo').insert(
			{before:
				ELM.DIV({id:'imageContainer', style:'display:none; cursor: auto;'},
					[
						ELM.P({id:'clicktoclose',
							style:'width: 180px; height: 50px; text-align:center; margin:'+(pos[1]+document.viewport.getHeight()/40)+'px auto 0; background: #333; -moz-border-radius: 10px; -webkit-border-radius: 10px;'},
							[ELM.IMG({src: '/assets/img/prev2.png', style: 'cursor:pointer;', className: 'prev'}),
							ELM.IMG({src: '/assets/img/next2.png', style: 'cursor:pointer;', className: 'next'}),
							ELM.IMG({src: '/assets/img/close2.png', style: 'cursor:pointer;', className: 'close'})]
						),
					ELM.IMG({id:'innerImage', src:this.spinner, style:'display:block; margin:20px auto; cursor: auto;'})]
				)
			}
		)
	},
	changeImage:function(src){
		new ImageLoader({url: src, target: $('innerImage')});
	},
	clickAction: function(evt){
		if (evt.findElement('.close')) {
			$('imageContainer').stopObserving();
			$('imageContainer').remove();
			$('overlay').remove();
		}
		if (evt.findElement('.prev') && this.currentPhotoIdx > 0) {

			this.changeImage(this.imageList[--this.currentPhotoIdx]);
			$('imageContainer').down('.next').setOpacity(1.0);
			if (this.currentPhotoIdx === 0) {
				$('imageContainer').down('.prev').setOpacity(0.5);
			}
		}
		if (evt.findElement('.next')&& this.currentPhotoIdx < (this.imageList.length - 1)) {
			this.changeImage(this.imageList[++this.currentPhotoIdx]);
			$('imageContainer').down('.prev').setOpacity(1.0);
			if (this.currentPhotoIdx === this.imageList.length - 1) {
				$('imageContainer').down('.next').setOpacity(0.5);
			}
		}
	}
});


var Music = new Class.create()
Music.prototype = {
	initialize:function(){
		$('content').observe('click', this.lyricAction.bind(this));
	},
	lyricAction:function(evt){
		var elm = evt.findElement('.lyricsLink');
		if (elm) {
			new FullscreenText(elm.next('div.lyrics').innerHTML);
		}
	},
	unload:function(){
		$('content').stopObserving();
	}
};


var Links = function(){
	$$('.category').each(function(elm){elm.down('ul').toggle()});
	$('content').observe('click', this.clickAction.bind(this));
};

Links.prototype = {
	clickAction:function(evt){
		var elm = evt.element();
		if (elm && elm.up('.category') && elm.next('ul')) {
			elm.next().toggle();
			elm = elm.up('.category');
			elm.toggleClassName('expanded');
			elm.toggleClassName('contracted');
		}
	},
	unload:function(){
		$('content').stopObserving();
	}
}

document.observe('dom:loaded', Interface.bootup)