tt = {};

tt.Loader = function (pathRoot, paths) {
  this.pathRoot = pathRoot;
  this.paths = paths;
};

tt.Loader.usedPaths = [];

tt.Loader.create = function (root /* optional */, paths) {
  if (paths == undefined) {
    paths = root;
    root = tt.Loader.defaultPathRoot;
  }
  if (typeof(paths) == 'string') {
    paths = [paths];
  }
  return new tt.Loader(root, paths);
};

tt.Loader.defaultPathRoot = '/tt/20/';

tt.Loader.prototype.listPaths = function () {
  var p = [];
  for (var i = 0; i < this.paths.length; i++) {
    p.push(this.pathRoot + this.paths[i]);
  }
  return p;
};

tt.Loader.prototype.load = function (onComplete) {
  var p = this.listPaths();
  var recurse = function (i) {
    if (i >= p.length) {
      onComplete();
      return;
    }
    if ($A(tt.Loader.usedPaths).indexOf(p[i]) == -1) {
      tt.Loader.usedPaths.push(p[i]);
      var s = document.createElement('script');
      s.type = 'text/javascript';
      s.src = p[i];
      if (false) {
        s.src += '?' + Math.random();
      }
      Event.observe(s, 'load', function () {
// if ($('loadingStatus')) {
//   $('loadingStatus').remove();
// }
        recurse(i + 1);
      });
      Event.observe(s, 'readystatechange', function () {
        if (s.readyState == 'loaded' || s.readyState == 'complete') { 
// if ($('loadingStatus')) {
//   $('loadingStatus').remove();
// }
          recurse(i + 1);
        }
      });
// new Insertion.Bottom($$('body')[0], '<div id="loadingStatus" style="position: absolute; top: 10px; left: 10px; background: #ffffff; padding: 5px; border: solid 1px #000000;">loading ' + p[i] + '</div>');
      new Insertion.Bottom($$('head')[0], s);
    } else {
      recurse(i + 1);
    }
  };
  recurse(0);
};

tt.Loader.prototype.loadCSS = function (onComplete) {
  var p = this.listPaths();
  var recurse = function (i) {
    if (i >= p.length) {
      onComplete();
      return;
    }
    var l = document.createElement('link');
    l.href = p[i];
    l.rel = 'stylesheet';
    l.type = 'text/css';
    new Insertion.Bottom($$('head')[0], l);
    recurse(i + 1);
  };
  recurse(0);
};

tt.Loader.getPath = function (path) {
  return tt.Loader.defaultPathRoot + path;
};
