$(document).ready(function() {
  $("#slider").slider($("#sliderControls"));
});

jQuery.fn.slider = function(controls) {
  this.css({position: 'relative'});
  var data = {entries: {}};
  // Find and position the list items
  var entries = this.find("li");
  entries.css({position: 'absolute',left: '0', top: '0', "z-index": 1});
  // Hide all the entries except the first
  entries.filter("li:gt(0)").css({opacity: 0});
  // Default to the first entry
  data.current = entries[0];
  data.currentIndex = 0;
  controls.find("a:eq(0)").addClass("current");
  // Put entries into a hash, with their ID as the key
  entries.each(function(index, li) {
    data.entries[$(li).attr("id")] = li;
  });
  // the function for cycling to specified panel
  var cycle = function(destination, target) {
    if (data.current != destination) {
      data.animating = true;
      $(data.current).css({"z-index": 1});
      $(destination).css({"z-index": 2});
      $(destination).animate({opacity: 1}, 300, function() {
        $(data.current).animate({opacity: 0});


        data.current = destination;
        data.animating = false;
      });
      // Hi-light the current frame in the controls
      controls.find("a").removeClass('current');
      target.addClass('current');
    }
  }
  // Have a timeout run to change the panels
  var automate = function() {
    if ((data.currentIndex + 1) == entries.length ) {
      data.currentIndex = 0;
    }
    else {
      data.currentIndex += 1;
    }
    entry = entries[data.currentIndex];
    anchor = controls.find("a[href=#" + entry.id +"]");
    cycle(entry, anchor);
    timeout = window.setTimeout(automate, 6000);
  }
  var timeout = window.setTimeout(automate, 6000);
  // Set up controls
  controls.bind("click", function(e) {
    var target = $(e.target);
    if (target.is("a") && !data.animating) {
      // Stack the destination image on top, then fade it in. After, just hide
      // the previous frame.
      var destination = data.entries[target.attr("href").split("#")[1]];
      cycle(destination, target);
      window.clearTimeout(timeout);
    }
    return false;
  });
};
