// wrap everything to avoid namespace conflicts #756722
(function ($) {

  var interval = "";

  // Starts the slideshow and makes sure we are not in high contrast mode
  $(function(){
   if (!$("#page-tools .high-contrast").hasClass("selected")) {
      $("#slide-0").addClass("active");
      $("#slide-thumb-0").addClass("active");
      interval = window.setInterval(nextSlide, 10000);
    }

    // 3 actions for the play/pause + next + prev buttons.
    $("#play").click(function(){
      if (interval=="") {
        $(this).addClass("pause");
        nextSlide();
        interval = window.setInterval(nextSlide, 10000);
      } else {
        stopSlideshow();
      }
      return false;
    });

    $("#next").click(function(){
      stopSlideshow();
      nextSlide();
      return false;
    });

    $("#prev").click(function(){
      stopSlideshow();
      prevSlide();
      return false;
    });

    $("slide-img").click(function(){  
      stopSlideshow();
    });   


    // 3 actions to control slideshow thumbnails
    $("#slideshow-thumbs a").click(function() {
      $(this).addClass("active");
      $(this).siblings().removeClass("active");
      var index = $("#slideshow-thumbs a").index(this);
      var slide = $("#slideshow-holder > div.active").attr('id');
      newSlide = "slide-"+index;
      stopSlideshow();
      swapSlide(slide,newSlide);
      return false;
    });


    // The following functions control the progress of the slideshow
    function stopSlideshow() {
      $("#play").removeClass("pause");
      window.clearInterval(interval);
      interval = "";
    }

    function nextSlide() {
      var slide = $("#slideshow-holder > div.active").attr('id');
      if ($("#"+slide).next().hasClass("slide")) {
        var newSlide = $("#"+slide).next().attr('id');
      } else {
        var newSlide = "slide-0";
      }
      swapSlide(slide,newSlide);
    }

    function prevSlide() {
      var slide = $("#slideshow-holder > div.active").attr('id');
      if ($("#"+slide).prev().hasClass("slide")) {
        var newSlide = $("#"+slide).prev().attr('id');
      } else {
        var newSlide = $("#slideshow-holder > :last").attr('id');
      }
      swapSlide(slide,newSlide);
    }

    // Performs the actual animation/transition

    function swapSlide(slide,newSlide) {
      $("#"+newSlide).addClass("active");
      $("#"+slide).removeClass("active");
      $("#"+newSlide).fadeIn("slow");
      $("#"+slide).fadeOut("slow");
      var thumbIndex = $("#slideshow-holder div.slide").index($("#"+newSlide));
      $("#slide-thumb-"+thumbIndex).addClass("active");
      $("#slide-thumb-"+thumbIndex).siblings().removeClass("active");
    }

  });

})(jQuery);;

