/** list menul */
(function ($, LOGA) {

var sortOpt = {
	maxDepth: 2,
	depthLock: false,
	itemGroupData: 'ms-alias',
	listNodeName: 'ul',
	itemNodeName: 'li'
},
updateOrder = function(e) {
	updateOrders();
},
saveOrders = function (orders) {
	$.post(GV.URL.SORT_MENU,
		{sort:orders},
		function(data) {
			if(1 != data.status) {
				alert(data.message);
			}
		}, 'json');
},
updateOrders = function (ele, orders) {
	var root = false;
	if(typeof ele === 'undefined') {
		ele = $('.tree > ul');
		root = true;
		orders = {};
	}

	var index = 1;
	ele.children('li').each(function() {
		var $this = $(this),
			pid = $this.parent().parent().data('id') ? $this.parent().parent().data('id') : 0,
			order = index++;

		orders[$this.data('id')] = {pid:pid, order:order};

		var $ul = $this.children('ul');
		if($ul.length) {
			updateOrders($ul, orders);
		}
	});

	if(root) {
		saveOrders(orders);
	}
}

$('.tree').tree(sortOpt).on('change', updateOrder);
$('#tree-menu').on('click', function(e) {
	var target = $(e.target),
		action = target.data('treeNestableAction');
	if(action === 'expand-all') {
		$('.tree').tree('expandAll');
	}
	if(action === 'collapse-all') {
		$('.tree').tree('collapseAll');
	}
});

})(jQuery, LOGA);
