/**
 * Widget for handling the drag/drop functionality for a list
 */
nmdgf.widgets.SortableList = function(url) {
	this.items = [];
	this.url = url;
}

nmdgf.widgets.SortableList.prototype = {
		
	/**
	 * URL to post new list order to 
	 */
	url : null,
	
	/**
	 * Array of choices, indexed by the <li> id, with the value of the position element id
	 */
	items : null,
	
	/**
	 * ID of List element, assigned through addChoice
	 */
	listId : null,
		
	/**
	 * Called for each hunt choice.  Sets up the drag/drop widget, and callback for updating
	 * the choices ordering.
	 */
	addItem : function(objectId, listItemId, positionId) {
		if(this.listId == null) {
			this.listId = nmdgf.byId(listItemId).parentNode.id;
		}
		this.items[objectId] = { 'listItemId' : listItemId, 'positionId' : positionId };
		var dd = new nmdgf.widgets.DragDropListItem(listItemId);
		dd.endDragEvent.subscribe(function() {
			nmdgf.widgets.LoadingPanel.show('Updating List');
			var itemIds = nmdgf.dom.getListAttributeOrdered(this.listId, 'objectId');
	        nmdgf.ajax(
		        'POST', 
	        	this.url, 
	        	{ success: function(r) {
		        	nmdgf.widgets.LoadingPanel.hide();
		        	this.updatePositionValues(nmdgf.parseJSON(r.responseText));
	        	}, scope: this }, 
	        	'orderedList='+nmdgf.stringifyJSON(itemIds)
	    	);
		}, this, true);
	},
	
	/**
	 * Updates the position value in the UI upon completion of a drag/drop event during the re-ordering
	 */
	updatePositionValues : function(items) {
		for(var idx in items) {
    		var item = items[idx];
    		nmdgf.byId(this.items[item.id].positionId).innerHTML = item.position;
    	}
	}
	
};
