
var gImageLoader = new ImageLoader();

function ImageLoader()
{
	this.imageCount = 0;
	this.images = new Array();
	this.imagesLoaded = 0;
	
	this.Load = ImageLoad;
	this.FindImage = FindImage;
	this.FindImageIndex = FindImageIndex;
	this.GetImage = GetImage;
	this.OnLoadCallback = OnLoadCallback;

	this.LoadedCallback;
	
	this.loaded = false;
	
	gConsole.Log(1, "[IMG] Init");
}

function ImageLoad(name)
{
	gConsole.AssertMsg(this.loaded == false, "Late image load");
	gConsole.AssertMsg(FindImageIndex(name) == undefined, "Already loaded image");
	
	gConsole.Log(3, "[IMG] Load '" + name + "' (" + this.imageCount + ")");
	
	var i = this.imageCount;
	
	this.images[i] = new Image();
	this.images[i].src = name;
	this.images[i].name = name;
	this.images[i].onload = ImageOnLoad;
	this.images[i].onerror = ImageOnError;
	this.images[i].onabort = ImageOnError;
	
	this.imageCount++;
	
	return this.images[i];
}

function GetImage(index)
{
	gConsole.AssertMsg(index >= 0 && index < this.images.length, "[IMG] GetImage Failed " + index + " (expected range [0," + (this.images.length - 1) + "])");
	
	return this.images[index];
}

function FindImage(name)
{
	gConsole.Log(9, "[IMG] FindImage " + name);
	
	var imageIndex = this.FindImageIndex(name);
	
	return gImageLoader.images[i];
}

function FindImageIndex(name)
{
	gConsole.Log(8, "[IMG] FindImageIndex '" + name + "'");
	
	var length = gImageLoader.images.length;
	for(var i = 0; i < length; i++)
	{
		if(gImageLoader.images[i].name == name)
		{
			return i;
		}
	}
}

function ImageOnLoad()
{
	gImageLoader.imagesLoaded++;
	
	gConsole.Log(3, "[IMG] OnLoad " + "(" + gImageLoader.imagesLoaded + "/" + gImageLoader.imageCount + ")");
	
	if(gImageLoader.imagesLoaded == gImageLoader.imageCount)
	{
		gImageLoader.loaded = true;
		gConsole.Log(1, "[IMG] LoadedCallback");
		gImageLoader.LoadedCallback();
	}
}

function ImageOnError()
{
	gConsole.Log("[IMG] OnError");

	var length = gImageLoader.images.length;
	for(var i = 0; i < length; i++)
	{
		gConsole.Log("[IMG" + i + "] name:" + gImageLoader.images[i].name + " src:" + gImageLoader.images[i].src);
	}

	gConsole.AssertNow("[IMG] OnError");
}

function OnLoadCallback(callbackFunction)
{
	gImageLoader.LoadedCallback = callbackFunction;
	if(gImageLoader.imageCount == 0)
	{
		gConsole.Log(1, "[IMG] No images to load");
		gImageLoader.LoadedCallback();		
	}
}