$(document).ready(function(){

	$.ajax({
		url: 'news/news_items.php',
		dataType: "html",
		success: function(data) {
			
			last_item_id = 0;
			
			items = $(data).find('li');
			
			rotateNewHeadlines( items, items.length, last_item_id );		
			
			
		}
	});


});

function rotateNewHeadlines( items, count, last_item_id ){

	$('#home_news_headline').hide();
	$('#home_news_description').hide();

	chance = Math.random();
	
	// 1/3 of the time (randomly) choose from the most recent 3 items
	n = ( chance < 0.34 )? 3 : count;
	
	item_id = Math.floor( Math.random() * n + 1 );
	
	if( item_id ==  last_item_id ){ 
		rotateNewHeadlines( items, count, last_item_id ); 
	}
	else {
				
		$(items).each( function(){

			if( $(this).attr('id') == item_id ){
				
				link_href = $(this).find('a').attr('href');
				link_text = $(this).find('a').html();
				idescription = ( $(this).html().length > 77 )? $(this).html().substring( 0 , 80 ) + "..." : $(this).html();
				
				$('#home_news_headline').html( '<a target="_blank" href="'+link_href+'">'+link_text+'</a>' );
				$('#home_news_description').html( ''+ idescription + '' );

				$('#home_news_headline').fadeIn('slow');
				$('#home_news_description').fadeIn('slow');

			}

		});
		
		setTimeout( function(){ 
				rotateNewHeadlines( items, count, item_id );
			}, 
			6000 
		);
	
	}

}
