var Gallery = Class.create();
Gallery.prototype = {
	initialize: function(element) {
		this.photos = eval($(element).getAttribute('rel'));
		this.links = $(element).select('a');
		this.index = 0;

		if (this.links != null) {
			this.link = this.links[0]; // 1st in the index
			if (this.links.length >= 3) {
				this.stepLink = this.links[2]; // 3rd in the index
			}
		}
		this.preload();

		if (this.photos != null) {
			this.resetTimers();
		}
	},
	preload: function() {
		if (this.photos) {
			for ( var x = 0 ; x < this.photos.length; x++ ) {
				var img = new Image;
				var button = new Image;
				img.src = this.photos[x][0];

				if (typeof(this.photos[x]) == "string") {
					button.src = this.photos[x][1];
				}
			}
		}
	},
	resetTimers: function() {
		if (!this.paused) {
			clearTimeout(this.timer);
			this.timer = setTimeout( this.toggle.bind(this), 5000); //new Timer( this.toggle.bind(this), 6.0 );
		}
	},
	getNextImageIndex: function() {
		if (this.index <= 0) {
			return (this.photos.length-1);
		}

		return (this.index-1);
	},
	toggle: function() {
		this.index = this.getNextImageIndex();
		if (typeof(this.photos[this.index]) == "string") {
			this.link.style.background = 'url(' + this.photos[this.index] + ')';
		}
		else {
			if (this.photos[this.index].length == 4)
			{
				this.link.style.background = 'url(' + this.photos[this.index][0] + ')';
				this.stepLink.style.background = 'url(' + this.photos[this.index][2] + ')';
			}
			else {
				this.link.style.background = 'url(' + this.photos[this.index][0] + ')';
				this.stepLink.style.background = 'url(' + this.photos[this.index][1] + ')';
			}
		}

		if (this.photos[this.index].length == 3) {
			this.link.href = this.photos[this.index][2];
			this.stepLink.href = this.photos[this.index][2];
		}

		if (this.photos[this.index].length == 4) {
			this.link.href = this.photos[this.index][1];
			this.stepLink.href = this.photos[this.index][3];
		}
		this.resetTimers();
	}
}

Event.observe(window, 'load', function() { 
	$$("div.slideshow").each( function(node){
		var gallery = new Gallery(node); 
	});
});
