/* vkImagePreload.js */

var	instanceId = 0;

function	vkImagePreload(maxThreads)
{
	this.instanceId = instanceId++;
	this.maxThreads = maxThreads;
	this.currentThreads = 0;
	this.queue = [];
	this.preloads = [];
}

vkImagePreload.prototype.setThreads = function(threads)
{
	this.maxThreads = threads;
}

vkImagePreload.prototype.add = function(image)
{
	if(this.currentThreads < this.maxThreads)
		this._preload(image);
	else
	{
		vkDebug.text('Queueing '+image);
		this.queue[this.queue.length] = image;
	}
}

vkImagePreload.prototype._preload = function(image)
{
	var	idx, self;

	vkDebug.text('Preloading '+image);

	++this.currentThreads;
	idx = this.preloads.length;

	this.preloads[idx] = new Image;

	self = this;

	if(window.addEventListener)
	{
		this.preloads[idx].addEventListener('load', function() { self._onLoad(idx); }, false);
		this.preloads[idx].addEventListener('error', function() { self._onLoad(idx); }, false);
	}
	else
	{
		this.preloads[idx].attachEvent('onload', function() { self._onLoad(idx); });
		this.preloads[idx].attachEvent('onerror', function() { self._onLoad(idx); });
	}

	this.preloads[idx].src = image;
}



vkImagePreload.prototype._onLoad = function(idx)
{
	var	tmp;

	vkDebug.text('INSTANCE '+this.instanceId+' : Image #'+idx+' loaded');

	--this.currentThreads;

	for(var i = 0; this.currentThreads < this.maxThreads && i < this.queue.length; i++)
	{
		if(this.queue[i] != null)
		{
			tmp = this.queue[i];
			this.queue[i] = null;
			this._preload(tmp);
		}
	}

	if(!this.currentThreads)
	{
		vkDebug.text('Cleaning-up references');
		// Cleanup references
		this.queue = [];
		this.preloads = [];
	}
}

