ensurePackage('guardian.r2');

guardian.r2.newsTicker = function () {
	var speed = 5000; //change every 5 secs; TAKE INTO ACCOUNT THE FADE TIME THOUGH!
	var count = 0;
	var paused = false;
	var newsHeadlines = jQ('ul#ticker li'); //get the headlines
	var instance = this;
	
	this.changeStory = function(direction, hover) {
		var currentItem = jQ(newsHeadlines).eq(count);
		var newItem;
		
		timer = window.clearTimeout(timer);
		switch (direction) {
			
			case 'back' :  //previous
				if(paused) { 
					paused = false; //make sure we unpause when clicking next or previous
				}
				//decrement the count; go to the end if we've reached the first one
				(count === 0) ? count = newsHeadlines.length-1 : count--;
				//get the previous item 
				newItem = newsHeadlines.eq(count);
				break;		

			case 'pause' : //next
				if(!paused) {
					paused = true;
					break;
				} else {
					paused = false;
				}

			default : 	//next - or the default
				if(paused) { 
					paused = false;
				}
				//increment the count; set to 0 if we're at the end
				(count === newsHeadlines.length-1) ? count = 0 : count++;
				//get the next one
				newItem = newsHeadlines.eq(count);
				break;
		}
		if(!paused) {
			currentItem.fadeOut(250, function() {
				newsHeadlines.hide();
				newItem.fadeIn(250);				
			});
			timer = window.setTimeout(instance.changeStory, speed);
		}
	};

	this.hoverPause = function() {
		if(timer) { 
			timer = window.clearTimeout(timer);
		} else {
			timer = window.setTimeout(instance.changeStory, 2000);
		}
	};
	
	//set up event handlers
	jQ('p#ticker-controls input').click( function() {		
		var direction = jQ(this).attr('alt');
		instance.changeStory(direction);
	});

	newsHeadlines.hover(this.hoverPause, this.hoverPause);
	
	//set the timer running
	var timer = window.setTimeout ( this.changeStory, speed);
};	

jQ(document).ready(function() {
	var myTicker = new guardian.r2.newsTicker();
});
