$(function() {
  function cycleImage(element) {
    var currentImage = $(element).find(".slide:visible");
    var nextImage = currentImage.next(".slide");

    if (nextImage.length == 0) {
      nextImage = $(element).find(".slide:first");
    }

    currentImage.fadeOut(1000);

    nextImage.fadeIn(1000, function() {
      prepareNextCycle(element);
    });
  }

  function prepareNextCycle(element) {
    var timeout = (Math.random() * 5000) + 5000;
    setTimeout(function() { cycleImage(element) }, timeout);
  }

  function applyTape(position) {
    cssClass = "tape-" + position;
    $("." + cssClass).append("<img class=\"" + cssClass + "\" src=\"/images/tape.png\" />")
  }

  applyTape("top-left");
  applyTape("top-right");
  applyTape("bottom-left");
  applyTape("bottom-right");

  $(".slideshow").each(function() {
    prepareNextCycle(this);
  });

  $("a.listen").each(function() {
    $(this).click(function() {
      var audio = $("audio#" + this.id).get(0);

      $(this).toggleClass("playing");
      $(this).toggleClass("paused");

      if (audio.paused) {
        audio.play();
      } else {
        audio.pause();
      }

      return false;
    });
  });

  $(".lettering-lines").lettering("lines");
});

