// ******************************************************************* //
// ** 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 };
}

ItemManager.prototype.getItems = function() {
	var result = new Array();
	for (var i = 0; i < this.items.length; i++) {
		if (this.items[i])
			result.push({ item: this.items[i], wasCached: true });
	}
	return result;
}

// Create an item, and add it to the item pool (private method)
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;
}

ItemManager.prototype.freeAllItems = function() {
	this.items = new Array();
	this.loadedItemsPositions = new Object();
}

ItemManager.prototype.updateItem = function(itemId, item) {
	if (this.items[this.loadedItemsPositions[itemId]])
		this.items[this.loadedItemsPositions[itemId]] = item;
}

ItemManager.prototype.itemExists = function(itemId) {
	return (itemId != null && this.loadedItemsPositions[itemId] != null && this.items[this.loadedItemsPositions[itemId]]);
}


