/**
  * @author Hannes Lau <office@hanneslau.de>
  *
  */
var ImageBrowser = new Class({
	Implements: Options,

	options: {
		images : null, // array of URLs of images to display
		current : 0, // index of the image currently displayed in the images array
		display : null, // IMG element to display images with
		nextBtn : null,
		prevBtn : null
	},
	
	/**
	  * Update the visibility of the next and prev button. 
	  * The buttons will only be visible if there is an
	  * preloaded next/prev image to navigate to. 
	  */
	buttonVisibility : function() {
		var prevVisible = 
			(this.current > 0)
			&& $chk(this.imagesLoaded[this.current-1])
		;
		
		var nextVisible = 
			(this.current < this.options.images.length-1)
			&& $chk(this.imagesLoaded[this.current+1])
		;
		
		this.options.prevBtn.style.display = (prevVisible?"block":"none");
		this.options.nextBtn.style.display = (nextVisible?"block":"none");		
	},

	showImage : function(index) {
		if($chk(this.imagesLoaded[index])) {
			/*
			 * image index has already been preloaded: 
			 * replace the display with the new image
			 */
			this.display = this.imagesLoaded[index].replaces(this.display);
		} else {
			/*
			 * fallback: change the src of the existing image
			 * instead of replacing the entire img element. this
			 * will cause the webbrowser to show the image as 
			 * soon as the loading proccess completes. 
			 */
			this.options.display.src = this.options.images[index];
		}
		
		this.current = index;
		this.buttonVisibility();
	},

	initialize : function(options) {		
		this.setOptions(options);

		this.display = this.options.display;
		this.current = this.options.current;
		
		this.imagesLoaded = [];

		this.buttonVisibility();

		// preload images
		var imageBrowser = this;
		new Asset.images(this.options.images, {
			onProgress: function() {
				/*
				 * An image has just completed loading:
				 * Get the index of this image in the "images" array
				 * and add it to the "imagesLoaded" array at the same
				 * position. 
				 */
				// match the url of image just loaded against the list of all images to laod
				var staticURL = window.location.protocol + "//" + window.location.hostname + "/";
				var relURL = this.src.substr(staticURL.length-1);
				var index = imageBrowser.options.images.indexOf(relURL);
				
				imageBrowser.imagesLoaded[index] = this;				
				imageBrowser.buttonVisibility();				
			},
			onComplete : function() {
				imageBrowser.buttonVisibility();
			}.bind(this)
		});

		
		// add event handlers to the prev and next buttons
		this.options.prevBtn.addEvent('click', function(event) {
			this.showImage(this.current-1);
			event.preventDefault();
		}.bind(this));

		this.options.nextBtn.addEvent('click', function(event) {
			this.showImage(this.current+1);
			event.preventDefault();
		}.bind(this));
		
		this.options.prevBtn.style.cursor = "pointer";
		this.options.nextBtn.style.cursor = "pointer";
	}
});
