// jQuery JavaScript Document
var counter = 2;
var no_items;
var auto_play = true;
function auto_scroll(){
	if (auto_play) {
		$('#news_scroller #navigation a:nth-child(' + counter + ')').trigger('interval');
		counter = counter % no_items;
		counter++;
	}
}

$(function(){
	
	$('#news_data').before('<div id="news_scroller" class="auto_play">');
	$('#news_scroller').append('<div id="title">');
	$('#news_scroller').append('<div id="images">');
	$('#news_scroller').append('<div id="navigation">');
	
	$('div#title').append($('#news_data strong').clone()[0]);
		//displayItem(0, 0)
		
	// for each paragraph add navigation/indicator
	$('#news_data p')
		.each(function(index) {
			if (index == 0) {
				$('#news_scroller #navigation').append('<a class="current">&#8226;</a>');
			} else {
				$('#news_scroller #navigation').append('<a>&#8226;</a>');
			}
			$('div#images').append($('#news_data img').closest('a').clone()[index]);
			no_items = index + 1;
	});
	
	// line up news items //
	$('#news_scroller #images a').each(function(index) {
        $(this).css('left', index * $('#news_scroller').width() );
    });
	
	// click to scroll
	$('#news_scroller #navigation a').click(function(event) {
		//alert(event.eventPhase);
		var current = $(this).index()
		var offset = -1 * current * $('#news_scroller').width();
		$('#news_scroller #navigation a').removeClass('current');
		$(this).addClass('current'); 
		counter = current + 2;

		displayItem(current, offset)
	});
	$('#news_scroller #navigation a').bind('interval', function(event){
		//alert(event.eventPhase);
		var current = $(this).index()
		var offset = -1 * current * $('#news_scroller').width();
		$('#news_scroller #navigation a').removeClass('current');
		$(this).addClass('current'); 
		counter = current + 1;

		displayItem(current, offset)
		
	});
	// hover to pause	
	$('#news_scroller').mouseover(function(){
		auto_play = false;
	}).mouseout(function(){
		auto_play = true;
	});
	// SELECTOR TEST
	/*
	$('div#news_data').after('<textarea id="text" rows="20">');
	
	var selector = $('#news_data img').closest("a").html();
	$('#text').val(selector);
	*/
		
	setInterval(auto_scroll, 5000);
});
	function displayItem(current, offset) {
		$('#news_scroller #images').animate({left: offset}, 500);
		// fade out Title
		$('#news_scroller #title').animate({opacity:0}, 250, function(){
		// change Title
			$('#news_scroller #title strong')
				.html('')
				.append($('#news_data strong').clone()[current]); 
			});
		// fade in Title
		$('#news_scroller #title').animate({opacity:1}, 250);
	}

