<%@  page pageEncoding="utf-8" contentType="text/html;charset=utf-8" isELIgnored ="false" %>
<%@ taglib prefix="iman" uri="/WEB-INF/iman.tld" %>
<%--<%@ taglib uri="http://java.sun.com/jsp/jstl/core" --%>
<%--  prefix="c" %> --%>


<iman:stringtable bundle="DevResources" />
<iman:stringtable bundle="FwResources" />

<HTML>
<HEAD>
<TITLE>TreeResultsSS</TITLE>
<iman:eMFrameScripts/>
<LINK href="<iman:moduleUrl />/fw/css/osStyles.css" rel="styleSheet" type="text/css">

<script language="JavaScript">

   //------------- find OVTop ----------------
   var OVTop=top.Mainscreen.ObjectView;
   OVTop.resultsFrame=OVTop.Results;
<%--

   //************** Event Handlers *****************
   function doTaskList(refPos, objectName, evt)
   {
      evt = ((evt)?evt:((window.event)?window.event:null));
      if (evt!=null)
      {
         OVTop.doTaskList(refPos, objectName, evt);
         iman.cancelEvent(evt);  //cancel event propagation/bubbling and default action 
      }
      return false;
   }

   function downOneLevel(objectName, evt)
   {
      evt = ((evt)?evt:((window.event)?window.event:null));
      if (evt!=null)
      {
         OVTop.processDisplayCountChange();
         OVTop.Query.document.BrowseQuery.BQContext.value=objectName;
         OVTop.doSearch();
         iman.cancelEvent(evt);
      }
      return false;
   }

   function upOneLevel(evt)
   {
      evt = ((evt)?evt:((window.event)?window.event:null));
      if (evt!=null)
      {
         OVTop.processDisplayCountChange();
         OVTop.Query.document.BrowseQuery.BQContext.value="<iman:toScript>${requestScope['Search.ParentContainer']}</iman:toScript>";
         OVTop.doSearch();
         iman.cancelEvent(evt);
      }
      return false;
   }
   
--%>
   

    
   //**************** OnLoad Processing **********************
   var t = null;
   function queryOnLoad(cnt)
   {
      //wait up to 10 seconds for the Query frame to load
      iman.debugOV("TreeResultsSS::in queryOnLoad() cnt = "+cnt);
      if (cnt<100)
      {
         if (
         		OVTop.queryLoaded==false
         		//||OVTop.resultButtonsLoaded==false
             )
         {
            cnt++;
            t = setTimeout("queryOnLoad("+cnt+")",100)
         }
         else
         {
            if (t!=null)
            {
               clearTimeout(t);
            }

            // set search context id in query frame
            OVTop.m_searchContextId = "<iman:toScript>${requestScope['Search.ContextId']}</iman:toScript>";
//            displayResultButtons();
         }
      }
   }

</script>

<script language="JavaScript" type="text/javascript">
	dojo.require("dojo.lang.*");
//	dojo.require("dojo.debug.Firebug");
//	dojo.require("dojo.debug.console");
	dojo.require("dojo.widget.TreeV3");
	dojo.require("dojo.widget.TreeRpcControllerV3");
	dojo.require("dojo.widget.TreeSelectorV3");
	dojo.require("dojo.widget.TreeNodeV3");
	dojo.require("dojo.widget.TreeContextMenuV3");
	dojo.require("dojo.widget.iManTreeDocIconExtension");
	dojo.require("dojo.widget.TreeDisableWrapExtension");
	dojo.require("dojo.widget.Dialog");
<%--
	<c:forEach var="jsFile" items="${registeredJSImports}">
		dojo.require("${jsFile}");
	</c:forEach>
 --%>
