// TreeController.js
// E. van Raaij, Topshare International BV
// Implements bahaviour for tag @treecontroller.. treecontroller@ and @treemenu...treemenu...@
// and controls a @treedata .. treedata@ fetch, nows about the intrinsics of treedata menu generation
// and provides methods to facilitate it.

var ns_topshare;

if (!ns_topshare)
	ns_topshare = {};

if(!ns_topshare.ns_controllers)
	throw new Error('Missing dependency. Make sure Controllers.js is included.');

if(!ns_topshare.ns_treecontrollers)
{
	ns_topshare.ns_treecontrollers ={};


	ns_topshare.ns_treecontrollers.TreeController = function(p_ctlId, p_nodeId, p_baseNodeId,
								 p_typeFilter, p_depth, p_targetId, p_targetName, p_targetType, p_targetUrl, p_viewcontext, p_ppKey)
	{
		this.superclass(p_ctlId, p_viewcontext);
		this.AddHandler(ns_topshare.ns_controllers.RENDER, this.Render);
		this.AddHandler(ns_topshare.ns_controllers.SYNCNODE, this.SyncNode);

		// instance vars
		this.url = '/tagexpander/asp/tagexpander.aspx?nbrNodeID=-1&tag=';
		this.nodeId = p_nodeId;
		this.currentNodeId = p_nodeId;
		this.baseId = p_baseNodeId;
		this.currentBaseId = p_baseNodeId;
		this.typeFilter = p_typeFilter;
		this.depth = p_depth;
		this.targetId = p_targetId;
		this.targetName = p_targetName;
		this.targetType = p_targetType;
		this.targetUrl = p_targetUrl;
		this.layoutCategory = -1;
		this.ppKey = p_ppKey;
		this.showIcons = true;
		this.defaultLinkCss = '';
		this.focusCss = '';
		this.level = 0;    // The level to show; 0 is the baseID
		this.highlightLevel = false;
		this.treeclass = 'tagTree';
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype = new ns_topshare.ns_controllers.Controller();
	ns_topshare.ns_treecontrollers.TreeController.prototype.superclass = ns_topshare.ns_controllers.Controller;
	ns_topshare.ns_treecontrollers.TreeController.prototype.constructor = ns_topshare.ns_treecontrollers.TreeController;

	//
	// Correctly cleanup a tree by disposing each element from a given div
	//
	//ns_topshare.ns_treecontrollers.TreeController.prototype.
	//
	ns_topshare.ns_treecontrollers.TreeController.prototype.DeleteChildrenRecursive = function(p_node)
	{
	      while(p_node && p_node.hasChildNodes())
	      {
		  var childNode = p_node.firstChild;
		  this.DeleteChildrenRecursive(childNode);
		  p_node.removeChild(childNode);
		  childNode = null;   
	      }
	};							

	// GetData - client pull method to fetch data steered by controller.
	ns_topshare.ns_treecontrollers.TreeController.prototype.GetData = function(p_id, p_baseId)
	{
		var requestString = "@tscontrolledtree ";
		requestString += 'ownerctrlid="' + this.ctrl_id + '" ';	// this
		requestString += 'id="' + p_id + '" ';					// the id to focus on
		requestString += 'baseid="' + p_baseId + '" ';			// the baseid
		requestString += 'showitemicons="' + this.showIcons + '" ';		// the baseid
		requestString += 'defaultcss="' + this.defaultLinkCss + '" ';	// default css
		requestString += 'focuscss="' + this.focusCss + '" ';			// css of focussed item

		if(this.typeFilter != "")
		{
			requestString += 'types="' + this.typeFilter + '"';	// types to view
		}

		requestString += 'depth="' + this.depth + '" ';		// depth of retrieval
		requestString += 'viewcontext="' + this.viewcontext + '" ';		// viewcontext
		requestString += 'layoutcategory="' + this.layoutCategory + '" ';         
		requestString += 'ppkey="' + this.ppKey + '" ';
		
		if (this.highlightLevel > 0)
			requestString += 'highlight="' + this.AddHighlightNode(p_id) + '" ';

		requestString += 'treeclass="' + this.treeclass + '" ';
		requestString += "tscontrolledtree@";
		//alert(requestString);
		return this.LoadHtml(this.url + escape(requestString));
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.Render = function()
	{
		var base = this.baseId;
		var node = this.nodeId;
		if (this.level != 0)
		{
			var trail = this.GetTrail(this.nodeId);
			var nodes= trail.split(';');
			for (var i = 0; i < nodes.length; i++)
			{
				if (nodes[i] == this.baseId && (i + this.level < nodes.length))
				{
					base = nodes[i + this.level];
				}
			}
		}
		var data = this.GetData(node, base);
		var obj = document.getElementById(this.targetId);
		obj.innerHTML = data;
	};

	// Handle repositioning of tree by referring to the local anchor
	// within the target div
	ns_topshare.ns_treecontrollers.TreeController.prototype.Reposition = function(p_nodeId)
	{
		p_anchorName = "a_" + this.ctrl_id + "node" + p_nodeId;

		var anchor = document.getElementById(p_anchorName);

		if(anchor != null)
		{
			// ie nags when the anchor is not visible, and there's no need to set the focus on
			// a hidden anchor... 
			try
			{
				anchor.focus();
			}
			catch(e)
			{
				// do nothing
			}
		}
	};

	// Handle Synchronizing of tree
	// from parent to below.
	// we only do that if we can find a corresponding parent <div> element
	// thus proving that we have a path to show.
	ns_topshare.ns_treecontrollers.TreeController.prototype.SyncNode = function(p_msg)
	{
		var p_baseId = p_msg.argument[0];
		var p_nodeId = p_msg.argument[1];
		var p_sqlAction = p_msg.argument[2];

		if (p_sqlAction == null)
			p_sqlAction = 0;


		if(this.ExistsInTree(p_nodeId))
		{
		//	alert ('Entering SyncNode. NodeID: ' + p_nodeId + '\nBaseID: ' + p_baseId + '\nAction: ' + p_sqlAction);
			// Figure out CtrlId of treemenu
			var menuctrlid = this.ctrl_id;
			// The menucontroller is identified by the current controller id without the 'tree_' - prefix
			// We need to repaint when the menu is closed. We also need to repaint in case the 
			// Trashcan is being emptied.
			// Additionally we need to repaint after a move within the current treecontroller context
			menuctrlid = menuctrlid.substring(5);
			var menuCtrl = ns_topshare.ns_controllers.PageController.GetInstance().GetController(menuctrlid);

			if (menuCtrl.status == false || this.baseId == 1009)  
				menuCtrl.Toggle(false);
			
			var baseDivId = null;
			var actualDivId = null;

			if (p_baseId != null)
				this.currentBaseId = p_baseId;

			if (p_nodeId != null)
				this.currentNodeId = p_nodeId;

			if(p_nodeId != this.baseId)
			{
				actualDivId = this.ctrl_id + "node" + p_nodeId;

				if(p_baseId != this.baseId)
					baseDivId = this.ctrl_id + "node" + p_baseId;
				else
					baseDivId = this.targetId;
			}
			else
			{
				// navigate to root of control
				actualDivId = this.targetId;
				baseDivId = this.targetId;
			}
			// Load the treedata
			var data = this.GetData(p_nodeId, this.baseId);

			if (data != null)
			{
				var obj = document.getElementById(this.targetId);
				obj.innerHTML = data;

				// reposition on the 'leaf'
				this.Reposition(p_nodeId);


				if(p_sqlAction == ns_topshare.ns_controllers.sql_action.INSERT)
					this.PromoteToFolder(p_baseId);
			}
		}
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.Toggle = function(p_targetElem, p_nodeId, p_typeId, p_closedImage, p_openImage)
	{

		var div = document.getElementById(p_targetElem);
		var divClass = div.className;
		var imgid = 'img' + p_targetElem;
		var imgidobj = document.getElementById(imgid);
		if(divClass.indexOf('shown') >= 0)
		{
			// cleanup children and close it.
			this.DeleteChildrenRecursive(div);
			div.className = 'hidden';
			imgidobj.src = p_closedImage; //'/images/t_folder_closed.gif';
		}
		else if(divClass.indexOf('hidden') >= 0)
		{
			imgidobj.src = p_openImage; //'/images/t_folder_open.gif';
			// Fetch data for it and set it accordingly
			var data = this.GetData(p_nodeId, p_nodeId);
			div.className = 'shown';
			div.innerHTML = data;
		}
		this.currentNodeId = p_nodeId;
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.SendNavigateMessage = function(p_nodeId, p_parentId, p_typeId, p_subTypeId)
	{
		// p_nodeId is the file we want to navigate to.
		// However, we are not responsible for its rendering.
		// We only have to notify the responsible components.
		var args = new Array();
		args[0] = p_nodeId;
		args[1] = p_parentId;
		args[2] = p_typeId;
		args[3] = p_subTypeId;
		var msg = this.ConstructMessage(ns_topshare.ns_controllers.OPEN, args);
		this.SendMessage(msg);
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.Navigate = function(p_nodeId, p_parentId, p_typeId, p_subTypeId)
	{
		this.currentNodeId = p_nodeId;
		this.currentBaseId = p_parentId;
		var url = this.targetUrl + '?nbrNodeID=' + p_nodeId + '&nbrParentID=' + p_parentId;
		url = url + '&nbrTypeID=' + p_typeId + '&nbrSubTypeID=' + p_subTypeId
			+ '&nbrLayoutCategory=' + this.layoutCategory;

		if (this.targetType == 'frame')
			parent.frames[this.targetName].location.href = url;
		else // Must be a div then
			document.getElementById(this.targetName).innerHTML = this.LoadHtml(url);
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.IsOpen = function(p_nodeId)
	{
		var isOpen = false;
		var divId = this.ctrl_id + 'node' + p_nodeId; 
		var div = document.getElementById(divId);

		if (div != null)
		{
			if (div.className == 'shown')
				isOpen = true;
		}

		return isOpen;
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.PromoteToFolder = function(p_nodeId)
	{
		var target = this.ctrl_id + 'node' + p_nodeId;
		var imgdivid = 'img' + target;
		var imgdivobj = document.getElementById(imgdivid);

		if (imgdivobj != null)
		{
			imgdivobj.src = '/images/t_folder_open.gif';
			// link on the image
			var imglink = 'imglink_' + target;
			var imglinkobj = document.getElementById(imglink);

			imglinkobj.href = 'javascript:toggle(\'' + this.ctrl_id + 
					'\', \'' + target + '\', ' +
					p_nodeId + 
					', 5, \'/images/t_folder_closed.gif\', \'/images/t_folder_open.gif\');';

			// finally the title link must be adjusted
			var titlelink = 'titlelink_' + target;
			var titlelinkobj = document.getElementById(titlelink);
			var link = titlelinkobj.href;

			var linkpieces = link.split(',');

			link = linkpieces[0] + ', ' + linkpieces[1] + ', ' + linkpieces[2] + ', 5, ' + linkpieces[4]; 
			titlelinkobj.href = link; 
			// Lastly, set the classname
			document.getElementById(target).className = 'shown';
		}
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.GetTrail = function(p_nodeId)
	{
		var tag = '@tstrailarray ';
		tag = tag + 'id=' + p_nodeId;
		tag = tag + ' tstrailarray@';

		var trail = this.LoadHtml(this.url + escape(tag));
		return trail;
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.ExistsInTree = function(p_nodeId)
	{
		
		var trail = this.GetTrail(p_nodeId);
		var basereg = new RegExp(this.baseId + ';');
		var baseFound = false;

		if(trail != null)
		{
			baseFound = basereg.test(trail);
		}
		return baseFound;

	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.SetLayoutCategory = function(p_layoutCategory)
	{
		this.layoutCategory = p_layoutCategory;
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.SetIconVisibility = function(p_visibility)
	{
		this.showIcons = p_visibility;
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.SetDefaultLinkCss = function(p_cssClass)
	{
		this.defaultLinkCss = p_cssClass;
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.SetFocusCss = function(p_cssClass)
	{
		this.focusCss = p_cssClass;
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.SetLevel = function(p_level)
	{
		this.level = parseInt(p_level);
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.SetHighlightLevel = function(p_highlight)
	{
		this.highlightLevel = parseInt(p_highlight);
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.SetTreeClass = function(p_treeclass)
	{
		this.treeclass = p_treeclass;
	};

	ns_topshare.ns_treecontrollers.TreeController.prototype.AddHighlightNode = function(p_nodeId)
	{
		var trail = this.GetTrail(p_nodeId);
		var nodes = trail.split(';');
		var index = 0;
		// Figure out where the baseid is
		for (var i = 0; i < nodes.length; i++)
		{
			if (parseInt(nodes[i]) == this.baseId)
				index = i + this.highlightLevel;
		}
		return nodes[index];
	};
}

