var Slideshow = new Class({
	
	initialize: function(options)
	{
		this.setOptions({
			fadeDuration	: 2500,
			displayDuration	: 4500			
		}, options);										
		
		// Continue only if slideshow element is found
		if ($chk($('slideshow'))) {
			
			this.slideshow = $('slideshow');		
			this.slide_pos = 0;			
			this.old_slide_pos = null;
			this.files_loaded = 0;
			
			this.images = Array();
			this.files = null;
			
			//new Element('div', {id: 'image_container'}).addClass('ajax-indicator').injectInside('slideshow');
			
			this.slideshow_id = this.options.slideshowId;
			this.path = this.options.slideShowPath;			
			this.displayDuration = this.options.displayDuration;
			this.fadeDuration = this.options.fadeDuration;
			
			// Initialize AJAX object
			this.my_ajax = new Ajax(this.options.url, {
				method		: 'post',
				evalResponse: true,
				onRequest 	: function(){
					this.files = null;
				},
				onComplete	: function(response){
					// Continue only if files are found
					if (typeof(files) != 'undefined') {
						this.files = files;
						this.loadImages();
					}
				}.bind(this)
			});
			
			this.initSlideshow();
		}
	},
	
	initSlideshow: function()
	{
		// Read files using AJAX only if files are not found yet
		if (this.files == null) {
			// Change AJAX url depending on where we are located in the slideshow
			this.my_ajax.options.data = 'call=ajax';//+this.slides[this.slide_pos].getProperty('id');
			this.my_ajax.request();
		} else {
			this.loadImages();
		}
	},
	
	swapImage: function()
	{
		this.images[this.slide_pos].setStyle('z-index', 0);
		this.old_slide_pos = this.slide_pos;		
		this.slide_pos++;
		if (this.slide_pos>=this.files_loaded) {
			this.slide_pos = 0;
		}
		this.images[this.slide_pos].setStyle('z-index', 999);
		this.images[this.slide_pos].fx.start(1);
	},

	loadImages: function()
	{
		new Asset.images(this.files, {
						 
			onProgress: function(){
				image = new Element('img').setProperties({
					'src'	: this.files[this.files_loaded]
				}).setStyle('z-index',0).setOpacity(0).injectInside('slideshow');
				
				this.images[this.files_loaded] = image;
				this.images[this.files_loaded].fx = new Fx.Style(image, 'opacity', {
					duration:this.fadeDuration,
					onComplete: function(){
						if (this.old_slide_pos != null) {
							this.images[this.old_slide_pos].setOpacity(0);
						}
						this.swapImage.delay(this.displayDuration, this);
					}.bind(this)
				});
				this.files_loaded++;
				
				if (this.files_loaded == 1) {
					this.images[0].setStyle('z-index', 999).setOpacity(1);
				} else if (this.files_loaded == 2) {
					this.swapImage.delay(this.displayDuration, this);
				}
			}.bind(this)
		});
	}
});

Slideshow.implement(new Options);
