/**
* Class Effect.SlideShow
*
*/

Effect.SlideShow = Class.create();
Object.extend(Object.extend(Effect.SlideShow.prototype,
Effect.Base.prototype), {

	// Constructor
	initialize: function(element) {
		this.element = $(element);
		this.options = Object.extend({
			duration:       arguments[2],
			slidetime:      arguments[1],
			imagelinks:     arguments[3],
			images:     new Array()
			});

		var dummy = new Array();
		// load all the pictures into the image cache
		for (i=0; i<this.options.imagelinks.length; i++) {
			dummy[i] = new Element('img', { src: this.options.imagelinks[i] });
		}
		this.options.images = dummy;

		// Create child nodes with images
		var frontimagediv = new Element('div', {id: 'frontimage'});
		var backimagediv = new Element('div', {id: 'backimage'});

		// Update styles and position
		frontimagediv.setStyle({
			height:Element.getStyle(this.element, 'height'),
			width:Element.getStyle(this.element, 'width'),
			top:Element.getStyle(this.element, 'top'),
			left:Element.getStyle(this.element, 'left'),
			position:'absolute',
			display:'inline-block'
		});

		backimagediv.setStyle( {
			height:Element.getStyle(this.element, 'height'),
			width:Element.getStyle(this.element, 'width'),
			top:Element.getStyle(this.element, 'top'),
			left:Element.getStyle(this.element, 'left'),
			position:'absolute',
			display:'inline-block'
		});

		// Load images into front and back divs
		frontimagediv.update(this.options.images[0]);
		backimagediv.update(this.options.images[1]);

		// load divs into page
		this.element.insert(backimagediv);
		this.element.insert(frontimagediv);

		this.imagecursor = 2;
		this.pe = new PeriodicalExecuter(this.shownext.bind(this),this.options.slidetime);
	},

	// Show Next Image
	shownext: function() {
		new Effect.Fade($('frontimage').firstDescendant(), {
			duration:this.options.duration,
			afterFinish: this.onappearfinish.bind(this)
		});
	},

	// Appear effect onfinish callback
	onappearfinish: function() {
		// Copy contents of back div to front div
		$('frontimage').update($('backimage').firstDescendant());

		// Make front div visible
		$('frontimage').firstDescendant().show();

		// load back div with the next image
		if(this.imagecursor >= this.options.imagelinks.length){
			this.imagecursor = 0;
		}

		$('backimage').update();
		$('backimage').update(this.options.images[this.imagecursor]);
		this.imagecursor++;
		backimage = $('backimage').firstDescendant();
		backimage.show();
	}

});
