Event.observe(window, 'load', function() {
  var w = getClientWidth() - 50;
  var h = getClientHeight();
  Show.and('p', {duration: 5}).go();
  var paper = Raphael(0, 0, w, h);
  triggerCircle(paper, w, h);
  $$('.box').each(function(el) {
    el.morph('left:'+(w+500)+'px', {
      duration: 40,
      transition: 'easeInOutCubic'
    });
  });
});

function getRandNr(min, max) {
  return Math.floor(Math.random()*(max-min)) + min;
}

function triggerCircle(paper, w, h) {
  thisW = getRandNr(50, w-50);
  thisH = getRandNr(50, h-50);
  thisDur = getRandNr(1, 6) * 500;
  renderCircle(paper, thisW, thisH, 30, thisDur, 1);
  setTimeout(function() {
    triggerCircle(paper, w, h);
  }, getRandNr(3,9) * 1000);
}

function renderCircle(paper, w, h, size, dur, cnt) {
  var prevSize = size;
  size *= 1.2;
  dur *= 1.5;
  cnt++;
  var el = paper.circle(w, h, prevSize).animate({
    fill: "#223fa3", 
    stroke: "#000",
    "stroke-width": 80,
    "stroke-opacity": 0.5,
    "opacity": 0,
    size: size
  }, dur);
  el.toBack();
  if (cnt <  6) {
    setTimeout(function() {
      renderCircle(paper, w, h, size, dur, cnt);
    }, dur/4);
  }
}

// Singleton to get instance of Showcase class.
var Show = function () {
  var showcase = null;
  return {
    and: function() {
      if (showcase != null) {
        return showcase;
      }
      else {
        showcase = new Showcase(arguments[0]);
        return showcase;
      }
    }
  }
}();

var Showcase = Class.create({
  initialize: function(el) {
    this.options = Object.extend({
      duration: 2 // in seconds
    }, arguments[0] || {});
    this.el = el;
  },

  go: function() {
    $(this.el).fade({
      duration: this.options.duration * 2,
      transition: 'bounce'
    }).appear({
      duration: this.options.duration * 3,
      after: (function() {
        Show.and('p').go();
      }).bind(this)
    });
  }
});

