(function() {

  $(document).ready(function() {

    var $groups = $('.ss-container .ss-group');

    // Hide all groups other than the first
    // $groups.filter(':not(:first)').hide();

    // And fadeout all images
    $groups.find('.image').fadeTo(0,0);

    // Bind some public events
    $groups.bind('show', function() {
      animate_slide( $(this), 1 );
    });

    $groups.bind('hide', function() {
      animate_slide( $(this), 0 );
    });

    // Private function
    var animate_slide = function( $group, to ) {
      // DOM elements
      var $images = $group.find('.image');

      // Some settings
      var time_between_display = 150;   // Make it the same as animation_time, and they will show up exactly after.
      var animation_time = 400;

      // Sequentially show them
      $images.each(function(n) {

        var $image = $(this);

        setTimeout(function() {

          $image.fadeTo(animation_time,to);

        }, n*time_between_display);

      });
    };

  });

  $(window).load(function() {

    var current_index = 0;
    var first_time = true;

    var $groups = $('.ss-container .ss-group');

    var interval_fn = function() {
      if( !first_time ) {
        $groups.eq( current_index ).trigger('hide');
        current_index = ( current_index+1 >= $groups.length ? 0 : current_index+1 );
      }

      setTimeout(function() {
        $groups.eq( current_index ).trigger('show');
      }, 800);

      first_time = false;
    };

    setInterval(function() {
      interval_fn();
    }, 5000);

    interval_fn();


  });

})();
