//Namespace
if (typeof EnergyApps == "undefined"){ EnergyApps = { Ticker: {} } }
if (typeof EnergyApps.Ticker == "undefined"){ EnergyApps.Ticker = {}; }


/**
 * @class EnergyApps.Ticker
 * @namespace EnergyApps
 * @extends Publicis.Observable
 * @author Jonas Bach
 * @author Sebastian Sauer
 * @constructor
 */

EnergyApps.Ticker = function ( config ) {
	EnergyApps.Ticker.superclass.constructor.call( this, config );

	/**
	 * @cfg {String} proxy required
	 */
	if( ! config.proxy ) {
		return;
	}
	/**
	 * @cfg {Element} tickerLink default: $('pub_ticker').down('p a')
	 */
	config.tickerLink = ( !! config.tickerLink )
		? config.tickerLink
		: $('pub_ticker').down('p a');

	/**
	 * @cfg {Number} duration default: 5
	 */
	config.duration = ( parseInt( config.duration, 10 ) > 0 )
		? parseInt( config.duration, 10 )
		: 5 ;
		
	config.url = config.url ? encodeURI( config.url ) : "";

	/**
	 * @cfg {Number} truncate default: 110
	 */
	config.truncate = ( parseInt( config.truncate, 10 ) > 0 )
		? parseInt( config.truncate, 10 )
		: 110 ;

	this.config = config;

	this._init();
}

Publicis.extend(EnergyApps.Ticker , Publicis.Observable, {
	/**
	 * read JSON & initialize cycling
	 * @private
	 */
	_init: function(){
		if(this._elements === undefined){
			// request newsletter elements
			new Ajax.Request(this.config.proxy, {
				method:'post',
				parameters : {
					url : this.config.url
				},
				onSuccess: function(transport){
					this._elements = transport.responseText.evalJSON();
					this._init();
				}.bind(this)
			});
		}else{
			// process newsletter elements
			this._active = -1;
			this._cycleTimer = false;
			this._link = $(this.config.tickerLink);

			// stop slideshow on mouseenter, proceed on mousleave
			this._link.observe('mouseenter', this._stopCycle.bind(this));
			this._link.observe('mouseleave', this._startCycle.bind(this));

			// start the cycle
			this._next();
			this._startCycle();
		}
	},

	_startCycle: function(){
		this._cycleTimer = new PeriodicalExecuter(function(){
			this._next();
		}.bind(this), this.config.duration);
	},

	_stopCycle: function(){
		this._cycleTimer.stop();
	},

	_next: function(){
		if(this._active < this._elements.length-1){
			this._active++;
		}else{
			this._active = 0;
		}
		var active = this._elements[this._active];

		// hide link
		this._link.addClassName('active');
		this._link.writeAttribute('href', active.link || "javascript:;");
		this._link.writeAttribute('target', '_blank');

		// update link data
		window.setTimeout(function(){
			this._link.writeAttribute('title',active.description);
			this._link.update(active.title.truncate(this.config.truncate, '…'));
			this._link.removeClassName('active');
		}.bind(this), 300);

	}
});

