$(function(){
	
	
	/*
	
	Setup
	-----------
	Hide the articles not being used
	Set the width of #headlines .ticker to not wrap
		-This needs to be done every time an article loads
	
	Tasks
	------------
	1.	Position the #ticker content to the right beyond the visable point
	2.	Move it in from right to left until the 
		last point of it reaches the right hand side of the wrap
	3. 	When the mouse moves over it stop the scroll
	4. 	Load the next story
	5.	Load the previous story
	
	
	*/
	
	/***** SETUP *****/
	//Hide the articles not being used
	$('.ticker').hide()
	$('.ticker.current_ticker').show()
	
	//Set the width of #headlines .ticker to not wrap
	set_width($('.current_ticker'))
	
	//Setup variables
	sliding = false;
	total = $('.ticker').length
	ticker_count = 1
	
	//1.	Position the #ticker content to the right beyond the visable point
	//2.	Move it in from right to left until the 
	//		-last point of it reaches the right hand side of the wrap
	position_ticker($('.current_ticker'))
	
	
	//3. 	When the mouse moves over it stop the scroll
	$('.current_ticker').mouseover(function(e){
		//	If it's still sliding then stop it
		// 	-and the the sliding variable to false????
		if(sliding){
			$(this).stop();
		}
	})
	$('.current_ticker').mouseout(function(){
		//	If it's still not at the finish point continue the slide
		if($(this).css("marginLeft") != $('#ticker_wrap').width() - $(this).width()){
			slide($(this))
		}
	})
	
	
	//4. 	Load the next story
	$('#headline_next').click(function() {
		
		if(ticker_count < total){
			n = $('.current_ticker').next()
			
			$('.current_ticker').stop().css({
				marginLeft: $('#ticker_wrap').width()
			})
			
			$('.current_ticker').hide().removeClass("current_ticker")
		
			n.show().addClass("current_ticker")
			position_ticker(n)
			
			ticker_count ++
			
		}
		
		return false;
		
	});
	
	//5.	Load the previous story
	$('#headline_previous').click(function() {
		
		if(ticker_count > 0){
			n = $('.current_ticker').prev()
			
			$('.current_ticker').stop().css({
				marginLeft: $('#ticker_wrap').width()
			})
			
			$('.current_ticker').hide().removeClass("current_ticker")
		
			n.show().addClass("current_ticker")
			
			position_ticker(n)
			
			ticker_count = ticker_count-1
			
		}
		
		return false;
		
	});
	
})

function position_ticker(e){
	
	e.css({
		marginLeft: $('#ticker_wrap').width()
	})
	
	slide(e)
	
}

function slide(e){
	//Set the sliding variable to true
	sliding = true;
	
	finish_pos = $('#ticker_wrap').width() - e.width()
	if(finish_pos > 0){
		finish_pos = 0
	}
		
	//Start the animation
	e.animate({
		marginLeft: finish_pos
	}, 15000, "jswing", function(){
		
		//The animationa has finished
		// set sliding to false
		sliding = false;
		
		ticker_interval = setInterval (function(){
			clearInterval( ticker_interval )
			$('#headline_next').click()
		}, interval_time );
		
	})
}

function set_width(e){
	
	e.css({
		width: e.width() + 50,
		display: "block"
	})
	
}