/*       If you want to debug Dojo scripts, enable the following line. This makes sure 
		 that dojo does not request for the scripts through Ajax and you will be able to
         debug them using Firebug.
*/ 
// 	dojo.hostenv.writeIncludes();


	
/*
	function restoreIconSrc() {
		// icon was changed during the action => no need to move it back
		//alert("Restore "+this.icon.src.substr(-18))
		if (this.icon.src.substr(-18) != '${dojoTreeExamplePath}static/loading.jpg') { // check if icon.src is loading icon
			return;
		}
		this.icon.src = this.oldIconSrc;
	}
*/

	/* process create operation */
/*
	function createClicked(selectedNode, controllerId, icon) {
		if (!selectedNode || selectedNode.actionIsDisabled(selectedNode.actions.ADDCHILD)) {
			return false;
		}

		this.icon = icon;
		this.oldIconSrc = icon.src;

		this.controller = dojo.widget.manager.getWidgetById(controllerId);

		if (!selectedNode || !selectedNode.isFolder) {
			alert('Select folder please');
			return false;
		}

		this.icon.src = '${dojoTreeExamplePath}static/loading.jpg';

		// I send some data to server and recieve feedback with right node
		var res = controller.createChild(selectedNode, 0, { suggestedTitle: "New node" }, dojo.lang.hitch(this, restoreIconSrc));

		// local checks failed
		if (res == false) {
			restoreIconSrc.apply(this);
		}
	}

	function removeClicked(selectedNode, controllerId, icon) {

		if (!selectedNode) {
			alert('No node selected');
			return false;
		}

		if (selectedNode.actionIsDisabled(selectedNode.actions.REMOVE)) {
			return false;
		}

		this.icon = icon;
		this.oldIconSrc = icon.src;

		this.controller = dojo.widget.manager.getWidgetById(controllerId);


		this.icon.src = '${dojoTreeExamplePath}static/loading.jpg';

		var res = controller.removeNode(selectedNode, dojo.lang.hitch(this, restoreIconSrc));

		// local checks failed
		if (res == false) {
			restoreIconSrc.apply(this);
		}


	}
*/
	
	function updateContentWithContainer(selectedNode){
		//window.alert("in titleClicked: "+selectedNode.widgetId);
		//if the widgetId is the specialMoreIndicator then just bail out
		var context = selectedNode.widgetId;
		if("specialMoreIndicator"==selectedNode.widgetId)
		{
			alert(selectedNode.objectTypeDisplayName);
			return;
		}
		if("rootTreeNode"==context){
			context="";
		}
		if(exists(top.Mainscreen.Content.displayContainer))
		{
			top.Mainscreen.Content.displayContainer(context);
		}else{
			initContent(context);
		}
	}
	function nodeIconClicked(nodeWidgetId)
	{
		iman.debug("icon clicked for node with widgetId= "+nodeWidgetId);
		var selectedNode = dojo.widget.manager.getWidgetById(nodeWidgetId);
		updateContentWithContainer(selectedNode);
	}

	function initContent(context){
		//window.alert("in titleClicked");
		OVTop.selectTaskForId("fw.Tree View Content", pack([context]));
		
	}

	var reporter = function(reporter) {
		this.name = eventName;
		this.go = function(message) {
			var rep = [ reporter + " -- event: "+this.name ];
			for(i in message) rep.push(i+": "+message[i]);
			//dojo.debug(rep.join(', '));
			iman.debugOV("Console:"+ rep.join(', '));
		}
	}


	dojo.addOnLoad(function(){
//	var djAlert= dojo.widget.manager.getWidgetById('djAlertDlg');
//	djAlert.setCloseControl(document.getElementById("djAlertHider"));
		/* Add debug print for all controller events */
		var controller = dojo.widget.manager.getWidgetById('treeController');
		for(eventName in controller.eventNames) {
			dojo.event.topic.subscribe(
				controller.eventNames[eventName],
				new reporter('controller'),
				'go'
			);
		}

		/* Add debug print for all Tree events */
		var dirTree = dojo.widget.manager.getWidgetById('dirTree');
		for(eventName in dirTree.eventNames) {
			dojo.event.topic.subscribe(
				dirTree.eventNames[eventName],
				new reporter('dirTree'),
				'go'
			);
		}
		/* Add debug print for all treeSelector events */
		var treeSelector = dojo.widget.manager.getWidgetById('treeSelector');
		for(eventName in treeSelector.eventNames) {
			dojo.event.topic.subscribe(
				treeSelector.eventNames[eventName],
				new reporter('treeSelector'),
				'go'
			);
		}
		//dojo.widget.manager.getWidgetById('1.1').edit({title: '123'});
//		djAlert.show();


	});

	
	function refreshContextsInTreeView(containers)
	{
		iman.debugOV("refreshing the contaiers: "+containers);
		// iterate down tree finding containers.
		for(var i = 0; i<containers.length; i++){
			var container =	containers[i];
			var node = findNodeForContainer(container);
			if(node){
				dojo.widget.manager.getWidgetById("treeController").refreshChildren(node, true);
			}else{
				iman.debug("node not found for context: "+container);
			}
		}
			
	}
	
	function findNodeForContainer(container){
		iman.debug("in findNodeForContainer: Container:"+container);
	
		var nodeIds = container.split(".");
		var currentNode=dojo.widget.manager.getWidgetById('rootTreeNode');
		var currentNodeId="";
		for(var i=nodeIds.length-1;i >= 0; --i)
		{
			if(i<nodeIds.length-1){
				currentNodeId="."+currentNodeId;
			}
			currentNodeId=nodeIds[i]+currentNodeId;
			iman.debug(i+": looking for Container:"+currentNodeId);
			node = findChildNodeWithId(currentNodeId, currentNode);
			if(node){
				iman.debug("found node: "+node.widgetId);
				currentNode=node;
			}else{
				iman.debug("node not found, Aborting");
				break;
			}
		}
		return currentNode;
	}
	
	function findChildNodeWithId(nodeId, parent){
		iman.debug("finding Child node of "+parent+".widgetId="+parent.widgetId+" with widgetId = -"+nodeId+"-");
		var controller=dojo.widget.manager.getWidgetById('treeController');
		controller.expand(parent,true);
		for(var j = 0; j < parent.children.length; j++){
		    var currentNode = parent.children[j];
			iman.debug(" comparing "+ currentNode+"  whose widgetId = -"+currentNode.widgetId+"-");
			if(currentNode.widgetId == nodeId){
				iman.debug("Found");
				return currentNode;
			}
		}
		iman.debug("NOT found");
	}
	
