(function($)
{
	// This script was written by Steve Fenton
	// http://www.stevefenton.co.uk/Content/Jquery-Drag-And-Drop-Sort/
	// Feel free to use this jQuery Plugin
	// Version: 3.0.0
	
	var classModifier = "dds";
	var nextSetIdentifier = 0;
	var currentItem = null;
	var currentTarget = null;
	var itemInTransit = false;
	
	var insertClass;
	var movingClass;
	var itemClass;
	
	var myArray = [];
	var str = '';
	
	// Captures drops
	$(document).mouseup( function () {
		if (itemInTransit && currentTarget != null) {
			var clone = $(currentItem).clone();
			bindEvents(clone);
			$(currentTarget).before(clone);
			$(currentItem).remove();
		}
		currentItem = null;
		currentTarget = null;
		itemInTransit = false;
		$("." + movingClass).removeClass(movingClass);
		
		$('#model-list p').each(function() {
			 str += this.id + ',';
		});
		
		str = '';
	});

	// Bind the drag drop events
	function bindEvents(item) {
	
		$(item).mousedown( function () {
			currentItem = $(this);
			itemInTransit = true;
			$(this).addClass(movingClass);
			return false;
		});
		
		$(item).mouseenter( function () {
			if (itemInTransit) {
				currentTarget = $(this);
				$(this).addClass(insertClass);
				return false;
			}
		});
		
		$(item).mouseout( function () {
			$(this).removeClass(insertClass);
		});
	}
	
	$.fn.draganddropsort = function (settings) {
	
		var config = {
			classmodifier: "dds",
			appendlastline: true
		};
		
		if (settings) {
			$.extend(config, settings);
		}
		
		classModifier = config.classmodifier;
		insertClass = classModifier + "insert";
		movingClass = classModifier + "moving";
		itemClass = classModifier + "item";

		return this.each(function () {
		
			// Append a spare line, which allows items to be dragged past the last item
			if (config.appendlastline) {
				var clone = $(this).children().first().clone();
				var children = $(clone).children();
				if (children.length == 0) {
					$(clone).html("&nbsp;");
				} else {
					$(clone).children().each(function () {
						$(this).html("&nbsp");
					});
				}
				$(this).append(clone);
			}
		
			// Bind events for sortable items
			$(this).children().each(function () {
				bindEvents(this);
				$(this).addClass(itemClass);
			});
			
			nextSetIdentifier++;
		});
	};
})(jQuery);
