window.addEvent('domready', function() {

	$$('ul.sortables').each(function (el) 
	{
		new Sortables($(el.id), {
				opacity: 0.6,
				cloneOpacity: 0.85,
				constrain: true,
		        clone: true,
				revert: true,
				snap: 4,
			// code to run when sortables is added to the list
				initialize: function()
				{
					// check each list item has the right class name
						var setup_ok = true;

						this.elements.each(function(el, i)
						{
							var className = String(el.getProperty('className') || el.className);
							if (!className.match(/sortables_id([0-9]+)/)) setup_ok = false;
						});

					// does each list item have the right class names?
						if (!setup_ok) alert("The list items of the sortable list '" + el.id + "' require a 'class' attribute in the following format...\n\nsortables_id###\n\ne.g. sortables_id76");
				},
			// code to run when moved something
				onComplete: function()
				{
					// find related button
						var btn_id = "btn_" + el.id;

					// find related hidden field
						var order_id = "hidden_" + el.id;

					if ($(order_id))
					{
						// first lets make button visible...
							if ($(btn_id)) $(btn_id).setStyle('visibility', 'visible');

						// lets create order string
							$(order_id).value = "";

						// create function to serialize the list
							var getIDs = function(el, i)
							{
								var className = String(el.getProperty('className') || el.className);

								var id = className.match(/sortables_id([0-9]+)/);
								$(order_id).value+= "change_order[" + i + "]=" + id[1] + "&";
							}

							this.list.getChildren().each(getIDs, this);
					}
					else
						alert("Nothing to do with results!  Please make sure there is a hidden input field called '" + order_id + "'!");

				}
		 
		});

	});
});