/*
	function expandTreeToContainer(container){
		iman.debug("in expandTreeToContainer container = "+container);
		var dirTree = dojo.widget.manager.getWidgetById('dirTree');
		var controller = dojo.widget.manager.getWidgetById('treeController');
		//read the first element
		dojo.lang.forEach(dirTree.children, expand
		
		// start with the tree
		if(node){
			iman.debugOV("Found node!! node.widgetId="+node.widgetId);
		}else{
			iman.debugOV("Could NOT Find node.  POOP!!");
		}
	}
*/	


</script>

</head>
<BODY bgColor="#efeeec" >
<%--
<div dojoType="dialog" id="djAlertDlg" bgColor="red" bgOpacity="0.1" toggle="fade" toggleDuration="250">
	This is an alert.  <a id="djAlertHider" href="#">[X]</a>
</div>
 --%>
 
<div dojoType="TreeRpcControllerV3" RPCUrl="webacc?taskId=fw.ObjectView&SearchToken=SearchTokenPost&OV.Mode=Tree" widgetId="treeController"></div>
<div dojoType="TreeSelectorV3" widgetId="treeSelector"></div>
<div dojoType="iManTreeDocIconExtension" widgetId="docIcons"></div>
<div dojoType="TreeDisableWrapExtension" widgetId="disableWrap"></div>

