/*
Image Gallery Slideshow for use with EPIC CMS. Developed by R&D Eurotech. 17/Nov/2008
Requires the Prototype JS library 1.6
*/
var EPIC_slide = Class.create({
	initialize: function(div_id, images, interval) {
		var self = this;
		
		// set up slideshow properties
		this._position = 0;
		this._opacity = 0;
		this._interval = interval;
		this._images = images;

		// add HTML to div.
		this._div = $(div_id);
		this._img = new Element('img', { src: images[0].image, alt: images[0].name }).observe('load', function() {
				self._image_aspect_ratio = (self._image_aspect_ratio != null ? self._image_aspect_ratio : (self._img.getHeight() / self._img.getWidth()));
				
				var last_parent_container_id = self._parent_container != null ? self._parent_container.id : false;
				self._parent_container = self.find_parent_container(self._div);
				if (self._parent_container.id != last_parent_container_id) {
					self._img.style.display = 'none';
					self._container_width = self._parent_container.getWidth();
					self._img.style.display = 'block';
				}
				
				self._img.width = self._container_width;
				self._img.height = Math.round(self._image_aspect_ratio * self._container_width);
			} );
			
		this._div.insert(this._img);
		
		// set up readycheck for transition
		this._intervalTriggered = false;
		this._imgsrcReady = false;
		
		// ready, steady... go!
		this.fade_callback();
	},
	
	find_parent_container: function(container) {
		var parent = $(container.parentNode);
		if (parent.hasClassName('container'))
			return parent;
		else
			return this.find_parent_container(parent);
	},
	
	fade_next: function() {
		this._position++;
		if (this._position >= this._images.length) this._position = 0;
		
		this.set_opacity(this._img, 0);
		this._img.alt = this._images[this._position].name;
		this._img.src = this._images[this._position].image;
		
		this.fade();
	},

	fade: function() {
		if (this._opacity < 1) {
			this._opacity += 0.1;
			this.set_opacity(this._img, this._opacity);
			var self = this;
			setTimeout(function() { self.fade(); }, 40);
		} else {
			this._opacity = 0;
			this.fade_callback();
		}
	},
	
	set_opacity: function( obj, amt ) {
		obj.style.opacity = amt;
		obj.style.MozOpacity = amt;
		obj.style.filter = "alpha(opacity=" + (amt*100) + ")";
	},
	
	fade_callback: function() {
		var self = this;
		setTimeout(function() { self._intervalTriggered = true; self.transition_readycheck(); }, this._interval);
		
		var tmpImg = new Element('img');
		Event.observe(tmpImg, 'load', function () { self._imgsrcReady = true; self.transition_readycheck(); });

		var nextpos = this._position+1;
		if (nextpos >= this._images.length) nextpos = 0;
		tmpImg.src = this._images[nextpos].image;
	},
	
	transition_readycheck: function() {
		if (!this._imgsrcReady || !this._intervalTriggered)
			return false;
		
		this._imgsrcReady = false;
		this._intervalTriggered = false;
		this.fade_next();
	}
});