$(function() {
	//TreeView
	$("#toc li.closed").each(function(i) {
		var $this = $(this);
		$this.addClass("chidrenNotLoaded");
		$this.append($("<ul/>").html("<li><span>&nbsp;</span></li>"));
	});

	var $ul = $("#toc ul:first");
	$ul.addClass("filetree")
	$ul.treeview({
		persist: "location"
		, toggle: function() {
			var $this = $(this);

			if ($this.hasClass("chidrenNotLoaded")) {
				var childList = $this.removeClass("chidrenNotLoaded").find("ul");
				childList.empty();

				loadChildren(this.id.substr(2));
			}
		}
	});

	//Scroll to selected node
	var $selected = $(".selected").parent().parent();
	$("#toc").scrollTo($selected);

	//Search items
	$("form.search input.query").bind("focus", query_focus);


	var w = $.cookie("doctocwidth");
	if (w) {
		$("#toc").css("width", w + "px");
	}

	$("#toc").resizable({
		handles: "e"
		, minWidth: 50
		, maxWidth: 550
		, stop: function(event, ui) {
			$.cookie("doctocwidth", $("#toc").width(), { expires: 28 });
		}
	});
});
	
//TreeView
function loadChildren(id) {
	$.ajax({
		type: "POST",
		url: "../doc-viewer/toc.asmx/GetTopics",
		data: "{setID:" + DOC_SET_ID + ",parentID:" + id + "}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(msg) {
			var $ul = $("#dt" + msg.Parent + " ul");

			for (var i = 0; i < msg.Topics.length; i++) {
				var t = msg.Topics[i];

				var $li = $("<li />");

				if (t.HasChildren) {
					$li.addClass("closed");
				}
				$li.attr("id", "dt" + t.ID);
				$li.attr("title", t.Title);

				var $span = $("<span />");
				$span.addClass(t.HasChildren ? "folder" : "file");

				var $a = $("<a />");
				$a.attr("href", t.Path);
				$a.text(t.Title);

				$a.appendTo($span);
				$span.appendTo($li);

				if (t.HasChildren) {
					$li.addClass("chidrenNotLoaded");
					$li.append($("<ul><li><span>holder</span></li></ul>"));
				}

				$li.appendTo($ul);
				$("#toc ul:first").treeview({
					add: $li
				});				
			}
		}
	});
}


function query_focus(e) {
	var $q = $(this);

	if ($q.hasClass("query-inactive")) {
		$q.removeClass("query-inactive")	
		$q.val("");
	}
}
