(function($){  
  $.fn.slideShow = function(){  
    return this.each(function(){       
      // Get the neccessary elements
      var slideshow_timer;
      var slideshow_wrapper = $(this);
      //var holder = slideshow_wrapper.children('.slideshow-navigation');
      var holder = $('.slideshow-navigation-wrapper');
      var previous = holder.children('.previous-slide');
      var next = holder.children('.next-slide');
      var navigation = holder.children('.slideshow-navigation');
      var navigation_buttons = navigation.children('li');
      
      var count_buttons = navigation_buttons.length - 1;
      
      var slideshow = slideshow_wrapper.children('.slideshow-slides');
      var slides = slideshow.children('li');
      
      // Add active states to the first slide and button      
      slides.eq(0).addClass('active');
      navigation_buttons.eq(0).addClass('active');
            
      var navigation_active = navigation.find('.active');
                     
      // Navigation buttons click event
      navigation_buttons.click(function(){
        // Change active buttons
        var button = $(this);
        var index = button.index();
        if(button.hasClass('active')) return false;
        navigation_active.removeClass('active');
        button.addClass('active');
        navigation_active = button;
        // Change slideshow images
        slides.eq(index).addClass('next').fadeIn(200, function(){
          var slide = $(this);
          slideshow.find('.active').removeClass('active').css({display: 'none'});
          slide.addClass('active').removeClass('next');
          // Set new timer
          clearTimeout(slideshow_timer);
          slideshow_timer = setTimeout(triggerClick, 5000);
        });
      });
      
      // Show the next slide
      function triggerClick(){
        if(navigation_active.next().length) navigation_active.next().trigger('click');
        else navigation_buttons.eq(0).trigger('click');
      }      
      
      next.click(function(){
        if(navigation_active.next().length) navigation_active.next().trigger('click');
        else navigation_buttons.eq(0).trigger('click');
      });
      
      previous.click(function(){
        if(navigation_active.prev().length) navigation_active.prev().trigger('click');
        else navigation_buttons.eq(count_buttons).trigger('click');
      }); 
       
      // Trigger timer
      setTimeout(triggerClick, 5000);        
    });
  };  
})(jQuery);
