var storyBook = document.getElementById('home_people');
var stories = storyBook.getElementsByTagName('li')
var altStories = 0;
var widgets    = document.createElement('p')
var buttonPrev = document.createElement('img');
var buttonNext = document.createElement('img');
var label      = document.createElement('span');
var labelText  = document.createTextNode('Meet people living with RLS');

var autoPlayTimeout   	= null;
var apInterval 			= 10000;		// Timeout between auto change
var apTimeout  			= 20000;	// Timeout to wait to resume autoplay after click

for(var i = 0; i < stories.length; i++) {
  if(stories[i].className.indexOf('displayed') == -1) {
    stories[i].style.display = 'none';
    altStories++;
  }
}

// If the 'displayed' class wasn't found in any element, show the first story in the list.
if(altStories == stories.length) {
  stories[0].style.display = 'block';
  stories[0].className = 'displayed';
}

function flipStory() {
  for(var i = 0; i < stories.length; i++) {
    if(stories[i].className == 'displayed') {
      storyIndex = this.id == 'home_people_prev' ? (i-1) : (i+1);
	  
      if(storyIndex < 0) storyIndex = stories.length - 1;
      else if(storyIndex >= stories.length) storyIndex = 0;
	  
      stories[i].className = '';
      stories[i].style.display = 'none';
      }
  }
  
  if(!this.id){
	  clearTimeout(autoPlayTimeout);
	  autoPlayTimeout = setTimeout('flipStory()', apInterval);
  }else{
	  clearTimeout(autoPlayTimeout);
	  autoPlayTimeout = setTimeout('flipStory()', apTimeout);
  }
  
  stories[storyIndex].className = 'displayed';
  stories[storyIndex].style.display = 'block';
}

buttonPrev.setAttribute('src','images/arrow_left.gif');
buttonPrev.setAttribute('alt','Previous');
buttonPrev.setAttribute('title','Previous');
buttonPrev.setAttribute('id','home_people_prev');
buttonPrev.onclick = flipStory;

buttonNext.setAttribute('src','images/arrow_right.gif');
buttonNext.setAttribute('alt','Next');
buttonNext.setAttribute('title','Next');
buttonNext.setAttribute('id','home_people_next');
buttonNext.onclick = flipStory;

storyBook.appendChild(widgets);
widgets.appendChild(buttonPrev);
widgets.appendChild(label);
label.appendChild(labelText);
widgets.appendChild(buttonNext);

autoPlayTimeout = setTimeout('flipStory()', apInterval);
