
window.addEvent('domready', function(){
	
	new Carousel('carousel');
	
});

var Carousel = new Class({
	
	Extends: MerryGoRound,
	
	options: {
		wrapper_options: {
			'class': 'carousel',
			'styles': {
				'overflow': 'hidden'
			}
		},
		per_page: 1,
		previous_button_options: {
			'class': 'prev'
		},
		next_button_options: {
			'class': 'next'
		},
		page_controls: true,
		page_controls_options: {
			'class': 'dots'
		},
		current_page_class: 'current',
		fx_options: {
			duration: 750,
			transition: 'quad:out'
		}
	},
	
	initialize: function(elem, options){
		this.parent(elem, options);
		
		this.riders_info = this.riders.map(function(rider){
			var text = rider.getElements('h3, p');
			text.each(function(el, i){
				el.set('tween', {duration: 150 + i * 250}).fade('hide');
			});
			
			return {
				text: text,
				left: rider.getElement('h2').getStyle('left')
			};
		}, this);
		
		this.heading = new Element('h2', {
			tween: this.options.fx_options
		}).inject(this.element);
		
		this.width = this.element.getWidth();
		
		this.scroll.addEvent('complete', this.onScroll.bind(this));
		this.onScroll();
		this.move_heading(0);
	},
	
	onScroll: function(){
		this.riders_info[this.current_index].text.each(function(el, i){
			el.fade.delay(i * 300, el, 'in');
		});
	},
	
	move_heading: function(page_index){
		this.heading.tween(this.riders_info[page_index].left);
	},
	
	scroll_to_page: function(page_index){
		this.move_heading(page_index);
		
		this.riders_info[this.current_index].text.cancel().fade('hide');
		
		this.parent(page_index);
	},
	
	// there were rounding errors
	_calculate_scroll: function(){
		return -this.current_index * this.width;
	}
	
});


Element.implement({
	
	cancel: function(){
		var fx = this.get('tween') || this.get('morph');
		fx.cancel();
		return this;
	}
	
});
