/**
 * Copyright (c) 2007 Timothy Grant Vogelsang
 * 
 * Author: Timothy Grant Vogelsang <tvogelsang@esolutionsgroup.ca>
 */
var SortableDataList = Class.create();

SortableDataList.prototype = {
	// This public function initializes the DataGridX.
	initialize: function (parameters) {
		this.parameters = parameters;
		this.registerSortable();
	},
	
	// This public function gets the parent object.
	getParent: function() {
		return $(this.parameters.parentId);
	},
	
	// This public function gets the parentId value.
	getParentId: function() {
		return this.parameters.parentId;
	},
	
	// This public functions gets the allow sortable value.
	getAllowSortable: function() {
		return this.parameters.allowSortable;
	},
	
	// This public function gets the sort value.
	getSort: function() {
		return this.parameters.sort;
	},
	
	// This public function gets the update url value.
	getUpdateUrl: function() {
		return this.parameters.updateUrl;
	},
	
	// This public function registers the sortable element.
	registerSortable: function() {
		if (this.getAllowSortable() && this.getParent()) {
			setTimeout(function() {
				Sortable.create(this.getParentId(),
					{
						constraint: 'vertical',
						overlap: 'vertical',
						handle: this.parameters.handle,
						hoverclass: 'SortableHover',
						ghosting: false,
						onUpdate: this.onUpdate.bindAsEventListener(this),
						scroll: window,
						tag: 'div'
					} ); }.bindAsEventListener(this),
				100);
				
		}
	},
	
	// This public function handles the sortable update.
	onUpdate: function(e) {
		var serialize = Sortable.serialize(this.getParentId(), { name: 'key' } );	
		
		serialize = serialize.replace(/&key\[\]=/g, ',').replace(/key\[\]=/g, '');
		
		if (this.getUpdateUrl()) {
			new Ajax.Request(this.getUpdateUrl() + '?Keys=' + serialize);
		}
		else if (this.getSort()) {
			var nodes = $A(serialize.split(','));
			
			nodes.each( function(node) {
					var parent = $(this.getParentId() + '_' + node);
					
					if (parent.link)
						$(parent.link).value = nodes.indexOf(node);
				}.bindAsEventListener(this)
			);
		}
	}
	
}

// Sortables inside each other (fix)
Sortable.destroy = function(element) {
	var s = Sortable.options(element);
    
	if(s) {
		if (element.id == s.element.id) {
			Draggables.removeObserver(s.element);
			s.droppables.each(function(d){ Droppables.remove(d) });
			s.draggables.invoke('destroy');
	      
			delete Sortable.sortables[s.element.id];
		}
	}
}

// Microsoft AJAX .NET load script
if (typeof(Sys) != "undefined")
	Sys.Application.notifyScriptLoaded();