var homepageImageActive = 'out';
var homepageTimeoutID = null;

$(document).ready(function()
{
	var currentSelection = 0;

	$('#pagination-controls img.pagination-image').click(function()
	{
		clearTimeout(homepageTimeoutID);
		var direction = $(this).attr('alt');

		if( direction == 'Next' )
		{
			currentSelection++;

			if( currentSelection == news_list.length )
			{
				currentSelection = 0;
			}
		}

		if( direction == 'Previous' )
		{
			currentSelection--;
			if( currentSelection == -1 )
			{
				currentSelection = news_list.length - 1;
			}
		}

		update_hero(currentSelection);
	});

	$.each(news_list, function(key, value)
	{
		$('#iphone-dots').append('<span class="black" id="iphone-dot-' + key + '">&middot;</span> ');
	});

	if( news_list.length < 2 )
	{
		$('#pagination-controls img.pagination-image').hide();
	}

	update_hero(currentSelection);
});


function slideHeroPages()
{
	$('#pagination-next').click();
}

function update_hero( selection )
{
	if( news_list[selection].display_more_link != false )
	{
        	$('#hero-title').html('<a href="' + news_list[selection].url + '">' + news_list[selection].title + '</a>');

            $('#her-find-out-more').show();
    	    $('#her-find-out-more').attr('href', news_list[selection].url);
	}
	else
	{
		$('#her-find-out-more').hide();
		$('#hero-title').html('<a href="#" style="cursor: default;">' + news_list[selection].title + '</a>');
	}


	if( news_list[selection].title.length > 3 )
	{
		$('#hero-title').show();
	}
	else
	{
		$('#hero-title').hide();
	}

	var otherState = 'in';
	if( homepageImageActive == 'in' )
	{
	  otherState = 'out';
	}

	// Load the image into the other state.
	var img = new Image();
	$(img).load(function()
	{
	  $('#hero-image img.' + homepageImageActive).fadeOut(1000);

	  $('#hero-image img.' + otherState).attr('src', $(this).attr('src'));
	  $('#hero-image img.' + otherState).fadeIn(1000, function()
	  {
	    $(this).attr('src', $(this).attr('src'));

	    if( news_list[selection].show_release_date != false )
	    {
	        $('#hero-date').show();
	        $('#hero-date').html(news_list[selection].timestamp);
	    }
	    else
	    {
	        $('#hero-date').hide();
	    }

	    $('#iphone-dots span.white').removeClass('white').addClass('black');

	    $('#iphone-dot-' + selection).removeClass('black');
	    $('#iphone-dot-' + selection).addClass('white');
	  });
	  homepageImageActive = otherState;

	  homepageTimeoutID = setTimeout(function()
	  {
		slideHeroPages();
	  }, 2000);

	}).attr('src', news_list[selection].image_url); 
}
