/*
---

name: Wallpapers.SlideShow

description: Wallpapers turned into a slideshow with Ryan Florence's SlideShow (https://github.com/rpflorence/SlideShow) with image preloading

authors: Rolf Langenhuijzen

license: MIT-style license.

requires: [Wallpapers, SlideShow.ImagePreloading]

provides: Wallpapers.SlideShow

...
*/

;(function(){

Wallpapers.SlideShow = this.Wallpapers.SlideShow = new Class({

	Extends: Wallpapers,

	isPlaying: false,

	options: {
		durationbar: false,
		slideshowOptions: {
			delay: 8000,
			transition: 'crossFade',
			duration: 500,
			autoplay: false
		}
	},

	initialize: function(container, options){
		this.container = document.id(container);
		var slideshowOptions = Object.merge({imageAsBackground: options.useCSS != null ? options.useCSS : false}, Object.merge(this.options.slideshowOptions, options.slideshowOptions));
		this.slideshow = new SlideShow.ImagePreloading(this.container, slideshowOptions, true);
		this.slideshow.addEvents({
			play: function(){
				this.isPlaying = true;
			}.bind(this),
			pause: function(){
				this.isPlaying = false;
			}.bind(this)
		});

		if (window.ProgressBar && options.durationbar) this.setupDurationbar();

		this.parent.apply(this, arguments);
	},

	process: function(stack){
		this.parent(stack);

		stack.each(function(wallpaper){
			new Element('div').set('data-slide', wallpaper).inject(this.container, 'bottom');
		}.bind(this));

		this.slideshow.setup();

		return this;
	},

	show: function(wallpaper){
		if (wallpaper == 'next' || wallpaper == 'previous') wallpaper = this[wallpaper]();
		if (typeof wallpaper == 'number') wallpaper = this.stack[wallpaper];
		if (wallpaper == this.current) return this;

    if (this.isPlaying) this.pause();

		var index = this.current = this.stack.indexOf(wallpaper);
		this.slideshow.show(index);

		if (!this.rendered) this.rendered = true;

		return this;
	},

	play: function(){
		if (this.stack.length > 1) this.slideshow.play();
		return this;
	},

	pause: function(){
		this.slideshow.pause();
		return this;
	},

	setupDurationbar: function(){
		this.durationbar = new ProgressBar(this.container.getParent(), {
			cssClassPrefix: 'wallpapers',
			cssClass: 'Progressbar',
			morphOptions: {
				duration: this.options.slideshowOptions.delay - this.options.slideshowOptions.duration
			}
		});
		this.slideshow.addEvents({
			play: function(){
				this.durationbar.show().start();
			}.bind(this),
			pause: function(){
				this.durationbar.stop().hide();
			}.bind(this),
			show: function(){
				if (this.isPlaying) this.durationbar.stop().hide();
			}.bind(this),
			showComplete: function(){
				if (this.isPlaying) this.durationbar.show().start();
			}.bind(this)
		});
		return this;
	}

});

})();
