var Preloader = function(obj, cb){
  this.Preload = 0;
  this.Preloaded = 0;
  this.obj = obj;
  this.cb = cb;
  this.html = this.obj;
  
  this.PreloadImged = function(img){
    if(img.toload){
      img.toload = false;
      img.onload = null;
      this.Preloaded++;
      if(this.Preloaded >= this.Preload){
        document.body.removeChild(this.el);
        this.el.style.display = '';
        this.el.style.zIndex = 1;
        this.cb(this.obj);
      }
    }
  };
  this.setTime = function(img){
    var myself = this;
    setTimeout(function(){ myself.PreloadImged(img); }, 1000);
  };
  
  this.el = document.createElement('div');
  this.el.style.display = 'none';
  this.el.style.position = 'absolute';
  this.el.style.top = '0px';
  this.el.style.left = '0px';
  this.el.style.zIndex = '-10';
  if(typeof(this.obj) === "object"){
    this.html = this.obj.html;
    this.obj.el = this.el;
  }
  this.el.innerHTML = this.html;
  var tw = document.createTreeWalker(this.el,1,null,true);
  var now, myself = this;
  while(now = tw.nextNode()){
    if(now.tagName && now.tagName.toLowerCase() == "img"){
      if(!now.complete){
        now.toload = true;
        this.setTime(now);
        now.onload = function(){myself.PreloadImged(this)};
        this.Preload++;
      }
    }
  }
  if(!this.Preload){
    this.el.style.display = '';
    this.el.style.zIndex = 1;
    this.cb(this.obj);
  }else{
    document.body.appendChild(this.el);
  }
}

function setLoading(el){
  if(typeof(el) !== "object"){
    if(el[0] == "#"){
      if(!(el = document.getElementById(el.substring(1,el.length)))) return;
    }else return;
  }
  while(el.firstChild) el.removeChild(el.firstChild);
  var img = document.getElementById("loading");
  var toimg = img.cloneNode(true);
  toimg.style.display = "block";
  toimg.style.marginTop = parseInt((el.offsetHeight-img.offsetHeight)/2,10)+'px';
  toimg.style.marginLeft = parseInt((el.offsetWidth-img.offsetWidth)/2,10)+'px';
  el.appendChild(toimg);
}
