

var NewsModule = Class.create({
	
	element: null,
	pager: null,
	slider: null,
	current_index: 0,
	max_index: null,
	rotate_intervalID: null,
	
	slideTimout: null,
	slideInterval: (5*1000),
	
	initialize: function( element ) {
		this.element = $(element);
		if (!this.element) throw(Effect._elementDoesNotExistError);
		
		this.setup();
	},
	
	setup: function() {
		this.pager = $(this.element.getElementsBySelector('div.pager')[0]);
		this.slider = this.element.getElementsByClassName('slider')[0];
		
		var scope = this, panelHeight = 0;
		
		// Set same height:
		this.slider.down().childElements().each(function(panel) {
			var h = panel.getHeight();
			if ( h > panelHeight ) panelHeight = h;
		}).invoke('setHeight', panelHeight);
		
		// Add pager behavior:
		this.max_index = 0;
		$A(this.pager.childElements()).each(function(anchor) {
			scope.max_index++;
			$(anchor).onclick = function() {
				scope.scroll(this);
				return false;
			};
		});
		
		// URL Anchors
		if ( window.location.hash.match(/^#promo_/) ) {
			var panel = $(window.location.hash.substring(1));
			if ( panel ) {
				var panelIndex = this.slider.down().childElements().indexOf(panel);
				if ( panelIndex != -1 ) this.setPosition(panelIndex);
			}
		}
		
		// Lauch slide
		this.slideTimeout = setTimeout(this.slide.bind(this), this.slideInterval);
		this.element.observe('click', function() {
			clearTimeout(this.slideTimeout);
		}.bindAsEventListener(this));
	},
	
	slide: function() {
		clearTimeout(this.slideTimeout);
		var index = this.current_index + 1;
		this.scrollTo((index >= this.max_index ? 0 : index));
		this.slideTimeout = setTimeout(this.slide.bind(this), this.slideInterval);
	},
	
	scroll: function(anchor) {
		if ( !Object.isElement(anchor) )
			throw (Effect._elementDoesNotExistError);
		
		// Find index of the current anchor:
		this.scrollTo(this.pager.childElements().indexOf(anchor));
	},
	
	scrollTo: function(index) {
		this.current_index = index;
		
		// Calculate y position of arrow background & scrollOffset of content:
		var scrollOffset = this.element.getWidth() * this.current_index;
		
		// Animate:
		new Effect.ScrollHorizontal(this.slider, {
			to: scrollOffset,
			afterFinish: function() {
				this.pager.childElements().invoke('removeClassName', 'selected');
				this.pager.childElements()[this.current_index].addClassName('selected');
			}.bindAsEventListener(this)
		});
	},
	
	setPosition: function(index) {
		this.current_index = index;
		this.slider.scrollLeft = this.element.getWidth()*index;
		this.pager.childElements().each(function(element) {
			element.removeClassName('selected');
		});
		this.pager.childElements()[index].addClassName('selected');
	}
});

