﻿// Image Preloader script by Julian Grinblat
// Gets a list of image paths, and loads them.
// When it finishes, it callbacks to the client

var ImagePreloader = function(images, callback)
{
    this.callback = callback;
    this.paths = images;
    this.validPaths = new Array(); // Will store the valid paths in this array
    this.count = 0;
	this.CountIncreased = function(count) {}; // Event to be fired each time the count raises
    
    this.StartLoading = function()
    {
        var currImg;
        var i;
        var totalImgs = this.paths.length;
        if(totalImgs > 0)
        {
	        for(i = 0; i < totalImgs; i++)
	        {
	            currImg = document.createElement("img");
	            addEvent(currImg, "load", createObjectCallback(currImg, this.OnImageLoaded, [this]));
	            addEvent(currImg, "error", createObjectCallback(currImg, this.OnImageError, [this]));
	            currImg.setAttribute("src", this.paths[i]);
	        }
        }
        else
        {
        	this.DoCheck();
        }
    }
    
    this.OnImageLoaded = function(thisObj)
    {
        thisObj.count++;
        thisObj.validPaths.push(this.src); // Add this to the valid paths
        thisObj.DoCheck();
    }
    
    this.OnImageError = function(thisObj)
    {
    	thisObj.count++;
    	thisObj.DoCheck();
    }
    
    this.DoCheck = function()
    {
    	var totalImgs = this.paths.length;
        if(this.count == totalImgs)
        {
            if(this.callback != null)
            {
                // Finished loading, call the callback
                this.callback();
            }
            
        }
		else
		{
			this.CountIncreased(this.count);
		}
    }
}