/**
 * Photo Gallery Component 2
 * MooTools Framework
 * Pellucid Designs, 2008 <info@unclouded.com>
 */

/**
 * Array of Objects copying format fouund in Cake model
 * images[0] = {'id':12, 'title':'caption'; }
 */
//var images = [
//	{"id":"409",
//"item_id":"83",
//"title":"",
//"description":"",
//"size":"1408498",
//"type":"image/pjpeg",
//"filename":"00804-X Dancing pix 1 -054.jpg",
//"created":"2008-04-30 12:35:42",
//"created_by":"11",
//"modified":"2008-04-30 12:35:46",
//"modified_by":"11",
//"order":"314",
//"visible":"1"}
//];

/**
 * Wait until DOM has loaded
 * 
 * @param {Object} images
 */
window.addEvent('domready', function(){
	
	var srcPrefix = '/thumbnail.jpg?w=500&sy=109&sh=157&src='+prefix;
	var frames = [							// Images that will hold slides
		$('front-splash-1'),
		$('front-splash-2')];	
	var frameIndex = 0;					// Index of the presently visible holder frame
	var imageIndex = -1;					// Location in master stack of all images
	
	// -------------------------------------------------------------
	var fading = false;						// True during transition
	
	loadNextImage();
	setInterval( loadNextImage, 5000 );
		
	/**
	 * Load image with given index into viewer
	 * 
	 * @param {Object} imageIndex
	 */
	function loadNextImage(){		
		
		if( imageIndex < (images.length - 1)){
			showSlide( imageIndex + 1 );
		}
		else{
			showSlide( 0 );
		}	
	}
	
	/**
	 * Fade out present image, load next image, and fade back in
	 */
	function showSlide( iToShow ){
		if( fading ){
			return;
		} 
		window.status = "Loading image "+iToShow;
		
		var currentSlide = frames[frameIndex];
		var nextSlide = frames[((frameIndex==1)?0:1)];
		var nextSrc = srcPrefix + images[iToShow].id;
		
		var fadeIn = function(s){
			fading = true;
			s.setStyles({
				display:'block',
				visibility: 'visible',
				opacity: 0
			});
			
			s.get('tween').start('opacity', 1).chain(function(){
                    fading = false;
                    this.fireEvent('onShow', [imageIndex]);
					
					// Move to next slide in list
					imageIndex = (imageIndex < (images.length - 1))?imageIndex+1:0;
					
					// Toggle active image
					if( frameIndex ){
						frameIndex = 0;
					}
					else{
						frameIndex = 1;
					}
            });
			
		}
		
		if ( nextSlide ) {
			if( imageIndex != iToShow ){
				fading = true;
				nextSlide.set('src', nextSrc );
				
				currentSlide.get('tween').start('opacity',0).chain(function(){
					currentSlide.setStyle('display','none');
					fadeIn(nextSlide);
				})
			}	
		}
	}
	
	
	
	// loadData();
	
});
