// JavaScript Document
var stories = new Array();
var currentStoryNumber = 0;

function getStories(theURL)
{
	 var jqxhr = $.ajax(theURL)
	 	.done(processStories);
}

function processStories(data)
{
		$(data).children('div.story').each(function()
	{
		stories.push(this);	
	});
	if (stories.length > 1)
	{
		var nextButton = '<a href="#" class="nextButton">Next Story</a>';
		var previousButton = '<a href="#" class="previousButton">Previous Story</a>';
		
		for(story in stories)
		{
			$(stories[story]).children('nav').append(previousButton + nextButton);	
		}
	}
	//$("#storyContent").append($(stories[0]).html());
	goToNextStory();
}

function changeStories(p_story)
{
	if ($(".story").length > 0)
	{
		$(".story").fadeOut(500,function()
		{
			$("#storyContent .story").remove();
			showNewStory();
		});
	}else{
		showNewStory();
	}
	function showNewStory()
	{
		$("#storyContent").append(p_story);
		$(".story").fadeIn(500,removeStoryNavigationDefaults());
	}
}

function goToNextStory()
{
	if (currentStoryNumber < (stories.length -1))
	{
		currentStoryNumber++;
	}else{
		currentStoryNumber = 0;
	}
	changeStories(stories[currentStoryNumber]);
}

function goToPreviousStory()
{
	if (currentStoryNumber < 1)
	{
		currentStoryNumber = stories.length-1;
	}else{
		currentStoryNumber = currentStoryNumber-1;
	}
	changeStories(stories[currentStoryNumber]);
}

function removeStoryNavigationDefaults()
{
  $(".nextButton").click(function(event){
	   event.preventDefault();
	   goToNextStory();
   });
   $(".previousButton").click(function(event){
	   event.preventDefault();
	   goToPreviousStory();
   });
}
