/**
 * Apex Framework
 * 
 * @revised $LastChangedDate: 2008-12-15 21:53:54 +0800 (Mon, 15 Dec 2008) $
 * @version $Id: FadingBanner.js 10 2008-12-15 13:53:54Z eugim $
 */

ApexFadingBanner = Class.create({
	
	id : '',

	width : '',
	
	height : '',
	
	fadeShowInterval : 6000, //6 seconds
	
	/**
		array of html, dom, object has items to be faded
	 */ 	
	items : [],

	_currentItemIndex : 0,
	
	/** 
	   the container of the widget
	 */
	_container : null,
	
	_intervalId : null,
	
	_isMouseOver : false,
		
	initialize : function(config){
		
		Object.extend(this, config);
		this._container = $(this.id).firstDescendant();
		this._container.observe('mouseover', this._handleMouseOver.bindAsEventListener(this));
		this._container.observe('mouseout', this._handleMouseOut.bindAsEventListener(this));
		this._init();
	},
	
	_handleMouseOver : function(e){
		
		this._isMouseOver = true;
		this.stopFading();
	},
	
	_handleMouseOut : function(e){
		
		this._isMouseOver = false;
		this.startFading();
	},
	
	//must be called only once, hence private
	_init : function(){
		
		if( this.items.length <= 0 ){
			return;
		}
		
		this._container.setStyle({
			overflow: 'hidden'
		});
		
		//set the first item
		this._container.update(this.items[0]);
		
		//prepare the fade/show mechanism
		this.startFading();
	},
	
	_fade : function(){
		
		var obj = this;
		this._intervalId = setInterval(function(){
			
			if( obj._isMouseOver ){
				obj._container.setOpacity(1);
				clearInterval(obj._intervalId);
				obj._container.update(obj.items[obj._currentItemIndex]);
				return;
			}
			
			if( !obj._container.opacity ){
				obj._container.opacity = .05;
			}
			obj._container.opacity = obj._container.opacity + .15;
			obj._container.setOpacity(obj._container.opacity >= 1 ? 1 : obj._container.opacity);
			
			if(obj._container.opacity > .5 && obj._container.opacity < .8){
				obj._container.update(obj.items[obj._currentItemIndex]);
			}
			
			if(obj._container.opacity >= 1){
				
				clearInterval(obj._intervalId);
				obj._container.opacity = false;
				obj.startFading();
			}
		}, 500);			
	},
	
	/**
	   toggle show/hide the fading effect
	 */	
	_toggleFadeItem : function(){
		
		this.stopFading();
		this._fade();
		
		//update the current item index
		if( this._currentItemIndex != this.items.length - 1){
			this._currentItemIndex++;
		}
		else{
			this._currentItemIndex = 0;
		}
	},
	
	/**
	   stops the fading (internally used when mouse is over an item)
	 */
	stopFading : function(){
		clearInterval(this._intervalId);
	},
	
	/**
	   starts the fading (internally used when mouse is out an item)
	 */
	startFading : function(){
		
		var obj = this;
		this._intervalId = setInterval(function(){
			obj._toggleFadeItem();
		}, this.fadeShowInterval);
	}
});