// Automatically create slideshows
$(document).ready(function(){  
  $("#slideshow").each(function(){
    new Slideshow($(this));
  });
});

var Slideshow = function(slideshow){
  
  var DEBUG_MODE = true;
  
  var VIEW_TIME = 3000;
  var FADE_TIME = 1000;
  
  var STATE_INIT = 0;
  var STATE_VIEWING = 1;
  var STATE_FADING = 2;
  
  var currentState = STATE_INIT;
  var currentSlide = 0;
  
  var slideshow_container = $(slideshow);

  if( slideshow_container.length <= 0 ){
    if( DEBUG_MODE ){
      window.alert("Slideshow: No slideshow container found.");
    }
    return false;
  }
  if( slideshow_container.length > 1 ){
    if( DEBUG_MODE ){
      window.alert("Slideshow: More than one slideshow was found.");
    }
    return false;
  }

  // Hide images, and position them correctly
  var slides = slideshow_container.children().css({
    opacity: 0.0,
    top: 0,
    left: 0,
    position: 'absolute'
  })

  if( slides.length <= 0 ){
    if( DEBUG_MODE ){
      window.alert("Slideshow: No slides found within slideshow container.");
    }
    return false;
  }
  
  
  var changeState = function( state ){
    
    if( state == currentState ){
      return;
    }
    currentState = state;
    
    switch( currentState ){
      
      case STATE_INIT:
        // DO NOTHING
        break;
        
      case STATE_VIEWING:
        currentSlide = (currentSlide + 1) % slides.length;
        setTimeout(function(){changeState(STATE_FADING)}, VIEW_TIME );
        
        break;
        
      case STATE_FADING:
        // Move current down one (10 -> 9)
        if (Slideshow.current_slide)
          Slideshow.current_slide.css('z-index', '9');

        // Get next one
        var nextSlideIndex = (currentSlide + 1) % slides.length;
        var nextSlide = $(slides[nextSlideIndex]);

        // Show new slide
        nextSlide.css("opacity", "0.0")
          .css("z-index", "10")
          .animate({opacity: 1.0}, 1000, function() {
            if (Slideshow.current_slide) {
              Slideshow.current_slide.css('z-index', '8');
            }
            Slideshow.current_slide = nextSlide;
            changeState(STATE_VIEWING);
          });
        
        // Hide old one at same time...
        if (Slideshow.current_slide)
          Slideshow.current_slide.animate({opacity: 0.0}, 1000);
        
        break;
    }
  }
 
  changeState( STATE_FADING );
  return true;
}

