/*
---

name: SlideShow.ImagePreloading

description: Extension for Ryan Florence's SlideShow (https://github.com/rpflorence/SlideShow)

authors: Rolf Langenhuijzen

license: MIT-style license.

requires: [SlideShow, More/Assets]

provides: SlideShow.ImagePreloading

...
*/

SlideShow.ImagePreloading = new Class({

	Extends: SlideShow,

	options: {
		/*
		onLoadImage: function(){},
		onLoadImageComplete: function(){},
		onLoaded: function(){},
		*/
		imageAsBackground: false
	},

	initialize: function(){
		this.parent.apply(this, arguments);
		this.isLoading = false;
	},

	loadImage: function(index, showOnload, options){
    this.isLoading = true;
		var slide = this.slides[index];
		if (this.slideLoaded(slide)){
			this.loadImageComplete(index, showOnload, options);
		} else {
  		this.fireEvent('loadImage', [slide, index]);
			new Asset.image(slide.get('data-slide'), {
				onload: function(image){
					if (!this.options.imageAsBackground){
						slide.grab(image);
					} else {
						new Element('div', {
							styles: {
								'background-image': 'url(' + image.get('src') + ')'
							}
						}).inject(slide);
						/*
						Needs testing... doesn't working properly atm...
						slide.setStyle('background-image', 'url(' + image.get('src') + ')');
						slide.eliminate('slideshow:oldStyles').store('slideshow:oldStyles', slide.get('style'));
						*/
					}
					slide.store('loaded', true);
					this.loadImageComplete.delay(10, this, [index, showOnload, options]);
				}.bind(this)
			});
		}
	},

	loadImageComplete: function(index, showOnload, options){
	  this.isLoading = false;
		if (showOnload) this.show(index, options);
		this.fireEvent('loadImageComplete', [index, options]);
	},

	slideLoaded: function(slide){
		return slide.retrieve('loaded') ? true : false;
	},
	
	show: function(slide, options){
		if (this.isLoading || this.transitioning) return this;

		if (slide == 'next' || slide == 'previous') slide = this[slide + 'Slide']();
		if (typeof slide == 'number') slide = this.slides[slide];

		if (this.slideLoaded(slide)) this.parent(slide, options);
			else this.loadImage(this.slides.indexOf(slide), true, options);

		return this;
	}

});
