/**
*	Gallery Version 0.01 
* 	Author: Manuel Zamora-Morschhäuser <manuel at zamora dot de>
*
*	License: LGPL latest version
*
*/

var Gallery = Class.create({
	galleryElement: null,
	images: null,
	imagesObjects: new Array(),
	currentImage: -1,
	numberOfImages: -1,
	destination: null,
	
	initialize: function(galleryElement, prefs) {

		this.images = $$('#'+galleryElement+' li img').pluck('src');
		$(galleryElement).hide();

		this.galleryElement = galleryElement;
		this.destination = prefs.destination;
		this.timer = prefs.timer;
		
		$(this.destination).addClassName('mainImage');
		this.numberOfImages = this.images.size();
		
		// Preloading
		this.images.each(function (url, index) {
			this.imagesObjects[index] = new Image();
			this.imagesObjects[index].src = url;
			// this.imagesObjects[index].hide();
			this.imagesObjects[index].id = "galleryImage"+index;
			
			$(this.destination).insert(this.imagesObjects[index]);
			$(this.imagesObjects[index].id).hide();

			
			
			if (index == 0) {
				if (typeof(this.imagesObjects[index].naturalWidth) != 'undefined' || this.imagesObjects[index].complete == true) this._nextEvent();
				else Event.observe(this.imagesObjects[index], 'load', this._firstEvent.bindAsEventListener(this));
			} else {
				if (typeof(this.imagesObjects[index].naturalWidth) != 'undefined' || this.imagesObjects[index].complete == true) {
					this.imagesObjects[index].loaded = true;
					// alert("already loaded");
				}
				else Event.observe(this.imagesObjects[index], 'load', this._loadedEvent.bindAsEventListener(this));
			}
			

			
		}.bind(this) );
		
		if (prefs.rightClick == false) {
			$(this.destination).observe('contextmenu', function(e) { e.stop(); return false;  });
		}
		
	},
	
	_loadedEvent: function(event) {
		Event.element(event).loaded = true;
	},
	
	_firstEvent: function(event) {
		this._loadedEvent(event);
		this._nextEvent(event);
	},
	
	_nextEvent: function(event) {
		if (typeof(event) != 'undefined') event.stop();
		
		// console.log(this.currentImage);
		
		if (this.currentImage == -1) {
			this.currentImage = 0;
		} else if (this.currentImage == 0 ) {
			$('galleryImage'+(this.numberOfImages-1)).fade();
		} else {
			if (this.imagesObjects[this.currentImage].loaded == false) {
				Event.observe(this.imagesObjects[this.currentImage], 'load', this._nextEvent.bindAsEventListener(this));
			} else $('galleryImage'+(this.currentImage-1)).fade();
		}
		$('galleryImage'+this.currentImage).appear();
		
		this.currentImage++;
		if (this.currentImage == this.numberOfImages) this.currentImage = 0;
		
		new PeriodicalExecuter(this._nextEvent.bindAsEventListener(this), this.timer);
		
	}
})


