// Valid "type" values for createDivs:
//   "empty"
//   "full"

function Animator (numDivs, divOffset, maxIters, type) {
  this.created = false;
  this.numDivs = numDivs;
  this.divOffset = divOffset;
  this.maxIters = maxIters;
  this.starttime = null;
  this.createDivs(type);
}

Animator.prototype = {
  prefix: "animator_div",
  start: function() {
    this.numIters = 0;
    this.starttime = new Date();
    this.animate(0, this.maxIters, this.numDivs, this.prefix,
		 this.divOffset, 0,
		 window.innerWidth - 100 - this.numDivs * this.divOffset,
		 this.starttime, this.animate);
  },
  createDivs : function(type) {
    if (this.created) {
      return;
    }
    if (type != "empty" && type != "full") {
      alert("Unknown type, dude");
      return;
    }
    for (var i = 0; i < this.numDivs; ++i) {
      var node = document.createElement("div");
      node.setAttribute("style",
                        "width: 100px; height: 100px; background: red; " +
                        "position: absolute; top: " + i*this.divOffset  +
			"px; right: " + i*this.divOffset + "px;");
      node.setAttribute("id", this.prefix+i);
      if (type == "full") {
        var table = document.createElement("table");
        var tbody = document.createElement("tbody");
	var tr = document.createElement("tr");
        var td = document.createElement("td");
        var span = document.createElement("span");
        span.style.color = "white";
        span.appendChild(document.createTextNode("A text"));
        td.appendChild(span);
        tr.appendChild(td);
        // Make 6 copies of the tr
        tbody.appendChild(tr);
        tr = tr.cloneNode(true);
        tbody.appendChild(tr);
        tr = tr.cloneNode(true);
        tbody.appendChild(tr);
        tr = tr.cloneNode(true);
        tbody.appendChild(tr);
        tr = tr.cloneNode(true);
        tbody.appendChild(tr);
        tr = tr.cloneNode(true);
        tbody.appendChild(tr);
        table.appendChild(tbody);
        node.appendChild(table);
      }
      window.document.body.appendChild(node);
    }
    this.created = true;
  },
  animate: function(numIters, maxIters, numNodes, nodePrefix,
		    divOffset, rightPos, width, starttime, continuation) {
    ++rightPos;
    ++numIters;
    if (rightPos > width) {
      rightPos = 0;
    }
    for (var i = 0; i < numNodes; ++i) {
      document.getElementById(nodePrefix+i).style.right =
        (rightPos + i*divOffset) + "px";
    }

    if (numIters < maxIters) {
      setTimeout(continuation, 0, numIters, maxIters, numNodes, nodePrefix,
		 divOffset, rightPos, width, starttime, continuation);
    } else {
      var end = new Date();
      alert("Elapsed time: " + (end - starttime) + "ms");
    }
  }  
};
