/* JQuery slides plugin */
/* Copyright (c) IVP 2010 */

    jQuery.fn.slideShow = function(settings)
    {
      var config = {showButtons: true, slidePeriod: 10000};
      var timer;
      var slideContainer;
      var slideCount;    
      var slideButtons;
      
      function switch_slide(event, index)
      {
         // If we've gone beyond the last slide, go back to the first one
         if(index > slideCount) index = 1;
         // Hide the old slide 
         jQuery(slideContainer).children().css("display","none");
         // Bring in the new slide
         var thisSlide = jQuery(slideContainer).children().eq(index-1);
         jQuery(thisSlide).css("opacity","0");
         jQuery(thisSlide).css("display","");
         jQuery(thisSlide).css("visibility","visible");
         jQuery(thisSlide).animate({"opacity":1},700, "linear", null);
         // Update the location buttons
         jQuery(slideButtons).children().removeClass("active");
         jQuery(slideButtons).children().eq(index-1).addClass("active");
         // Set a timer to go on to the next slide
         clearTimeout(timer);
         timer = setTimeout(function() { switch_slide({},index + 1) } ,config.slidePeriod);
      }

      function setup(elem, settings)
      {
        if(settings)
        {
          config = jQuery.extend(config, settings);
        }
        slideContainer = elem;
        slideCount = jQuery(slideContainer).children().length;
        // Wrap the slides container in a 'slideshow' div
        jQuery(slideContainer).wrap("<div class='slideshow'></div>");
        // Buttons for controlling the flow
        if(config.showButtons)
        {
          // Create the buttons
          slideButtons = jQuery("<ul id='slideshowButtonCollection'></ul>").addClass("buttons");
          for (i = 1; i <= slideCount; i++)
          {
            var buttonLI = jQuery("<li id='button" + i + "'></li>").append("<a href='#'>" + i + "</a>");
            slideButtons.append(buttonLI);
          }
          jQuery(slideContainer).parent().prepend(slideButtons);
          // Bind the buttons
          var btnCount = 1;
          jQuery(slideButtons).children().children("a").each( function(e)
          {
             // when this is clicked, switch to the applicable slide
             var thisBtnCount = btnCount++;
             jQuery(this).click(function(e) {switch_slide(e,thisBtnCount);return false; });       
          });
        }
        // Start on a random slide
        switch_slide({},Math.round(Math.random() * (slideCount - 1) + 1));
      }
      
      return $(this).each(function() {
        setup(this, settings);
      });
    };

