
function parseTree(ul){
	var tags = [];
	ul.children("li").each(function(){
		var subtree =	$(this).children("ul");
		if(subtree.size() > 0)
			tags.push([$(this).attr("id"), parseTree(subtree)]);
		else
			tags.push($(this).attr("id"));
	});
	return tags;
}

$(document).ready(function(){
		
	$("li.tree_item span").droppable({
		tolerance		: "pointer",
		hoverClass		: "tree_hover",
		drop			: function(event, ui){
			var dropped = ui.draggable;
			dropped.css({top: 0, left: 0});
			var me = $(this).parent();
			if(me == dropped)
				return;
			var subbranch = $(me).children("ul");
			if(subbranch.size() == 0) {
				me.find("span").after("<ul></ul>");
				subbranch = me.find("ul");
			}
			var oldParent = dropped.parent();
			subbranch.eq(0).append(dropped);
			var oldBranches = $("li", oldParent);
			if (oldBranches.size() == 0) { $(oldParent).remove(); }
		}
	});
	
	$("li.tree_item").draggable({
		opacity: 0.5,
		revert: true
	});
	
	$("#save").click(function(){
		/*
		var tree = $.toJSON(parseTree($("#tag_tree")));
		$.post("@saveTags", {tags: tree}, function(res){
			$("#printOut").html(res);
		});
		*/
		$.debug.print_r(parseTree($("#tag_tree")), "printOut", false);
	});

	
});
