window.onload = function () { new NewsChanger($("#feature_area")); };


function NewsChanger(news)
{
	// Offset so the arrow
	var ARROW_OFFSET = 0;

	// Time (in milliseconds) to wait to switch to the next story automatically
	var SWITCH_TIME = 5000;
	
	// Key codes
	var UP_ARROW = 38;
	var DOWN_ARROW = 40;
 
	var _current_story = 0;

	var _news_links = $(news).find("#right_column #news_items a");
	var _news_img =  $(news).find("#news_img")[0];
	var _news_link =  $(news).find("#news_link")[0];
	var _arrow = $(news).find("#arrow")[0];

	(function init()
	{
	//	bind_keys();
		add_onclicks();
		move_arrow(_news_links[0]);
		_auto_change_interval = setInterval(auto_change, SWITCH_TIME);
	})();

	// Switches to the next story (returns to first story once the last story has been reached)
	function auto_change()
	{
		var next_story = _current_story + 1 < _news_links.length ? _current_story + 1 : 0;
		change_story(next_story);
	}
	
	function bind_keys()
	{
		$(window).keypress(function(e) 
		{ 
			if (e.which == UP_ARROW)
				change_story(_current_story - 1);
			else if (e.which == DOWN_ARROW)
				change_story(_current_story + 1);
		});
	}
	
	// Add an onclick to each news link
	function add_onclicks()
	{
		_news_links.each(function (index, link) 
		{ 
			link.onclick = 
			function () 
			{ 
				change_story(this.id); 
				clearInterval(_auto_change_interval);
				return false; 
			}; 
		});
	}
	
	// Change to the story for the link
	function change_story(story_id)
	{
		if (story_id >= 0 && story_id < _news_links.length)
		{
			swap_img(story_id);
			set_current(story_id);
			_current_story = story_id;
		}
	}

	// Set the link as the curent link
	function set_current(story_id)
	{
		_news_links.each(function (index, link) { link.className = ""; });
		_news_links[story_id].className = "selected";
		move_arrow(_news_links[story_id]);
	}

	// Move the arrow to the link
	function move_arrow(link)
	{
		$(_arrow).animate({ "top": link.offsetTop + ARROW_OFFSET + "px" }, 300);
	}

	// Change the image story to the image for the story id
	function swap_img(story_id)
	{
		_news_img.src = stories[story_id].media_url;
		_news_link.href = stories[story_id].href;
	}
}