var slideshows = {};

var delay = 1000;
var start_frame = 0;

var slideshow = Class.create();
slideshow.prototype = {

	initialize : function( item ) {
		this.lis = item.images;
		this.settings = item.settings;

		this.appearEffect = 'Appear';
		this.fadeEffect = 'Fade';
		this.effectTime = 1;
		this.showTime = 5;
		this.tagName = 'li'

		if(item.settings.appear) { this.appearEffect = item.settings.appear; }
		if(item.settings.fade) { this.fadeEffect = item.settings.fade; }
		if(item.settings.time) { this.showTime = item.settings.time; }
		if(item.settings.duration) { this.effectTime = item.settings.duration; }
		if(item.settings.tag) { this.tagName = item.settings.tag; }

		// $('loading').style.display = 'none';

		this.current_frame = 0;
		this.next_frame = 1;
		this.start_frame = 0;
		this.end_frame = this.lis.length -1;

		this.start_slideshow();

	},
	start_slideshow : function() {
		$(this.settings.container).insert('<'+this.tagName+' id="'+this.settings.container+this.current_frame+'" class="sectionslideshows"><img src="'+this.lis[this.current_frame]+'"></'+this.tagName+'>');
		this.timeout = new PeriodicalExecuter( this.fadeInOut.bind(this), this.showTime);

		// Preload next image
		x = new Image();
		x.src = this.lis[this.next_frame];
	},
	fadeInOut : function() {
		// Change this to fade in and out adding new dom elements to the page.
		Effect[this.fadeEffect]($(this.settings.container+this.current_frame), { duration: this.effectTime, queue: 'end' } );

		if (this.current_frame == this.end_frame) { this.current_frame = this.start_frame; } else { this.current_frame++; }
		if (this.next_frame == this.end_frame) { this.next_frame = false; } else { this.next_frame++; }

		// Before we fade in the new element, we have to insert the image into the page...
		// ..and only if it doesn't exist already!
		if (!$(this.settings.container+this.current_frame))
		{
			// Insert current image
			$(this.settings.container).insert('<'+this.tagName+' id="'+this.settings.container+this.current_frame+'" style="display: none" class="sectionslideshows"><img src="'+this.lis[this.current_frame]+'"></'+this.tagName+'>');
			Effect[this.appearEffect]($(this.settings.container+this.current_frame), { duration: this.effectTime, queue: 'end' } );

			if (this.next_frame != false) {
				// Preload next image
				x = new Image();
				x.src = this.lis[this.next_frame];
			}
		} else {
			// We don't use this line for every image, because new images must only appear *once* they've been loaded!
			Effect[this.appearEffect]($(this.settings.container+this.current_frame), { duration: this.effectTime, queue: 'end' } );
		}
		
	}
}

function init_slideshows()
{
	var i=0;
	if(typeof simpleSlideShowShows=='undefined') { return ; }

	simpleSlideShowShows.each(
		function ( item ) {
			//alert(item.settings.container);
			var n = 'show'+i;
			slideshows.n = new slideshow( item );
			i++;
		}
	);
}


document.observe('dom:loaded', init_slideshows, false);