// JavaScript Document

/*			
	index		Sort position (dynamic)
	id			Item ID (static)
	nr			Original sort position (static)		
*/

function SortableCollection(onChange) {
	this.itemIdByIndex 		= new Array();
	this.itemIndexById 		= new Object();
	
	this.itemIndexByNr 		= new Array();
	this.itemNrByIndex 		= new Array();
	this.items 						= 0;
	this.onChange					= onChange;
}

SortableCollection.prototype.addItem = function(id) {
	this.itemIdByIndex[this.items] 	= id;
	this.itemIndexById[id] 					= this.items;
	
	this.itemNrByIndex[this.items] 	= this.items;
	this.itemIndexByNr[this.items] 	= this.items;
	this.items++;
}

SortableCollection.prototype.moveItem = function(thisId, delta) {
	var thisIndex 	= this.itemIndexById[thisId];
	var otherIndex 	= this.itemIndexById[thisId] + delta;
	
	var thisNr 			= this.itemNrByIndex[thisIndex];
	var otherNr 		= this.itemNrByIndex[otherIndex];
	var otherId;
	
	if(delta != 0 && otherIndex >= 0 && otherIndex < this.items) {
		
		otherId = this.itemIdByIndex[otherIndex];				
		this.itemIdByIndex[otherIndex] 	= thisId;
		this.itemIndexById[otherId] 		= thisIndex;
		this.itemIdByIndex[thisIndex] 	= otherId;
		this.itemIndexById[thisId] 			= otherIndex;

		this.itemNrByIndex[otherIndex] 	= thisNr;
		this.itemIndexByNr[otherNr] 		= thisIndex;
		this.itemNrByIndex[thisIndex] 	= otherNr;
		this.itemIndexByNr[thisNr] 			= otherIndex;
		
		this.onChange(thisNr);
	}
}

SortableCollection.prototype.dump = function() {
	alert(this.itemIdByIndex.join());
}

SortableCollection.prototype.getNrByIndexArray = function() {
	return this.itemNrByIndex;
}

SortableCollection.prototype.getIdByIndexArray = function() {
	return this.itemIdByIndex;
}

