/* Image slideshow */
/* 
<script src="/misc/slideshow.js"></script>
<img id="rotating-images" src="http://farm4.static.flickr.com/3601/3300773637_22d9ede58b_m.jpg" width="240" height="180">

<script>
var images = new Array('http://farm4.static.flickr.com/3601/3300773637_22d9ede58b_m.jpg',
	'http://farm4.static.flickr.com/3568/3300766845_a15ea78c71_m.jpg',
	'http://farm4.static.flickr.com/3379/3301582780_469544d88f_m.jpg',
	'http://farm4.static.flickr.com/3391/3300755229_0a6470189e_m.jpg');

new SlideShow({id: 'rotating-images', images: images, transition: 0.5, width: 240, height: 180});
</script>
*/

var SlideShow = new Class.create();
SlideShow.prototype = {
	
	initialize: function(args){
		// Id of the image to rotate
		this.id = args.id;

		// Array of images
		this.images = args.images;

		// Delay between rotations
		this.delay = args.delay ? args.delay : 2;

		// Size of area
		this.height = args.height;
		this.width = args.width;

		// Seconds to transition between one image and the next
		this.transition = args.transition ? args.transition : 1;

		// Private
		this.id2 = this.id + '2';
		this.index = 0;
		this.direction = 1;

		// Start the show (once the page is fully loaded)
		Event.observe(window, 'load', this.start.bind(this));
	},
	
	// Start the show
	start: function() {

		// Preload
		images.each(function(src) {
			var preloader = new Image();
			preloader.src = src;
		});

		// Wrap a DIV around the first image
		var i1 = $(this.id);
		i1.style.width = this.width + 'px';
		i1.style.height = this.height + 'px';
		var style = 'height:' + this.height + 'px; width:' + this.width + 'px';
		i1.wrap('div', {'style': style});
		i1.style.position = 'absolute';

		// Add the second image
		i1.insert({after: '<div><img id="' + this.id2 + '" style="' + style + '"></div>'});
		var i2 = $(this.id2);
		i2.style.opacity = 0.01;
		i2.style.filter = 'alpha(opacity=1)';
		i2.style.position = 'absolute';
		i2.style.left = getRealLeft(i1);
		i2.style.top = getRealTop(i1);
		i2.src = this.images[1];

		setInterval(this.next.bind(this), this.delay*1000);
	},

	next: function() {
		this.index++;
		if (this.index >= this.images.length) {
			this.index = 0;
		}

		if (this.direction == 1) {
			$(this.id2).src = this.images[this.index];
			Effect.Fade(this.id, {to: 0.01, duration: this.transition})
			Effect.Fade(this.id2, {to: 1, duration: this.transition})
			this.direction = 0
		}
		else {
			$(this.id).src = this.images[this.index];
			Effect.Fade(this.id2, {to: 0.01, duration: this.transition})
			Effect.Fade(this.id, {to: 1, duration: this.transition})
			this.direction = 1
		}
	}
}
