// ******************************************************************* //
// ** Handles the creation, queueing and recycling of list of elements //
// ******************************************************************* //

ItemManager = function(maxItems, creatorObject, creatorMethod) {
	this.items = new Array();
	this.loadedItemsPositions = new Object();
	this.maxItems = (!maxItems ? Number.POSITIVE_INFINITY : maxItems);
	this.creatorObject = creatorObject;
	this.creatorMethod = creatorMethod;
}

// Returns an item. If it doesn't exist, it creates it, or recycles an existing one if the maximum allowed has already been reached
ItemManager.prototype.getItem = function(itemId) {
	// If it is already loaded, return it
	if (this.loadedItemsPositions[itemId] != null) {
		//** move it to the bottom of the recycle queue
		return { item: this.items[this.loadedItemsPositions[itemId]], wasCached: true };
	}

	// Create or recycle one and return it
	if (this.items.length < this.maxItems)
		var item = this.createItem();
	else
		var item = this.recycleItem();

	this.loadedItemsPositions[itemId] = item.index;
	return { item: item.obj, wasCached: false };
}

// Create an item, and add it to the item pool
ItemManager.prototype.createItem = function() {
	var newItem = this.creatorObject[this.creatorMethod]();
	this.items.push(newItem);
	//** add it to the bottom of the recycle queue

	return { obj: newItem, index: this.items.length - 1 };
}

ItemManager.prototype.recycleItem = function() {
	//** Replace this with a proper image recycler
	return this.createItem();
}

// Completely eliminates the item from the list
ItemManager.prototype.freeItem = function(itemId) {
	this.items[this.loadedItemsPositions[itemId]] = null;
	this.loadedItemsPositions[itemId] = null;
}


