function queueNextPhoto() {
  timeout = setTimeout(
    function() { 
      if (currentPhoto + 1 == photos.size()) {
        nextPhoto = 0;
      } else {
        nextPhoto = currentPhoto + 1;
      }
      loadPhoto();
    }, 
    3000
  );
}

function skipToPhoto(photoIndex) {
  if (!busy && photoIndex != currentPhoto) {
    if (playing) {
      playing = false;
  		clearTimeout(timeout);
    }
    nextPhoto = photoIndex;
    loadPhoto();
  }
}

function loadPhoto() {
  busy = true;
  var image = new Image();
  image.onload = function() {
    var clone = $("photo_" + currentPhoto).cloneNode(true);
    clone.id = "photo_" + nextPhoto;
    clone.style.display = "none";
    $("photos").insert(clone);
    clone.down("a").href = photos[nextPhoto][1];
    clone.down(".name").update(photos[nextPhoto][2]);
    clone.down("img").src = photos[nextPhoto][0];
    new Effect.Parallel(
      [
        new Effect.Move(
          "gallery_marker", 
          {
            x: 4 + // padding
              (100-24)/2 + // difference in widths
              (100 + 4) * nextPhoto, // offset (width + margin)
            y: 292, 
            mode: "absolute"
          }
        ),
        new Effect.Appear("photo_" + nextPhoto)
      ],
    	{ 
    		duration: 0.5, 
    		afterFinish: function() { 		
    			Element.remove("photo_" + currentPhoto);
          currentPhoto = nextPhoto;
          busy = false;
          if (playing) {
            queueNextPhoto();
          }
    		}
    	}
    );
  };
  image.src = photos[nextPhoto][0];
}