/*
-----------------------------------------------
Horizon Shutters Homepage
Author: Chad Spencer & Jeremy Boles
----------------------------------------------- */

window.addEvent('domready', function() {
  
  /* Slideshow
  ----------------------------------------------- */
  var slideshow = $('slideshow');
  if ($defined(slideshow)) {
    var items = slideshow.getElements('li');
    items.set('tween', { 'duration' : 'long', 'property' : 'opacity' });
    items.each(function(item) { 
      var height = item.getSize().y;
      item.setStyles({'margin-top' : (-height), 'position' : 'relative', 'top' : (height + 5)});
      item.get('tween').set(0);
    });
    items[0].get('tween').set(1);
    
    // Create the navigation
    var nav = new Element('div', { 'id' : 'slideshow-nav' });
    var links = new Elements();
    items.each(function(item, index) {
      // Array indexes always start at 0 so add 1 to it
      index = (index + 1).toString();
      
      // Create the link to change the image
      var link = new Element('a', { 'href' : ('#image-' + index), 'text' : index });
      link.store('item', item);
      item.store('link', link);
      
      // Create a change function for the link
      link.store('change', (function() {
        items.each(function(item) { item.get('tween').start(0); });
        link.retrieve('item').get('tween').start(1)
      }));
      
      // Add the a click event
      link.addEvent('click', (function(event) {
        event.stop();
        link.retrieve('change').run();
        // Don't change right away
        slideshow.store('skip', true);
      }).bindWithEvent(link));
      
      link.inject(nav);
      links.push(link);
    });
    
    // Make the first link active
    links[0].addClass('active');
    
    // Add the navigation to the slideshow
    nav.inject(slideshow);
    
    // When a transition starts, make it's link active
    items.each(function(item) { 
      item.get('tween').addEvent('start', function() {
        links.removeClass('active');
        item.retrieve('link').addClass('active');
      });
    });
    
    // Run as slideshow
    (function() {
      // If the person had just clicked on it, we don't want to change right away
      if (slideshow.retrieve('skip', false)) {
        slideshow.store('skip', false);
        return true;
      }
      
      // Figure out the current link and what will be the next
      var active = links.filter('.active')[0];
      var current = links.indexOf(active);
      var next = current + 1;
      
      // If we're at the end, go back to the beginning
      if (next == links.length) next = 0;
      
      // Run the link's change function
      links[next].retrieve('change').run();
    }).periodical(5000);
  }
  
});