/*------------------------------------------------------------------------------------
 
	Preloader
	A very simple image preloader object
  
 	Usage:
 	
    Preloader.add(path);
    Preloader.onFinish(func);
    Preloader.load();
    
      path: 		A string or array of strings of image paths to preload
      func:     A function or array of functions to be called after images are loaded

      load():   Start the preloader
      
------------------------------------------------------------------------------------*/
progressBar = new Image();
progressBar.src = "./images/percentage.png";
progressBar2 = new Image();
progressBar2.src = "./images/percentImage.png";
	  
var Preloader = {
  finishCallbacks: [],
  updateCallbacks: [],
  images: [],
  loadedImages: [],
  imagesLoaded: 0,
  imageCount: 0,
  
  add: function(image){
    if (typeof image == 'string') { 
		this.images.push(image); 
		this.imageCount++; 
	}
    if (typeof image == 'array' || typeof image == 'object'){
      for (var i=0; i< image.length; i++){
        this.images.push(image[i]);
		this.imageCount++;
      }
    }
  },
  onUpdate: function(func){
	if (typeof func == 'function') this.updateCallbacks.push(func);
    if (typeof func == 'array' || typeof func == 'object'){
      for (var i=0; i< func.length; i++){
        this.updateCallbacks.push(func[i]);
      }
    }  
  },
  onFinish: function(func){
    if (typeof func == 'function') this.finishCallbacks.push(func);
    if (typeof func == 'array' || typeof func == 'object'){
      for (var i=0; i< func.length; i++){
        this.finishCallbacks.push(func[i]);
      }
    }
  },
  load: function(){
    for(var i=0; i<this.images.length; i++){
      this.loadedImages[i] = new Image();
      this.loadedImages[i].onload = function(){ Preloader.checkFinished.apply(Preloader) }
      this.loadedImages[i].src = this.images[i];
    }
  },
    
  checkFinished: function(){
    this.imagesLoaded++;
	this.fireUpdate();
    if (this.imagesLoaded == this.images.length) this.fireFinish();
  },  
  fireUpdate: function() {
	for (var i=0; i<this.updateCallbacks.length; i++){
      this.updateCallbacks[i]();
    }  
  },
  fireFinish: function(){
    for (var i=0; i<this.finishCallbacks.length; i++){
      this.finishCallbacks[i]();
    }
    this.images = [];
    this.loadedImages = [];
    this.imagesLoaded = 0;
	this.imageCount = 0;
    this.finishCallbacks = [];
	this.updateCallbacks = [];
  }
}