﻿function ShowPageChooserDialog(branchToExclude, title, question, OK_Callback)
{
	var baseDialogHtml = $.template('<div id="pageChooserDialog" class="flora">' +
	'<form id="frmPageChooser" name="frmPageChooser" action="" method="post" >' +
	'<div>${Question}</div>' +
	'<div id="pageChooserList"><ul id="ul-1" class="filetree" /></div>' +
	'</form>' +
	'</div>');
	
	//setup dialog HTML
	$('body').append(baseDialogHtml, {question: question});
	
	PopulatePageList(branchToExclude);

	$("#pageChooserDialog").dialog(
	{
		buttons: 
		{
			'Cancel': function() 
			{ $(this).dialog('close'); }
		},
		title : title,
		height: 300,
		width: 350,
		modal: false,
		close : function()
		{
		  $("#pageChooserDialog").remove();
		  //document.isDialogOpen = false;
		}
	});
	
//	$('#ul-1').treeview({
//		persist: "location",
//		collapsed: true,
//		unique: true
//	});
	
	function PopulatePageList(ExcludedBranch)
	{
	  $.ajax({
	    url: '/rpc/ContentRpcServices/GetPageHierarchyData',
	    success: function (data)
	    {
	      var pageList = { Id: -1, Pagename: "Top Level", ChildPages: data };
	      PopulatePageListChildren(pageList, -1);
	    }
	  });
	}
	
	function PopulatePageListChildren(pageList, parentId)
	{
		if (pageList == null)
		{ return; }

		var listItemTemplate = 
      $.template('<li><span class="folder"><a id="aPage${Id}" href="javascript:;\" >${Pagename}</a></span><ul id="ul${Id}"/></li>');
		//var listTemplate = $.template('<ul id="ul${Id}"></ul>');
		
		var attachmentPoint = $("#ul" + parentId);
		attachmentPoint.append(listItemTemplate, pageList);
		$('#aPage' + pageList.Id).click(function()
		{
			$('#pageChooserDialog').dialog('close');
			if (OK_Callback != null)
			{ OK_Callback.call(this, pageList.Id, pageList.Pagename); }
			return false;
		});

		for (var i = 0; i < pageList.ChildPages.length; i++)
		{ PopulatePageListChildren(pageList.ChildPages[i], pageList.Id); };
	}
}

