/* 
	j123 -- JavaScript common library
	mail: sebastian.hanula@gmail.com
	www:  http://www.hanula.com/lab/j123

	j123 sortable HTML list library (using drag & drop)
*/


j123.drag.SortableList = {
	list_handle:null,
	items:null,
	temp_item:null,
	onChangeOrder:null,
	init: function(args) {
		var list = $(args['list']);
		this.onChangeOrder = args['onChangeOrder'];
		this.list_handle = list;
		this.items = list.getElementsByTagName('li');
		for(var i=0;i<this.items.length;i++) {
			
			this.items[i].setAttribute('orig_order',i);
			this.items[i].setAttribute('list_order',i);
			this.items[i].onDragStart = this.onItemDragStart;
			this.items[i].onDrag = this.onItemDrag;
			this.items[i].onDragEnd = this.onItemDragEnd;
			
			j123.drag.init(this.items[i],this.items[i]);
		}
	},

	sortItems : function(item_top) {
		
		var item = j123.drag.object;
		
		var items = j123.drag.SortableList.items;
		var y = parseInt(item.style.top);
		var height = parseInt(item.offsetHeight); 
		var item_index = parseInt(item.getAttribute('list_order'));
		y += item_index*height;

		var index =  Math.floor(y / height); if(index < 0) index=-1;
		else if(index > items.length-1) index = items.length-1;

		if(!isNaN(index)) {

			if(index > item_index) {
			 		j123.drag.SortableList.list_handle.insertBefore(items[index] ? items[index]:null,item);
					item_top -= height;
			} else if(index < item_index -1 && (item.prev_index!=index)) {
						j123.drag.SortableList.list_handle.insertBefore(items[index+1],item ? item.nextSibling:null);
						item.prev_index = item_index;
						item_top += height;
			}
		}
		
		for(var i=0;i<items.length;i++) {
			items[i].setAttribute('list_order',i);
		}
		
		return item_top;
	},
	onItemDragStart : function(x,y) {
		j123.drag.object.style.top=0;	
		j123.drag.object.style.position='relative';
	},
	onItemDrag : function(x,y,cx,cy,event) {
		y = j123.drag.SortableList.sortItems(y);
		return {y:y};
	},
	
	onItemDragEnd: function(x,y,cx,cy) {
		j123.drag.object.style.position='static';
		
		if(j123.drag.SortableList.onChangeOrder) {
			j123.drag.SortableList.onChangeOrder(j123.drag.SortableList.items);
		}
	}
};