$(document).ready(function() {
  $('.spotlight_wrapper').each(function() {
    // Initialization
    var spotlight       = $(this);
    var first_picture   = $(this).children('.spotlight_picture:first');
    var picture_count   = $(this).children('.spotlight_picture').length;
    var current_picture = null;
    var timer_label     = 'spotlight' + spotlight.index();

    // Add number icons to each picture
    $(this).children('.spotlight_picture').each(function()
    {
      for (i = 1; i <= picture_count; i++)
      {
        if ($(this).index() == i)
        {
          $(this).children('.userinfo').children('.spotlight_numbers').append('<img src="/genjUserGalleryPlugin/images/spotlight' + i + '_active.png" alt="" />');
        }
        else
        {
          $(this).children('.userinfo').children('.spotlight_numbers').append('<img src="/genjUserGalleryPlugin/images/spotlight' + i + '.png" alt="" />');
        }
      }
    });

    // Bind click event to number icons
    $(this).children('.spotlight_picture').each(function()
    {
      $(this).children('.userinfo').children('.spotlight_numbers').children('img').each(function() {
        $(this).click(function() {
          current_picture.css('display', 'none');
          current_picture = spotlight.children('.spotlight_picture:eq(' + $(this).index() + ')');
          current_picture.fadeIn(500);
          spotlight.children('.spotlight_category').html(current_picture.children('.category').html());

          // Stop and re-initialize timer
          $(document).stopTime(timer_label);
          $(document).everyTime(5000, timer_label, function(i) {
            current_picture.css('display', 'none');
            if (current_picture.next().length == 0)
            {
              current_picture = first_picture;
            }
            else
            {
              current_picture = current_picture.next();
            }
            current_picture.fadeIn(500);
            spotlight.children('.spotlight_category').html(current_picture.children('.category').html());
          });
        });
      });
    });

    // Show first picture
    first_picture.fadeIn(1000);
    spotlight.children('.spotlight_category').html(first_picture.children('.category').html());

    // Initialize timer
    current_picture = first_picture;
    $(document).everyTime(5000, timer_label, function(i) {
      current_picture.css('display', 'none');
      if (current_picture.next().length == 0)
      {
        current_picture = first_picture;
      }
      else
      {
        current_picture = current_picture.next();
      }
      current_picture.fadeIn(500);
      spotlight.children('.spotlight_category').html(current_picture.children('.category').html());
    });
  });
});

