window.addEvent('domready', function(){
	if (!$(document.body).hasClass('editor') && $('gallery') && $('gallery').getElement('a') && $('gallery').getElement('li')) {
		var index = 0;
		var src = '';
		var image = new Element('img').inject(
			new Element('div').inject($('gallery'), 'top')
		).addEvent('load', function(){
			fx.start('opacity', 1);
		});
		
		var init = 1;
		if (window.location.hash != '') {
			init = window.location.hash.substr(1).toInt();
		}
		image.setProperties({
			'src': $('gallery').getElements('a')[init-1].getProperty('href')
		});
		
		var fx = new Fx.Tween(image, {
			link: 'cancel',
			duration: 300,
			onComplete: function(){
				if (image.getStyle('opacity') == 0) {
					image.setProperty('src', src);
				}
			}
		});
		
		$('gallery').setStyles({
			'position': 'relative'
		});
		
		var scroller = null;
		var position = $('gallery').getElement('ul').getPosition().x;
		var width = $('gallery').getElement('ul').getSize().x;
		var velocity = 0;
		$('gallery').getElement('ul').setStyles({
			'position': 'relative'
		}).addEvent('mousemove', function(e){
			e = new Event(e);
			position = $('gallery').getElement('ul').getPosition().x;
			width = $('gallery').getElement('ul').getSize().x;
			velocity = 0;
			if ((e.client.x - position) < (width / 4)) {
				velocity = -(((width / 4) - (e.client.x - position)) * 0.1);
			} else if ((e.client.x - position) > (width - (width / 4))) {
				velocity = (((e.client.x - position) - (width - (width / 4))) * 0.1);
			}
			if (scroller == null) {
				scroller = (function(){
					if (velocity != 0) {
						$('gallery').getElement('ul').scrollTo($('gallery').getElement('ul').getScroll().x + velocity, $('gallery').getElement('ul').getScroll().y);
					} else {
						clearInterval(scroller);
						scroller = null;
					}
				}).periodical(10);
			}
		}.bind(this)).addEvent('mouseleave', function(e){
			if (scroller != null) {
				clearInterval(scroller);
				scroller = null;
			}
		}.bind(this));
		
		$('gallery').getElements('li').each(function(li, i){
			li.setStyles({
				'position': 'absolute',
				'top': 1,
				'left': 85*(i+index)
			}).set('tween', {
				link: 'chain',
				duration: 200
			});
			li.getElement('a').addEvent('click', function(e){
				new Event(e).stop();
				if (this.getProperty('href') != image.getProperty('src')) {
					$('gallery').getElements('li').removeClass('selected');
					li.addClass('selected');
					window.location.hash = '#'+(i+1);
					src = this.getProperty('href');
					fx.start('opacity', 0);
				}
			});
			if (li.getElement('a').getProperty('href') == image.getProperty('src')) {
				li.addClass('selected');
			}
		});
		
		$('gallery').getElement('ul').scrollTo(85*(init-1), $('gallery').getElement('ul').getScroll().y);
						
	}
});
