/**
 * Very simple slideshow for the frontpage
 */

Slideshow = function(expr) {
  var oldContainer = $(expr), self = this;
  this.pos = 0;
  this.pictures = $('li a', oldContainer);
  oldContainer.parent().append(
    this.container = $('<div class="slideshow">')
      .append(this.overlay = $('<div class="overlay">'))
      .hide()
      .slideDown('slow')
      .append(this.title = $('<h3>'))
      .click(function() {
        document.location.href = $(self.pictures[self.pos]).attr('href');
      })
  );

  if (this.pictures.length) {
    $.shuffeArray(this.pictures);
    this.nextPicture();
  }
}

Slideshow.prototype.nextPicture = function() {
  var
    self = this,
    picture = $('img', this.pictures[this.pos = (this.pos + 1) %
                                     this.pictures.length]);

  this[this.pos % 2 ? 'container' : 'overlay']
    .css('backgroundImage', 'url(' + picture.attr('src') + ')');

  if (!this.title.text())
    this.title.fadeIn('slow').text(picture.attr('alt'));

  window.setTimeout(function() {
    var newTitle = picture.attr('alt');
    if (newTitle != self.title.text())
      self.title.fadeOut(1000, function() {
        $(this)
          .text(picture.attr('alt'))
          .fadeIn(1000);
      });
    self.overlay[self.pos % 2 ? 'fadeOut' : 'fadeIn'](2000, function() {
        self.nextPicture();
    })}, 4000);
};
