window.addEvent("domready", function() {
	
	var newsContent = $("news_sidebar_scroller");
	var newsScroller = new scroller(newsContent, 0);
	newsScroller.start();
	
});


function scroller(element, JoomlaDN) {						 
	
	this.element = element; // The parent element
	this.element.setStyles('position: relative'); // Set styles for the parent
	
	// JoomlaDN = means we're using a module in Joomla that doesn't output all the required div elements
	this.JoomlaDN = JoomlaDN; 
	
	if (this.JoomlaDN) {
		// Make a new div to wrap the contents in
		this.container = new Element('div', {
						'styles': { // Set its styles here as well
							'position': 'absolute', 'top': 0
						}
					});
	}
	
	// Scroll properties	
	this.durationCONST = 12000;
	this.height = this.element.getFirst().getSize().size.y;
	this.baseHeight = this.element.getSize().size.y;
	
	
	// Initialise inner div and its styles
	// Add pause & resume event handlers
	this.start = function() {
		
		if (this.JoomlaDN) { // Put contents inside new inner container
			this.element.getChildren().injectInside(this.container);
			this.container.injectInside(this.element);
			
			// Get the real height now we can test the inner div
			this.height = this.element.getFirst().getSize().size.y;
			
		} else {
			// Set the styles of the inner div if we didn't create it earlier
			this.element.getFirst().setStyles('position: absolute; top: 0;');
		}
		
		// Set pause & resume handlers
		this.element.addEvent('mouseover', function(){this.scroll.stop();}.bind(this)); 
		this.element.addEvent('mouseout', function(){this.scrollUp();}.bind(this)); 
		
		this.scrollUp(); // Scroll it!
	}
	
	// Start the scroll! [method]		
	this.scrollUp = function() {
		// Are we at the top or the bottom of the div before we start scrolling?
		var currentPos = this.element.getFirst().getStyle('top');
		
		// Set the duration based on how far the scroll has to go
		this.duration = ((parseInt(currentPos) + this.height) / this.height) * this.durationCONST;
		
		this.scroll = new Fx.Style(this.element.getFirst(), 'top', {
			duration: this.duration,
			transition: Fx.Transitions.linear,
			onComplete: (this.reposition).bind(this)
		});
				
		if (this.height > this.baseHeight) { // Don't scroll if there's nothing else to see
			this.scroll.start(currentPos, 0 - this.height);
		}
	}
	
	// Reset to the bottom of the div [method]
	this.reposition = function() {		
		this.scroll.set(this.baseHeight);
		this.scrollUp();
	}
	

};