<!--<div dojoType="TreeContextMenuV3" toggle="explode" contextMenuForWindow="false" widgetId="treeContextMenu">-->
<!--	<div dojoType="TreeMenuItemV3" treeActions="addChild" iconSrc="<iman:moduleUrl />/dev/images/iconadd.gif" widgetId="treeContextMenuCreate" caption="%Create%"></div>-->
<!--	<div dojoType="TreeMenuItemV3" treeActions="remove" iconSrc="<iman:moduleUrl />/dev/images/iconremove.gif" caption="%Delete%" widgetId="treeContextMenuRemove"></div>-->
<!--	<div dojoType="TreeMenuItemV3" treeActions="updateContentPane" iconSrc="<iman:moduleUrl />/dev/images/go.gif" caption="%Contents%" widgetId="treeContextMenuUpdateContentPane"></div>-->
<!--	<div dojoType="TreeMenuItemV3" treeActions="init" iconSrc="<iman:moduleUrl />/dev/images/iconedit.gif" caption="<iman:string key="Init Contents"/>" widgetId="treeContextMenuInit"></div>-->
<!--	<div dojoType="TreeMenuItemV3" treeActions="refreshNodes" iconSrc="<iman:moduleUrl />/dev/images/iconedit.gif" caption="<iman:string key="Refresh Node"/>" widgetId="treeContextMenuRefreshNodes"></div>-->
<!--</div>-->
<script>

/* setup menu actrions  and  title click handler*/
dojo.addOnLoad(function() {

//	dojo.event.topic.subscribe('treeContextMenuCreate/engage',
//		function (menuItem) { createClicked( menuItem.getTreeNode(), 'treeController',  menuItem.getTreeNode().expandIcon); }
//	);

//	dojo.event.topic.subscribe('treeContextMenuRemove/engage',
//		function (menuItem) { removeClicked( menuItem.getTreeNode(), 'treeController',  menuItem.getTreeNode().expandIcon); }
//	);

//	dojo.event.topic.subscribe('treeContextMenuUpdateContentPane/engage',
//		function (menuItem) { updateContentWithContainer( menuItem.getTreeNode()); }
//	);

//	dojo.event.topic.subscribe('treeContextMenuInit/engage',
//		function (menuItem) { initContent( menuItem.getTreeNode()); }
//	);
/*
	dojo.event.topic.subscribe('treeContextMenuRefreshNodes/engage',
		function (menuItem) { findNodeForContainer("ramkis.novell"); }
	);
*/

	dojo.event.topic.subscribe('treeSelector/select',
		function (TreeNode) { updateContentWithContainer( TreeNode.node); }
	);
	

//	window.alert("expanding root of tree");

	
	dojo.widget.manager.getWidgetById("treeController").expand(dojo.widget.manager.getWidgetById("rootTreeNode"));
	var node = dojo.widget.manager.getWidgetById("rootTreeNode");
	node.iconNode.style.backgroundImage = "url(/nps/portal/modules/dev/images/dir/Tree.gif)";
	//initContent(node); // uncomment to get the content pane to initialize immediately.
	
	
	
});

/*
dojo.addOnLoad(function() {
	findNodeForContainer("ramkis.novell");

});
*/
</script>
<%--  <script type='text/javascript'>__debugTime('javascriptLoad Finished');</script> --%>

<style>
#toolsDiv img {
	vertical-align: middle;
}
.treeTable tr {
	vertical-align: top;
}
</style>

<!--
	Every node must have widgetId to get recognized by server (ajax)
	!!! wipe toggle from widget.Tree is buggy in FF (try open a lot of nodes)
-->
<div dojoType="TreeV3" selector="treeSelector" widgetId="dirTree" listeners="treeController;docIcons;treeSelector;disableWrap" >
<!--<div dojoType="TreeV3" selector="treeSelector" widgetId="dirTree" listeners="treeController;docIcons;treeSelector;disableWrap;treeContextMenu" >-->

    <div dojoType="TreeNodeV3" widgetId="rootTreeNode" title="${requestScope['Search.TreeName']}" actionsDisabled="remove" isFolder="true" iconUrl="Tree.gif">
    </div>
</div>

</BODY></HTML>