// Developed by Hartanto Thio
// Slideshow Plugin

( function($) {    

  var Change = function( options, nextIndex ) {
    // Slides selector
    var slidesSelector = options.slidesId + ' ' + options.slideExpr;
    
    var active = $('#' + slidesSelector).eq(nextIndex);
    var nonActive = $('#' + slidesSelector).not(':eq('+nextIndex+')');
    
    active.show();
    nonActive.not(':hidden').hide('fade', options.speed, function() {
      if( active.is(':hidden') )    // In case of rapid slide change, shows the current one
        active.show('fade', options.speed);
      active.css('z-index', '6');
      nonActive.css('z-index', '5');
    });
  } // Change()

  
  var Start = function( options ) {
    // Slides selector
    var slidesSelector = options.slidesId + ' ' + options.slideExpr;
    var totalSlides = $('#' + slidesSelector).length; // Total images

    var intervalId = setInterval( function() {
      var nextIndex = $('#' + slidesSelector).not(':hidden').index();
      nextIndex++;
      if( nextIndex >= totalSlides )
        nextIndex = 0;   
      Change(options, nextIndex);
    }, options.interval);
    return intervalId;
  } // Start()

  
  //////////////////////////////
  ///// jQuery Functions
  //////////////////////////////
  $.fn.Slideshow = function( options ) {
    // Default settings
    var defaults = {
      slidesId: 'slideshow-slides',
      navId: 'slideshow-nav', 
      changeOnHover: true,
      stopOnHover: true, 
      interval: 7000,
      speed: 300, 
      slideExpr: 'img'
    };

    // Merge defaults and options
    var options = $.extend(defaults, options);
    
    // Slides selector
    var slidesSelector = options.slidesId + ' ' + options.slideExpr;
    
    // Set defaults
    $('#' + slidesSelector + ':gt(0)').hide();
    $('#' + slidesSelector + ':gt(0)').css('z-index', '5');
    $('#' + slidesSelector + ':eq(0)').css('z-index', '6');

    var intervalId = Start(options);
    
    $('#' + options.navId + ' a')
      .hover(function() {
        if( options.stopOnHover ) {
          // Stop interval
          clearInterval(intervalId);
        }
        
        if( options.changeOnHover ) {
          var nextIndex = $(this).index();
          Change(options, nextIndex);
        }
      }, function() {        
        // Start slideshow
        intervalId = Start(options);
      });
    
    return this;
  } // Slideshow()
  
}) (jQuery)

