$(document).ready(function() {
  var body = $("body");
  body.addClass("javascript");
  
  var overlayIDs = ["bottom", "middle", "top"];
  var overlays = [];
  var visible = [];
  for (var i=0; i < overlayIDs.length; i++) {
    var overlay = $('<div id="' + overlayIDs[i] + '">&nbsp;</div>');
    body.append(overlay);
    overlays.push(overlay);
    visible.push(true);
  };
  
  // Insert the flicker
  var flicker = $('<div id="flicker">&nbsp;</div>');
  body.append(flicker);

  // Animations
  var randomEntry = function(collection) {
    var index = Math.floor(Math.random() * collection.length);
    return collection[index];
  };
  
  var current = null;
  
  var widthLeft = function() {
    current.animate({width: "70%"}, 4000, "linear", animate);
  };
  
  var widthRight = function() {
    current.css({left: "auto", right: 0});
    current.animate({width: "50%"}, 6000, "linear", animate);
  };
  
  var fadeOut = function() {
    current.animate({opacity: 0}, 100, "linear", animate);
  };
  
  var rollup = function() {
    current.animate({height: 0}, 500, "linear", animate);
  };
  
  var animations = [widthLeft, widthRight, fadeOut, rollup];
  var timeouts = [2000, 5000, 8000, 4000, 10000];
  
  var animate = function() {
    // Reset the existing animation
    if (current) {
      current.animate({opacity: 1, left: 0, right: "auto", height: 600, width: "100%"}, 100);
    }
    // Pick a random overlay
    current = randomEntry(overlays);
    // Pick a random animation & timeout
    var animation = randomEntry(animations);
    var delay = randomEntry(timeouts);
    window.setTimeout(animation, delay);
  };
  
  animate();
});
