$(function(){
	rotation = setInterval(function(){showNextStory()}, 5000)
	$('#featured_stories ul li a').click(function(){
		clearInterval(rotation)
		toggleSelectedStory(this)
		showStory(this.id)
		return false
	})
})

function showNextStory() {
	var next = $('#featured_stories ul li.selected').next().children('a')
	if ($(next).attr('id')) {
		showStory($(next).attr('id'))
		toggleSelectedStory(next)
	} else {
		var first = $('#featured_stories ul li:first').children('a')
		showStory($(first).attr('id'))
		toggleSelectedStory(first)
	}
}

function toggleSelectedStory(selected) {
		$('#featured_stories ul li').removeClass('selected')
		$(selected).parent('li').addClass('selected')
}

var featuredStories = Array();

function showStory(id) {
	if (typeof featuredStories[id] === 'undefined') {
		$.getJSON('/articles/featured/' + id, function(data){
			featuredStories[id] = data
			populateStory(id, data)
		})
	} else {
		populateStory(id, featuredStories[id])
	}
}

function populateStory(id, data) {
	$('#featured_story').attr('style', 'background:url(' + data.banner + ')')
	$('#featured_story_text a').attr('href', '/' + id + '.html').text(data.title)
	$('#featured_story_text p').text(data.description)
}
