var firstLoad = true;
var openNodes = [];

$(function () { 
	if(nid == 0) firstLoad = false;

	$.post("/library/index.php/manager/getData/" + Directory + "/getParentNode", {nid: nid}, function(parents){
		var treeMenu = $("#treeMenu").tree({
			data : { 
				type : "json",
				async : true,
				opts : {
					method : "POST",
					url : "/library/index.php/manager/getData/" + Directory + "/getSiteTree"
				}
			},
			callback : { 
				beforedata : function (n, t) {
					$(n).select();
					return { id : $(n).attr("id") || 0 }
				},
				onload: function(t) {
					$.each($.parseJSON(parents), function(k, v) {
						openNodes.push(v);
					});
					openBranch(t);
				},
				onselect: catchEvent,
				ondblclk: catchEvent
			}
		});
	});

	function catchEvent (n, t) {
		var url = (URLDirectory != undefined && Directory != URLDirectory) ? URLDirectory : Directory;

		var href = "/e-library/" + url + "?nid=" + $(n).attr("id");

		if(Directory == "books") {
			if(!firstLoad) {
				location.href = href;
			}
		} else {
			if($(n).attr("leaf") == "true") {
				if(!firstLoad) {
					location.href = href;
				}
			} else {
				t.toggle_branch($(n));
			}
		}

		return false;
	}

	function openBranch(t) {
		if(nid > 0) {
			nid = openNodes.shift().id;
			if(nid == 1) nid = openNodes.shift().id;

			if(openNodes.length == 0) {
				t.select_branch($("#" + nid));
				t.open_branch($("#" + nid));
				firstLoad = false;
			} else {
				t.open_branch($("#" + nid), true, function() {
					openBranch(t);
				});
			}
		}
	}

	$(".ArticleMenu").tabs({
		collapsible: true,
		selected: -1
	});

	$(".order").click(function() {
		var c = $(this);
		var bid = c.attr("bid");
		var cat = c.attr("cat");
		var img = $("#order-status-" + bid);
		
		$.ajax({
			url: '/library/index.php/order/addBook',
			type: "POST",
			data: 'bid=' + bid + '&cat=' + cat,
			dataType: 'json',
			success: function(data) {
				if(data.success) {
					c.remove();
					img.attr("src", "/library/icons/htmleditor/basket_add.png");
					$("<span>&nbsp;Добавлено к заказу</span>").insertAfter(img);
				} else {
					c.remove();
					img.attr("src", "/library/icons/htmleditor/error.png");
					$("<span>&nbsp;Книга уже присутствует в списке</span>").insertAfter(img);
				}
			}
		});

		return false;
	});
});

