
// Keeps a list of elements in the correct z-index stacking order.
function Stack() {
	this.minIndex = 1;
	this.items = [];
}

// Adds an element to this stack.
Stack.prototype.add = function(elem, callback) {
	this.items.push({
		elem: elem,
		callback: callback
	});
}

// Resets all z-indexes to be in order.
Stack.prototype.reorder = function(doCallback) {
	for (var i=0; i<this.items.length; i++) {
		var item = this.items[i];
		$(item.elem).css('z-index', i + this.minIndex);
		
		if (doCallback && item.callback) {
			item.callback(i + this.minIndex);
		}
	}
}

// Moves the given element to the top of the z-order.
Stack.prototype.top = function(elem, doCallback) {
	//log('Stack.top()');
	if (doCallback == undefined) {
		doCallback = true;
	}
	var pos = null;
	for (var i=0; i<this.items.length; i++) {
		if (this.items[i].elem == elem) {
			pos = i;
			break;
		}
	}
	if (pos == -1) {
		alert('Stack.top(): Error, item not found in this.items.');
		return;
	}
	
	var item = this.items[pos];
	// Remove the element
	this.items.splice(pos, 1);
	// Add the element to the end of the list.
	this.items.push(item);
	
	this.reorder(doCallback);
}
