var headlines;
var k;
var max_length = 45;
var current_item = 1;

function newsrotate() {
	// Madness, json indexes from -1 !!!
	if (k > headlines.length-1) { k = 0; }

	// Remove any current item of this name
	$('#news_headline_' + current_item).slideUp('slow', function() {
		$('#news_headline_' + current_item).remove();
		
		var subject = headlines[k].subject;
		if (subject.length > max_length) {
			subject = subject.substring(0, max_length);
			subject = subject + '...';
		}
		
		// Create the inner anchor tag
		var a = $('<a />')
				.attr('href', headlines[k].uri)
				.html(document.createTextNode(subject));
		
		// Bold date
		var bold = $('<b />')
				.append(document.createTextNode(headlines[k].friendly_date));
		
		// Paragraph element to hold all of it
		var p = $('<p />')
				.attr('id', 'news_headline_' + current_item)
				.css('display', 'none')
				.append(bold)
				.append($('<br />'))
				.append(a);
		
		// Append to the inner news holder
		$('#news_inner').append(p);	
		
		// Display the element and then update any counters
		$('#news_headline_' + current_item).slideDown('slow', function() {
			if (current_item == 1) {
				current_item = 2;
			} else {
				current_item = 1;
			}
			
			k++;
		});
	});
	
}

$(document).ready(function () {
	$.get("/news/get_latest_headlines", function(data) {
		
		headlines = eval(data);
		k = 0;
		
		// Call newrotate once first to set up initial headlines
		newsrotate();
		
		// Interval call
		setInterval("newsrotate()", 6000);
		
	}, "json");
});
