	/*
 e24NewsRotator
	- MooTools version required: 1.2.2
	- MooTools components required: 
		Core: Fx.Tween and dependencies

	Changelog:
		- 1.0: First release
*/

/* Copyright: equipo24 S.L.N.E <http://equipo24.com/> - Distributed under MIT License - Keep this message! */

var e24NewsRotator = new Class({

	Implements: [Options],

	options: {
		container: undefined,
		width: 244,
		height: 124, 
		size: 3, 
		delay: 6000,
		duration: 3000,
		selector: '.newsitems'
	},

	initialize: function(options){	
		this.setOptions(options);
		this.container = $(this.options.container);
		this.curIndex = 0;
		
		
		this.news = $$(this.options.selector);
		this.news.each(function(el) {
			el.setStyles({
				'display': 'none'
			});
		}, this);
		
		
		this.el1 = new Element('div', {
			'id': 'news_el2',
			'style': 'position:absolute;' +
			'left: 0px;' +
			'top: 0px;' +
			'width: ' + this.options.width  + 'px;' +
			'height: ' + this.options.height  + 'px;'
		});	
		this.container.grab(this.el1);
		
		
		this.el2 = new Element('div', {
			'id': 'news_el2',
			'style': 'position:absolute;' +
			'left: 0px;' +
			'top: ' + this.options.height + 'px;' +
			'width: ' + this.options.width + 'px;' +
			'height: ' + this.options.height  + 'px;'
		});		
		this.container.grab(this.el2);
		this.el1.set('tween', {duration: this.options.duration});
		this.el2.set('tween', {duration: this.options.duration, onComplete: function() {
			this.next.delay(this.options.delay, this);			
		}.bind(this)});

		this.fill(this.el1);
		this.fill(this.el2);
		this.go.delay(this.options.delay, this, [this.el2, this.el1]);
	},

	fill: function(topEl) {
		for (var i = 0; i < this.options.size; i++) {
			this.curIndex = (this.curIndex < this.news.length)?this.curIndex+1:1;
			var el = this.news[this.curIndex-1].clone(true, true);
			el.setStyle('display', 'block');
			topEl.grab(el);
		}	
	},
	
	go: function(topEl, bottomEl) {
		bottomEl.tween('top', -this.options.height);
		topEl.tween('top', 0);
	},
	
	next: function(){
		var topEl;
		var bottomEl;
		if (this.el1.getPosition().y < this.el2.getPosition().y) {
			topEl = this.el1;
			bottomEl = this.el2;
		}
		else {
			topEl = this.el2;
			bottomEl = this.el1;		
		}
		
		topEl.empty();
		topEl.setStyles({
			'top': this.options.height
		});		
		this.fill(topEl);
		this.go(topEl, bottomEl);						
	}
	
});


