var PhotoNav = Class.create({
	initialize: function(options){
		this.attach();
	},
	attach: function() {
		this.targetEl = $('content');
		this.prev_link = $('prev_link');
		if (!this.prev_link) {
			return;
		}
		this.next_link = $('next_link');
		this.prev_link.observe('click', this.goPrev.bind(this));
		this.next_link.observe('click', this.goNext.bind(this));
		this.link_box = $('left_bar');
		this.thumbs = $$('#left_bar a.th');
		this.template = new Template($('picture-template').innerHTML);
		var self = this;
    this.thumbs.each(function (el) {
			el.observe('click', self.clickHandler.bindAsEventListener(self));
		});
		this.firstThumb = this.thumbs.first();
		this.lastThumb = this.thumbs.last();
		this.lastHash = this.parseHash();
		this.hashInterval = false;
		if (this.lastHash) {
			this.go(this.lastHash);
		} else {
			this.go(this.firstThumb);
		}
	},
	setHashInterval: function(){
		this.hashInterval = setInterval(this.checkHash.bind(this), 200);
	},
	goNext: function() {
		this.go(this.cursor.next('a') || this.firstThumb, 1);
	},
	goPrev: function() {
		this.go(this.cursor.previous('a') || this.lastThumb, -1);
	},
	go: function(toElement, direction){
		if (!toElement) {
			return;
		}
		toElement = $(toElement);
		if (this.cursor && (toElement.id == this.cursor.id)) {
			return;
		};

		clearInterval(this.hashInterval);
		var lastCursor = this.cursor;
		if (direction) {
			// maybe load the next one?
		}
		this.select(toElement);
		var infotxt = toElement.readAttribute('stuff');
		var info = eval('(' + infotxt + ')');
		var self = this;
		var loadyfunc = function () {
			self.setHashFromCursor();
			self.targetEl.update(self.template.evaluate(info));
			self.targetEl.down('img').src = info.main;
			self.setHashInterval();
		};
		var i = new Image();
		i.src = info.main;
		i.onload = loadyfunc;
		// i.onerror = loadyfunc;
	},
	clickHandler: function(event){
		var el = event.element();
		if (el.tagName != 'A') {
			el = el.up('A');
		}
		this.go(el, 0);
	},
	select: function(current){
		var last = this.cursor;
		if (last) {
			last.removeClassName('selected');
		}
		this.cursor = current;
		window.location.hash = '#/'+current.id;
		current.addClassName('selected');
	},
	setHashFromCursor: function(){
		var h;
		if (this.cursor) {
			h = '#/'+this.cursor.id;
		} else {
			h = '';
		}
		window.location.hash = h;
		this.lashHash = h;
	},
	parseHash: function() {
		var h_url = window.location.hash;
		var exp = /(image\d+)/;
		var stuff = exp.exec(h_url);
		if (stuff && stuff[1]) {
			return stuff[1];
		}
		return '';
	},
	checkHash: function(){
		var nowHash = this.parseHash();
		if (nowHash != this.lastHash) {
			this.lastHash = nowHash;
			this.go(nowHash);
		}
	}
});