var arr_images = new Array();
var arr_thumbnails = new Array();

var active;
var start = 0;

function load_slideshow() {
  arr_images = $$('div#slideshow img');
  arr_images_save = $$('div#slideshow img');
  arr_images_save.each(function(s) {
    arr_images.push(s);
  });

  arr_images.each(function(s) {
    s.setOpacity(0);
  });

  arr_images[start].setStyle({
    display: 'block'
  });

  arr_images[start].setOpacity(1);

  stop_pe = false;
  new PeriodicalExecuter(function(pe) {
    if (stop_pe != true) {
      active = window.setInterval('fade(start)', 100);
      stop_pe = true;
    } else {
      pe.stop();
    }
  }, 2);

  thumbnailsActivation(start);
}

function thumbnailsActivation(tPos) {
  arr_thumbnails = $$('div#thumbnails img');
  arr_thumbnails.each(function(s) {
    s.setOpacity(0.5);
  });
  arr_thumbnails[tPos].setOpacity(1);
}

function fade(c) {
  currentOpacity = arr_images[c].getStyle('opacity');
  arr_images[c].setOpacity(currentOpacity - 0.05);

  if (c + 2 == arr_images.length) {
    arr_images_save.each(function(s) {
      arr_images.push(s);
    });
  }

  if (currentOpacity == 0) {
    start = c+1;

if (start >= arr_thumbnails.length) {
  tPos = start - arr_images.length + arr_images_save.length;
  tPos = -1 == tPos ? 5 : tPos;
} else {
  tPos = start;
}
    thumbnailsActivation(tPos);

    window.clearInterval(active);

    stop_pe = false;
    new PeriodicalExecuter(function(pe) {
      if (stop_pe != true) {
        active = window.setInterval('fade(start)', 100);
        stop_pe = true;
      } else {
        pe.stop();
      }
    }, 2);

    return false;
  } else {
    arr_images[c+1].setStyle({
      display: 'block'
    });
    currentOpacity = arr_images[c+1].getStyle('opacity');
    arr_images[c+1].setOpacity(currentOpacity + 0.05);
  }
}

function goto_slideshow(pos) {
  window.clearInterval(active);
  start = pos;
  if (typeof pe != 'undefined') {
    pe.stop();
  }
  load_slideshow();
}
