var ImagePreloader = Class.create();

ImagePreloader.prototype = {
  // progressBar : {
  //   height: 15,
  //   width: 150,
  //   image1: "images/preload/black.gif",
  //   image2: "images/preload/blue.gif",
  // },
  imageList : null,
  // _coverage: null,
  
  //??
  _preImages: [],
  currCount: 0,
  _loadedImages: [],
  // i: null,
  // covered: null,
  timerID: null,
  // _leftOverWidth: null,
  
  initialize: function(images, options) {
    this._preImages = [];
    this._loadedImages = [];
    this.currCount = 0;
    this.timerID = null;
    
    this.imageList = images;
    var my_options = options || { };
    
    this.afterLoading = my_options.afterLoading || function() { };
    delete my_options.afterLoading;
    this.afterCheck = my_options.afterCheck || function() { };
    delete my_options.afterCheck;
    
    // Object.extend(this.progressBar, my_options.progressBar);
    // delete(my_options.progressBar);
    
    // if (document.images) {
      // var dots = [];
      // dots[0] = new Image(1,1);
      // dots[0].src = this.progressBar.image1; // default preloadbar color (note: You can substitute it with your image, but it has to be 1x1 size)
      // dots[1] = new Image(1,1);
      // dots[1].src = this.progressBar.image2; // color of bar as preloading progresses (same note as above)
      
      // this._coverage = Math.floor(this.progressBar.width/this.imageList.length);
      // this._leftOverWidth = this.progressBar.width % this._coverage;
    // }
    Object.extend(this, my_options);
    this.loadImages();
  },

  loadImages: function() {
    this.imageList.each(function(el){
      var tmp = new Image();
      tmp.src = el;
      this._preImages.push(tmp);
      this._loadedImages.push(false);
    }.bind(this));
    // this.checkLoad();
    if(this.imageList.length>0)
      this.timerID = this.timerID || new PeriodicalExecuter(this.checkLoad.bind(this), 0.5);

  },

  checkLoad: function() {
    debug ? console.log(this.currCount+' -- '+this._preImages.length) : null;
    if (this.currCount == this._preImages.length) {
      this.timerID.stop();
      debug ? console.log('avant afterLoading') : null;
   		this.afterLoading();
  		return;
  	}
    else
    {
      for (var i = 0; i < this._preImages.length; i++) {
        if (this._loadedImages[i] == false && this._preImages[i].complete) {
          this._loadedImages[i] = true;
          // eval("document.img" + this.currCount + ".src=this.progressBar.image2").bind(this);
          this.currCount++;
        }
      }
      this.afterCheck();
    }
  },
  
  getImages: function() {
    return this._preImages;
  },
  
  afterCheck: function() {
    
  },
  
  afterLoading: function() {
  }
}
