/**********************************************************************
* Image Slide Deck
*
* Author: Rick Holtz
* 
* Uses the Yahoo UI Library (v2) to cycle through images on a timer.
*
**********************************************************************/


function SlideDeck (container_el,img_list,settings) {
    this.container = container_el;
    this.settings = settings || {};
    this.imglist = img_list || [];
    this.timer = null;
    this.position = 0;
    this.render = function(){
    	if( this.container && this.imglist && this.imglist.length > 0 ){
    		
    		var first_img = this.spawnImage(0);
    		first_img.style.visibility = 'visible';
    		this.preFetch();
    		
    		// Fix scope issue
    		var self = this;
    		this.timer = setInterval(function(){self.nextImage();}, (settings.interval || 3000) );
    	}
    };
    this.nextImage = function(){
    	var new_idx = this.position + 1;
    	if( new_idx >= this.imglist.length ) new_idx = 0;
    	this.switchImage(new_idx);    	
    	this.position = new_idx;
    	this.preFetch();
    };
    this.preFetch = function(){
    	var new_idx = this.position + 1;
    	if( new_idx < this.imglist.length && typeof(this.imglist[new_idx]) == 'string' ){
    		this.imglist[new_idx] = this.spawnImage(new_idx);
    	}
    };
    this.switchImage = function(index){
    	if( index < this.imglist.length ){
    		var img_el = this.imglist[index];
    		var current_el = this.imglist[this.position];
    		if( typeof(img_el) == 'string' ) img_el = this.spawnImage(index);
    		if( img_el ){
    			img_el.style.opacity = 0;
    			img_el.style.filter = 'alpha(opacity=0)';
    			img_el.style.visibility = 'visible';
    			if( typeof(current_el) != 'string' ) current_el.style.zIndex = 1;
    			img_el.style.zIndex = 5;
    			var anim = new YAHOO.util.Anim(img_el, {
    			    opacity: {
    			    	from: 0,
    			        to: 1 
    			    } 
    			}, 1, YAHOO.util.Easing.easeOut);

    			anim.onComplete.subscribe(function(){
    				if( typeof(current_el) != 'string' ){
    	    			current_el.style.visibility = 'hidden';
    	    		}
    			});
    			anim.animate();
    		}
    	}
    };
    this.spawnImage = function(index){
    	var img_el = document.createElement('img');
    	img_el.style.visibility = 'hidden';
    	img_el.style.position = 'absolute';
    	img_el.style.top = '0';
    	img_el.style.left = '0';
    	img_el.src = this.imglist[index];
    	
    	this.container.appendChild(img_el);
    	this.imglist[index] = img_el;
    	return img_el;
    };
}
