/*	---------------------------------------------------------------------------
	CLASS:		FlipDeck (el,items,[speed,delay,visibleitems]);
	OPTIONS:	speed:			the transition speed (default:500)
				delay:			the amount of time a news item stays at a position (default: 5000)
				visibleItems:	the number of items to show in a single frame (default:3)
	AUTHOR:		Ryan J. Salva
	EMAIL		ryan at capitolmedia.com
	REVISED:	Decembe 16, 2009
*/
 
var FlipDeck = new Class({
	Implements: [Events, Options],
	options: {
		speed: 1000,
		delay: 10000,
		visibleItems: 1,
		onComplete: $empty,
		onStart: $empty
	},
	initialize: function(el,items,options){
		this.setOptions(options);
		this.el = el;
		this.items = items;
		this.visibleItems = this.options.visibleItems;
		this.sets = [];
		this.anchors = [];

		this.showing = 0;
 
		var i = this.visibleItems;
		var deck;
		this.items.each(function(item,index) {
			if (i >= this.visibleItems) {
				i = 0;
				deck = new Element('div',{
					'styles':{
					'position': 'absolute',
						'top':0,
						'left':0,
						'opacity':0
					},
					'tween':{
						'link':'cancel',
						'duration':this.options.speed
					}
				});
				this.sets.include(deck);
				this.el.adopt(deck);
			}
			deck.adopt(item);
			i++;
		}.bind(this));
		this.pagination = this.paginate();
		this.show(0);
	},
	
	play: function() {
		this.timer = this.next.periodical(this.options.delay,this);
	},
	
	show: function(deck) {
		this.sets[this.showing].tween('opacity',0);
		this.showing = deck;
		this.sets[this.showing].tween('opacity',1);
		this.flip();
		$clear(this.timer);
	},
	
	flip: function() {
		this.anchors.each(function(el,index) {
			el.removeClass('active');
		});
		if (this.anchors[this.showing]) this.anchors[this.showing].addClass('active');	
	},
	
	paginate: function() {
		var div = new Element('div',{'class':'pagination'});
		this.sets.each(function(s,index) {
			var a = new Element('a',{
				'href':'#',
				'text':index+1,
				'events':{
					'click': function() {
						this.show(index);
					}.bind(this)
				}
			});
			this.anchors.push(a);
			div.adopt(a);
		}.bind(this));
		return div;
	},
	
	next: function() {
		this.sets[this.showing].tween('opacity',0);
		this.showing = (this.showing >= this.sets.length-1)?0:this.showing+1;
		this.sets[this.showing].tween('opacity',1);
		this.flip();
	},
	
	previous: function() {
		this.sets[this.showing].tween('opacity',0);
		this.showing = (this.showing <= 0)?this.sets.length-1:this.showing-1;
		this.sets[this.showing].tween('opacity',1);
		this.flip();
	}
	
});
