(function( $, undefined ) {

	$.widget( "ui.slideshow", {
		
		version: "@VERSION",
		
		options: {
			fadeDuration: 2000,
			waitDuration: 5000
		},
		
		loadedImages: [],
		index: 0,
		
		_create: function() {
			var $this = this;
						
			$({}).imageLoader({
				images: $this.options.images,
				async: true,
				complete: function(e, ui) {
					$this.loadedImages.push($this.options.images[ui.i]);
				}
			});
			
			// Start the interval that checks for loaded images to display.
			// If there are none, do nothing. Otherwise show the image and
			// wait a preconfigured amount of time before trying to load another.
			$this.fadeInterval = setInterval(function() {

				if ($this.loadedImages[$this.index] != null){
					var oldImage = $this.element.find('img');
					var newImage = $('<img src="' + $this.loadedImages[$this.index] + '" style="display: none; opacity: 0" />');
					
					$this.index += 1;
					
					if ($this.index == $this.options.images.length){
						$this.index = 0;
					}
					
					$this.element.append(newImage);
					
					newImage.show().animate(
					{
						opacity: 1
					}, 
					{
						duration: $this.options.fadeDuration,
						complete: function(){
							oldImage.remove();
						}
					});
				}
				
			}, $this.options.waitDuration);
		},

		_init: function() {		

		},

		_destroy: function() {
			$.Widget.prototype.destroy.apply( this, arguments );
		},

	});

})( jQuery );

