﻿// JScript File
var globalVisibleTab;
var globalPreviousTab;
var globalVisibleLeftTab;
var globalAutoLoadTextView = true;
var globalLoadTabOnPageLoad = true;
var globalLoadMoreTextOnPageLoad = false;
var globalCurrentKnowdeIDForTab;
var globalDrawInitial = false;
var globalTabStripHCCWidth = 1000;

function LoadTabContentForPageLoad()
{
  if(globalLoadTabOnPageLoad == true && globalVisibleTab != null)
  {
    var initialTab = globalVisibleTab;
	  var tab = document.getElementById(initialTab);
		if(tab == null || !window.objectiveID)
		{   
			if(globalVisibleTab != "TSC_genes")
			{
				if(globalVisibleTab != "TSC_myprofile")
				{
					window.setTimeout('LoadTabContentForPageLoad()', 400);
					return;
				}
			}
		}
	  
    globalVisibleTab = null;
    ChangeTab(initialTab.replace('TSC_',''));
  }
}


function LoadMoreTextTabPageLoad()
{
	// This pre-loads the text view on a t=moretext URL parameter.
  ChangeTabToolStrip('moretext');
  DoExpandMapViewPane('split');
  ShowSplitterArrowDown();
  globalSplitterSetting = "split";
}


function ChangeTabFromMapView(_tabID, _tabName, _full)
{
	document.getElementById("BottomPaneExpanderOptionBox").className = "BottomPaneExpandOptionBoxHide";
	// Hide Map View Strip Control & expand splitter
	HideTabWidget();
	if (_full == 'true')
	{
	  globalSplitterSetting = 'single';
	  SplitterControl('up');
	  ShowSplitterArrowDown();
	  
	}
	else
	{
	  DoExpandMapViewPane("split");
	  globalSplitterSetting = "split";
	  ShowSplitterArrowDown();
	}
	
	// Run Change Tab Code
	ChangeTab(_tabID, _tabName);
}

function TabsDown(_newSplitterSetting)
{
  // tell the splitter to go either halfway or all the way to the bottom, depending on which arrow was clicked
  globalSplitterSetting = _newSplitterSetting;
  
  // move the splitter
  SplitterControl('down');
}

function ShowTabWidget()
{
	document.getElementById("BottomPaneExpanderOptionBox").className = "BottomPaneExpandOptionBoxShow";
}

function HideTabWidget()
{
	document.getElementById("BottomPaneExpanderOptionBox").className = "BottomPaneExpandOptionBoxHide";
}


function ChangeTab(_tabID, _tabName, _loadContent)
{
	// Grab the Tab & Tabstrip Elements
	var TabID = "TSC_" + _tabID;
	var Tab = document.getElementById(TabID);
	
	if ( Tab == null || Tab == undefined )
	  return;
	
	var TabStrip = Tab.parentNode;
	var currentContainerID = "TCC_" + _tabID;
	var currentContainer = document.getElementById(currentContainerID);
	
	// Deselect Current Tab & Select new one
	UpdateTabUI(TabStrip, Tab);
	// Show/Hide toolstrip
	ChangeTabToolStrip(_tabID);
	
	// Set the global js variable
	globalPreviousTab = globalVisibleTab;
	globalVisibleTab = TabID;
	
	// Perform Splitter Manipulation
	AdjustSplitterOnTabChange();
	
	if(_tabName == 'Communities' && CommunityLinkAdminUser)
	{
	  _loadContent = true;
	  globalCommunityTabLoaded = false;
	}
	
	// Call-back necessary control
	// we may need to callback tab as they have different modes... new check required.
	if(_loadContent == null || _loadContent != false)
	  TabContainerControl_CallbackDirection(_tabID);
	
	// Hide the other DIV containers
	HideContainers(currentContainer);
	
	// Show the new container
	ShowContainer(currentContainer);
	
	// hide publishing controls
	 // make sure the publish control is hidden, otherwise it will pop to top left after rerender
	if (globalVisibleTab.indexOf("myprofile") == -1)
	{
    if(g_publishHolderId != null && window.KGPublishOptionControl_HideMenu)
    {
	    window.setTimeout('KGPublishOptionControl_ReSetPublishingChoicesControl()', 500);
      KGPublishOptionControl_HideMenu(g_publishHolderId);
    }
  }
  
  if ( globalVisibleTab.indexOf("TSC_communities") == -1 )
  {
    var communitiesOptionsDiv = document.getElementById("TSC_TabStripControl_OptionDiv");
    if ( communitiesOptionsDiv != null )
    {
      communitiesOptionsDiv.style.display = "none";
    }   
  }
   
  
}

// Just update the selected tab UI of the TabStrip
function UpdateTabUI(_tabStrip, _tab, _LeftPaneTabs)
{
	// deselect all Tabs
	for(tabCounter = 0; tabCounter < _tabStrip.childNodes.length; tabCounter++)
	{
		_tabStrip.childNodes[tabCounter].isSelected = false;
		_tabStrip.childNodes[tabCounter].className = _tabStrip.childNodes[tabCounter].className.replace("Selected","Visible");
		//_tabStrip.childNodes[tabCounter].childNodes[0].className = _tabStrip.childNodes[tabCounter].childNodes[0].className.replace("Selected", "Visible");
		//_tabStrip.childNodes[tabCounter].childNodes[1].className = _tabStrip.childNodes[tabCounter].childNodes[1].className.replace("Selected", "Visible");
		//_tabStrip.childNodes[tabCounter].childNodes[2].className = _tabStrip.childNodes[tabCounter].childNodes[2].className.replace("Selected", "Visible");
		if(_LeftPaneTabs == true)
			_tabStrip.childNodes[tabCounter].childNodes[3].className = _tabStrip.childNodes[tabCounter].childNodes[3].className.replace("Selected", "Visible");
	}
	
	// select new tab
	_tab.isSelected = true;
	_tab.className = _tab.className.replace("Visible","Selected");
	//_tab.childNodes[0].className = _tab.childNodes[0].className.replace("Visible","Selected");
	//_tab.childNodes[1].className = _tab.childNodes[1].className.replace("Visible","Selected");
	//_tab.childNodes[2].className = _tab.childNodes[2].className.replace("Visible","Selected");
	if(_LeftPaneTabs == true)
		_tab.childNodes[3].className = _tab.childNodes[3].className.replace("Visible","Selected");
}

// Hide a Single Tab
function HideTab(_tab)
{
	// select new tab
	if(_tab.isSelected == true)
	{
		// need to change to default tab as we are hiding the selected one.
		ChangeToDefaultTab();
		_tab.isSelected = false;
		_tab.className = _tab.className.replace("Selected","Hidden");
		//_tab.childNodes[0].className = _tab.childNodes[0].className.replace("Selected","Hidden");
		//_tab.childNodes[1].className = _tab.childNodes[1].className.replace("Selected","Hidden");
		//_tab.childNodes[2].className = _tab.childNodes[2].className.replace("Selected","Hidden");
	}
	else
	{
		_tab.className = _tab.className.replace("Visible","Hidden");
		//_tab.childNodes[0].className = _tab.childNodes[0].className.replace("Visible","Hidden");
		//_tab.childNodes[1].className = _tab.childNodes[1].className.replace("Visible","Hidden");
		//_tab.childNodes[2].className = _tab.childNodes[2].className.replace("Visible","Hidden");
	}
}

// Show a Single Tab
function ShowTab(_tab, _widgetTab)
{
	// NOT THE SAME AS CHANGE TAB - DOES NOT PERFORM A SELECT
	if(_tab != null)
	{
		_tab.className = _tab.className.replace("Hidden","Visible");
		//_tab.childNodes[0].className = _tab.childNodes[0].className.replace("Hidden","Visible");
		//_tab.childNodes[1].className = _tab.childNodes[1].className.replace("Hidden","Visible");
		//_tab.childNodes[2].className = _tab.childNodes[2].className.replace("Hidden","Visible");
	}
	
	if(_widgetTab != null)
	{
		_widgetTab.className = _widgetTab.className.replace("Hidden","Visible");
		// HACK: in firefox, _widgetTab has more childNodes than expected, so instead 
		// just loop through all of them and check for defined _widgetTab.childNodes[index].className
		for (var index in _widgetTab.childNodes)
		{
		  if (_widgetTab.childNodes[index].className != null)
		    _widgetTab.childNodes[index].className = _widgetTab.childNodes[index].className.replace("Hidden","Visible");
		}
	}
}

// update splitter if required
function AdjustSplitterOnTabChange()
{
}

// If tab you are hiding is selected Tab
function ChangeToDefaultTab()
{
}

function TabControl_ResetScrollBar()
{
  document.getElementById("TCC").parentNode.scrollTop = 0;
}

function GetTabScroller()
{
  return document.getElementById("TCC");
}

function ShowLoadingSymbolForTab(_tab, _mode)
{
	switch(_tab)
	{
		case "Genes":
			// show loading symbol prior to callback for instant feedback to user.
			var grid = document.getElementById("TCC_GenesTabControl_Grid");
			var msgDiv = document.getElementById("GenesTabMessageDiv");
			if(grid != null)
			{
				// show loading symbol on the list grid
				grid.outerHTML = '<table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
				
				// clear the empty message
				var empty = document.getElementById("TCC_GenesTabControl_emptyCont");
				if(empty != null)
					empty.innerHTML = "";
				
				// show loading when on cat home page
				var catHome = document.getElementById("TCC_GenesTabControl_CatHomePageDiv");
				if(catHome != null)
					catHome.innerHTML = '<table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
				var catHomeSwitch = document.getElementById("TCC_GenesTabControl_CatHomeSwitch");
				if(catHomeSwitch != null)
					catHomeSwitch.style.display = "none";
				
				// put up correct title
				var header = document.getElementById("TCC_GenesTabControl_headerContTitle");
				if(header != null)
				{
					switch(_mode)
					{
						case "GenesList":
							header.innerHTML = "Genes List<sup><font color='white'>&#174</font></sup>";
							break;
						case "Search":
							header.innerHTML = "Search Results<sup><font color='white'>&#174</font></sup>";
							break;
						case "Category":
							header.innerHTML = "Featured Knowledge Genes<sup>&#174</sup>";
							break;
					}
				}
			}
			else if(msgDiv != null)
			{
			  	msgDiv.innerHTML = '<table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
			}
			break;
		case "Web":
			var grid;
			grid = document.getElementById("TCC_WebTabControl_Grid");
			var msgDiv = document.getElementById("WebTabMessageDiv");
			if(grid != null)
			{
				grid.outerHTML = '<table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
				var empty;
				empty = document.getElementById("TCC_WebTabControl_emptyCont");
				if(empty != null)
					empty.innerHTML = "";
				var header;
				header = document.getElementById("TCC_WebTabControl_headerContTitle");
				if(header != null)
				{
					switch(_mode)
					{
						case "Knowde":
							header.innerHTML = "Indexed Documents<sup><font color='white'>&#174</font></sup>";
							break;
						case "Search":
							header.innerHTML = "Search Results<sup><font color='white'>&#174</font></sup>";
							break;
					}
				}
			}
			else if(msgDiv != null)
			{
			  	msgDiv.innerHTML = '<table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
			}
			break;
	}
}

/*********************************************************************************/

var globalWebTabMode;

function setWebTabMode(_mode, _mergeRequests)
{
  var keys = '';
	var values = '';
	
	if(globalWebTabMode != _mode || m_bEditable == true)
	{
		switch(_mode)
		{
			case "Knowde":
				globalWebTabMode = "Knowde";
				keys += 'WebTabMode|';
				values += 'Knowde|';
				//SetSessionProperty('WebTabMode', "Knowde");
				if(globalLastSelectedKnowde != null && globalLastSelectedKnowde != "undefined")
				{
					var knowdeID = returnKnowdeID(globalLastSelectedKnowde);
				  keys += 'CurrentKnowdeIDForTab|';
				  values += knowdeID + '|';
				  // set global value so if tab callback trigger been called, then no need to set CurrentKnowdeIDForTab session
				  globalCurrentKnowdeIDForTab = knowdeID;
					//SetSessionProperty('CurrentKnowdeIDForTab', knowdeID);
			  }
				break;
			case "Search":
				globalWebTabMode = "Search";
				keys += 'WebTabMode|';
				values += 'Search|';
				//SetSessionProperty('WebTabMode', "Search");
				break;
		}
	}
	
	if(keys.length > 0 && values.length > 0)
	{
	  if(_mergeRequests == null || _mergeRequests == false)
	    SetSessionProperty(keys, values, true);
	}
	
	return keys + '[@|@]' + values;
}

var WebTab_KnowdeMemory;
var WebTab_ModeMemory;
function WebTabControl_CallbackTrigger_Wrapped(_mode, _cbref)
{//debugger;
  ClearWebTabSessionValuesForMode(globalWebTabMode);
  if(globalWebTabMode == null)
		globalWebTabMode = "Knowde";
		
	var whatId = GetGlobalHighlightedWhatId();
	
  switch(globalWebTabMode)
  {
		case "Knowde":
			if((!(window.globalLastSelectedKnowde) || globalLastSelectedKnowde == null || globalLastSelectedKnowde == "undefined")
			    && (whatId == null || whatId == ''))
			{
				// show no context message
				var args = "Action=NoContext";
					eval(_cbref);
			}
			else
			{
				var knowdeID = whatId;
				if(knowdeID == '')
				  knowdeID = returnKnowdeID(globalLastSelectedKnowde)
				if(WebTab_KnowdeMemory != knowdeID || WebTab_ModeMemory != globalWebTabMode || m_bEditable == true || globalDrawInitial == true)
				{
					globalDrawInitial = false;
					// callback web list if its not already loaded against this knowde.
					WebTab_KnowdeMemory = knowdeID;
					WebTab_ModeMemory = globalWebTabMode;
					//if(globalCurrentKnowdeIDForTab == null || globalCurrentKnowdeIDForTab !=  knowdeID)
					  SetSessionProperty('CurrentKnowdeIDForTab', knowdeID);
					// reset value
					globalCurrentKnowdeIDForTab = null;
					ShowLoadingSymbolForTab("Web", globalWebTabMode);
					var args = "Action=Reload";
					eval(_cbref);
				}
			}
			break;
		case "Search":
			WebTab_ModeMemory = globalWebTabMode;
			ShowLoadingSymbolForTab("Web", globalWebTabMode);
			var args = "Action=WebSearch";
			eval(_cbref);
			break;
  }	
}

function WebTabControl_CallbackDone_Wrapped(_args, _context)
{ 
  KGListViewControl_CallbackDone(_args, _context);
}

function WebTabControl_ProcessCallBackError_Wrapped(_args, _context, _clientId)
{
}

function ClearWebTabSessionValuesForMode(_mode)
{
	if(_mode == null)
	{
	  // clear search session
    SetSessionProperty('WebSearch_PhraseName', ''); 
	}
}

function setTabModes(_genesMode, _webMode)
{
  var sessionkeys = '';
	var sessionvalues = '';
  var keyvalues = setGenesTabMode(_genesMode, true);
  var kvpairs = keyvalues.split('[@|@]');
  if(kvpairs.length == 2 && kvpairs[0].length > 0)
  {
    sessionkeys += kvpairs[0];
    sessionvalues += kvpairs[1];
  }
  keyvalues = setWebTabMode(_webMode, true);
  kvpairs = keyvalues.split('[@|@]');
  if(kvpairs.length == 2 && kvpairs[0].length > 0)
  {
    sessionkeys += kvpairs[0];
    sessionvalues += kvpairs[1];
  }
  
  if(sessionkeys.length > 0 && sessionvalues.length > 0)
  {
    SetSessionProperty(sessionkeys, sessionvalues, true);
  }
}
/*********************************************************************************/

var globalGenesTabMode;

function setGenesTabMode(_mode, _mergeRequests)
{
  var keys = '';
	var values = '';

	if(globalGenesTabMode != _mode  || m_bEditable == true)
	{
		switch(_mode)
		{
			case "GenesList":
				globalGenesTabMode = "GenesList";
				keys += 'GenesTabMode|';
				values += 'GenesList|';
				//SetSessionProperty('GenesTabMode', "GenesList");
				if(globalLastSelectedKnowde != null && globalLastSelectedKnowde != "undefined")
				{
					var knowdeID = returnKnowdeID(globalLastSelectedKnowde);
				  keys += 'CurrentKnowdeIDForTab|';
				  values += knowdeID + '|';
				  // set global value so if tab callback trigger been called, then no need to set CurrentKnowdeIDForTab session
				  globalCurrentKnowdeIDForTab = knowdeID;
					//SetSessionProperty('CurrentKnowdeIDForTab', knowdeID);
			  }
				break;
			case "Search":
				globalGenesTabMode = "Search";
				keys += 'GenesTabMode|';
				values += 'Search|';
				//SetSessionProperty('GenesTabMode', "Search");
				break;
			case "Category":
				globalGenesTabMode = "Category";
				keys += 'GenesTabMode|';
				values += 'Category|';
				//SetSessionProperty('GenesTabMode', "Category");
				break;
		}
	}
	
	
	if(keys.length > 0 && values.length > 0)
	{
	  if(_mergeRequests == null || _mergeRequests == false)
	    SetSessionProperty(keys, values, true);
	}
	
	return keys + '[@|@]' + values;
}

var GenesTab_KnowdeMemory;
var GenesTab_ModeMemory;
function GenesTabControl_CallbackTrigger_Wrapped(_mode, _cbref)
{
  ClearGenesTabSessionValuesForMode(_mode);
    
	switch(globalGenesTabMode)
	{
		case "GenesList":
      var whatId = GetGlobalHighlightedWhatId();
		
			if((!(window.globalLastSelectedKnowde) || globalLastSelectedKnowde == null || globalLastSelectedKnowde == "undefined")
			&& (whatId == null || whatId == ''))
			{
				// show no context message
				var args = "Mode=NoContext";
			if((m_applicationControlOpen == null || m_applicationControlOpen == false) 
			    && (m_appForceOpen == null || m_appForceOpen == false)
			    && m_KGApplicationControl_appID <= 0)
  	      window.location = "examples.aspx";  
  	    else
			    eval(_cbref);
			}
			else
			{
				// callback genes list if its not already loaded against this knowde.
				var knowdeID = whatId;
				var kndTxt = '';
				if(knowdeID == '') // no what so use the selected knowde
				{
				  knowdeID = returnKnowdeID(globalLastSelectedKnowde);
				  //kndTxt = GetKnowdeFullText(globalLastSelectedKnowde); 
				  var knowdeTextObj = GetKnowdeTextObj(globalLastSelectedKnowde); // do use selected-in what
				  if (knowdeTextObj.Noun) // use noun only, but if there's no noun then use the verb
				    kndTxt = knowdeTextObj.Noun;
				  else if (knowdeTextObj.Verb)
				    kndTxt = knowdeTextObj.Verb;
				  else if (knowdeTextObj.Subject)
				    kndTxt = knowdeTextObj.Subject;  
				}
				else // there is a selected what, use that
				{
		      var nounText = GetInnerText(globalLastHighlightedWhat);
          //var verbText = GetVerbTextForKnowde(CurrentWhatRootKnowde);
          //kndTxt = ConcatWords(verbText, nounText);
          kndTxt = nounText;
				}

				if(GenesTab_KnowdeMemory != knowdeID || GenesTab_ModeMemory != globalGenesTabMode || m_bEditable == true || globalDrawInitial == true)
				{
					globalDrawInitial = false;
					GenesTab_ModeMemory = globalGenesTabMode;
					GenesTab_KnowdeMemory = knowdeID;
					ShowLoadingSymbolForTab("Genes", globalGenesTabMode);
					//if(globalCurrentKnowdeIDForTab == null || globalCurrentKnowdeIDForTab != knowdeID)
					  SetSessionProperty('CurrentKnowdeIDForTab', knowdeID);
					// reset value
					globalCurrentKnowdeIDForTab = null;
					
				  var isMapEdit;
				  if (m_bEditable == false || Map_TextEditOnly == 1)
				    isMapEdit = false;
				  else
				    isMapEdit = true;
					var args = "Mode=Genes|SearchPhrase=" + kndTxt + "|IsMapEdit=" + isMapEdit;
          ShowCategories(globalTabStripHCCWidth, false);
					eval(_cbref);
				}
			}
			break;
		case "Search":
			GenesTab_ModeMemory = globalGenesTabMode;
			ShowLoadingSymbolForTab("Genes", globalGenesTabMode);
			var args = "Mode=Search";
      ShowCategories(globalTabStripHCCWidth, false);
			eval(_cbref);
			break;
		case "Category":
		  LastKnowdeClickedKGID = '';
			GenesTab_ModeMemory = globalGenesTabMode;
			ShowLoadingSymbolForTab("Genes", globalGenesTabMode);
			var args = "Mode=Category";
      ShowCategories(globalTabStripHCCWidth, true);
			eval(_cbref);
			break;
		default:
		  // show no context message
		  var args = "Mode=NoContext";
			/*if((m_applicationControlOpen == null || m_applicationControlOpen == false) 
			    && (m_appForceOpen == null || m_appForceOpen == false)
			    && m_KGApplicationControl_appID <= 0)
			    {
		  // redirect to the examples
	    window.location = "examples.aspx";  
	    }
			else*/
			eval(_cbref);
			break;
		
	}
}

function GenesTabControl_CallbackDone_Wrapped(_args, _context)
{ 
  KGListViewControl_CallbackDone(_args, _context);
}

function ClearGenesTabSessionValuesForMode(_mode)
{
  if(_mode == "GenesList")
	{
	  // clear search session and 
    SetSessionProperty('GenesSearch_PhraseName', ''); 
	}
	if(_mode == "Category")
	{
	  // clear search session and knowde session
	  // this needs to be clear in SetSessionForHomeClick in HK.js and MembershipHeader usercontrols code behind as well
	  var keys = 'GenesSearch_PhraseName|CurrentKnowdeIDForTab';
	  var values = '|';
    SetSessionProperty(keys, values, true);
	}
	if(_mode == "Search")
	{
	  // clear knowde session
    SetSessionProperty('CurrentKnowdeIDForTab', ''); 
	}
}

function GenesTabControl_ProcessCallBackError_Wrapped(_args, _context, _clientId)
{
}

function GenesTabControl_GenesDocumentAvatarClick(_ownerKey, _event)
{
	ShowUser(_ownerKey);
	//alert("Have to Open Community Tab for OwnerKey " + _ownerKey + " Here...");
}

function GenesTabControl_KGKndClick(_kgid, _owner, _grpId, _kndId)
{
  ShowKeepKGPrompt("KGTabbedWindowsControl_KGSelected(" + _kndId + ", " + _owner + ", " + _kgid + ", false, false, " + _grpId + ")", true); 
  globalShowKeepKGPrompt = true;
  //LeftPaneMyKnowledgeControl_CallbackTrigger('Action=repopulate'); globalShowKeepKGPrompt = true;
}

function GenesTabControl_KGKndWithAppClick(e, _kgid, _owner, _grpId, _kndId, _strApps)
{
  KGExecuteMapControl_ShowMenu(e, 'IndexedDocs', _strApps, _kgid, _owner, '', _kndId, '', _grpId); 
  LeftPaneMyKnowledgeControl_CallbackTrigger('Action=repopulate'); 
  globalShowKeepKGPrompt = true;
}

function SwitchBetweenCategoryHomeAndList()
{
	var Header = document.getElementById("TCC_GenesTabControl_ListHeaderContainer");
	var Grid = document.getElementById("TCC_GenesTabControl_ListViewGridContainer");
	var Empty = document.getElementById("TCC_GenesTabControl_emptyCont");
	var CatHome = document.getElementById("TCC_GenesTabControl_CatHomePageDiv");
	var CatSwitch = document.getElementById("TCC_GenesTabControl_CatHomeSwitch");
	
	if(CatHome.style.display == "block")
	{
		if(Header != null)
			Header.style.display = "block";
		if(Grid != null)
			Grid.style.display = "block";
		if(Empty != null)
			Empty.style.display = "block";
		if(CatHome != null)
			CatHome.style.display = "none";
		if(CatSwitch != null)
			CatSwitch.innerHTML = "View Home Page for this Category";
	}
	else
	{
		if(Header != null)
			Header.style.display = "none";
		if(Grid != null)
			Grid.style.display = "none";
		if(Empty != null)
			Empty.style.display = "none";
		if(CatHome != null)
			CatHome.style.display = "block";
		if(CatSwitch != null)
			CatSwitch.innerHTML = "View Knowledge Genes in this Category";
	}
}

/*********************************************************************************/

function TabContainerControl_CallbackDirection(_TabID)
{
	switch(_TabID)
	{
		case "communities":
		  KGCommunityTabControl_Activate();
			break;
		case "moretext":
		  // auto load text view	
	    AutoLoadTextViewForKnowde('ChangeTab', null);
			break;
		case "myprofile":
		  KGMyProfileTab_Activate();
			break;
		case "genes":
			GenesTabControl_CallbackTrigger();
			break;
		case "web":
			WebTabControl_CallbackTrigger();
			break;
		case "mykg":
			//LeftPaneMyKnowledgeControl_CallbackTrigger('Action=repopulate');
			break;
		default:
			break;
	}
}

function TabContainerControl_CallbackDone_Wrapped(_args, _context)
{
  var stringArray = _args.split('[@.|.@]'); 
  var TabName = stringArray[0];
  var HTML = stringArray[1];
  var javaScripts = stringArray[2];
  
  // Register Appropriate Scripts
  if (javaScripts.length > 0)
	  EvalRegisterJavaScripts(javaScripts);
	
  // Update Container Content
	var currentContainer = document.getElementById("TCC_" + TabName);
	if(currentContainer != null)
	{
		UpdateHTML(currentContainer, HTML);
	}
	
	// Hide the other DIV containers
	HideContainers(currentContainer);
	
	// Show the new container
	ShowContainer(currentContainer);
}

function UpdateHTML(_currentContainer, _HTML)
{
	// extract all the cdatas lines from callback result
	var cdatas = _HTML.split('<![CDATA[');  
	_currentContainer.innerHTML = _HTML;
	// loop through the cdatas and process each of them
  var z = 0;
  for(z = 1; z < cdatas.length; z++)
  {
    // javascript starting position
    var posStart = cdatas[z].indexOf('window');
    
    // javascript ending position 
    var posEnd = cdatas[z].lastIndexOf('}') + 1;
    
    if(posStart > -1 && posEnd > -1)
    {
      // attemp to extract the javascript
      var jscript = cdatas[z].substring(posStart, posEnd);
     
      // Now we have the potential jscript we need to execute it to 
      // reinitiallise the grid
      if(jscript.length != 0)
      {        
        // redefine the init script on Page
        eval(jscript);
        var posNameStart = jscript.indexOf('window');
        var posNameEnd = jscript.indexOf('=');
        
        var functionName = jscript.substring(posNameStart, posNameEnd);
        // execute the script
        eval(functionName+'()');
        
        var objectNameStart = jscript.indexOf('new ComponentArt_Grid(') + 23;
        var objectNameEnd = jscript.indexOf('List\')') + 4;
        if(objectNameEnd > objectNameStart)
        {
          var objectName = jscript.substring(objectNameStart, objectNameEnd);           
          eval(objectName+'.Render()');
        }
      }
    }      
  }
}

function TabContainerControl_ProcessCallBackError_Wrapped(_args, _context, _clientId)
{
}
var globalHideTabs = false;
function HideContainers(_currentContainer)
{
  if((globalVisibleTab == "TSC_myprofile") || (globalVisibleTab == "TSC_communities" && globalHideTabs) || (globalVisibleTab == "TSC_genes" && globalHideTabs))
  {
    //document.getElementById("HelpContainer").style.display = "none";
    document.getElementById("TabScriptControl").style.display = "none";
    globalHideTabs = false;
    //document.getElementById("ToolStripContainerDiv").parentNode.style.display = "none";
  }
  else
		document.getElementById("TabScriptControl").style.display = "block";
  
	var parentContainer = _currentContainer.parentNode;
	for(containerCounter = 0; containerCounter < parentContainer.childNodes.length; containerCounter++)
	{
		parentContainer.childNodes[containerCounter].className = "TabContainerHidden";
	}
}

function ShowContainer(_currentContainer)
{
	_currentContainer.className = "TabContainerShown";
	
	if(m_EditFrame != null && _currentContainer.id.indexOf('text') != -1 && m_bEditable == true)
	{
		placeCursorAtEnd(m_EditFrame.contentWindow.document.body);
	}
}

/*********************************************************************************
ToolStrip
**********************************************************************************/
var m_toolStripUCIDPrefix = '';

function ChangeTabToolStrip(_tabID)
{
  //debugger;
  var toolStrip = document.getElementById(m_toolStripUCIDPrefix+ 'ToolStripContainerDiv');

  if(toolStrip == null)
    return;
    
  // hide all the tool divs first
  for(var tidx=0; tidx<toolStrip.childNodes.length; tidx++)
  {
		try{toolStrip.childNodes[tidx].style.display = 'none';}
		catch(e){}
  }
  
  switch(_tabID)
  {
    case 'genes':
      SetTooStripSearchButton(_tabID);

      // show the categories control
      if (globalGenesTabMode == "Category")
        ShowCategories(globalTabStripHCCWidth, true);
      else
        ShowCategories(globalTabStripHCCWidth, false);
      break;
    case 'web':
      SetTooStripSearchButton(_tabID);
      break;
    case 'communities':
      if(window.Active_KGID && Active_KGID != "")
        ShowToolStrip(toolStrip, m_toolStripUCIDPrefix + 'KGToolStrip_CommunityDiv');
      else
        toolStrip.style.display = 'none';
      break;
    case 'moretext':
      SetTooStripSearchButton(_tabID);
      ShowToolStrip(toolStrip, m_toolStripUCIDPrefix + 'KGToolStrip_TextDiv');
      break;
      /* can't do this here - it hides all the lower toolstrips and the categories controls at the beginning, but doesn't hide the left hand toolstrips
    case 'whats' :
			ShowToolStrip(toolStrip, m_toolStripUCIDPrefix + 'KGToolStrip_WhatsDiv');
			break;
		case 'semantictree' :
			ShowToolStrip(toolStrip, m_toolStripUCIDPrefix + 'KGToolStrip_TreeDiv');
			break;
			*/
    default:
			// show the categories control
      ShowCategories(globalTabStripHCCWidth, false);
      // hide tool strip
      toolStrip.style.display = 'none';
      break;
  }
}


// _width is the desired width for the categories control
function ShowCategories(_width, _showSelected)
{ 
  if (globalHCCRenderComplete)
  {
    // show or hide the selected category - tab dependent
	  // only need to do this if there isn't a callback, otherwise it'll be handled there
	  // don't need to do it if the control hasn't rendered yet
    if (_showSelected)
      HorizontalCategoriesControl_ShowSelection();
    else
      HorizontalCategoriesControl_HideSelection();
	  
	  // show or hide the breadcrumbs - tab dependent
	  // this isn't handled in the resize callback, but it is handled in the first Render
    if (_showSelected)
      HorizontalCategoriesControl_ShowLoadedBreadcrumbTrail();
    else
      HorizontalCategoriesControl_HideBreadcrumbTrail();
	}
}

function SetTooStripSearchButton(_tabID)
{
  var btn = document.getElementById('KGToolStrip_SearchButton');
  var searchBox = document.getElementById('KGToolStrip_KGSearchTextBox');
  if(btn != null && searchBox != null)
  {
     switch(_tabID)
      {
        case 'genes':
          if(btn.innerText != 'Search for Genes')
          {
            SetInnerText(btn, 'Search for Genes');
            searchBox.value = '';
          }
          break;
        case 'web':
          if(btn.innerText != 'Search the Web')
          {
            SetInnerText(btn, 'Search the Web');
            searchBox.value = '';
          }
          break;
      }
    
  }
}

function ShowToolStrip(_toolStrip, _toolDivId)
{
 // show tools
 if(_toolDivId != null)
 {
    var toolDiv = document.getElementById(_toolDivId);
//    if(toolDiv != null)
//      toolDiv.style.display = 'block';
 }
  // show strip
  _toolStrip.style.display = 'block';
}

/**************** Search ****************/
function KGTabSearch_Click()
{
  var itemType = 0;
  var searchBox = document.getElementById('KGToolStrip_KGSearchTextBox');
  if(searchBox != null && searchBox.value!=null && searchBox.value!='' && searchBox.value.replace(/'/g, '').replace(/^\s*/, '').replace(/\s*$/, '') != '')
  {
    // KGSearchServer will query QuerySearchResults when itemID = '-1'
    var itemName = searchBox.value; //.replace(/'/g, "\\" + "\'")
    
    
    if(globalVisibleTab.toLowerCase().indexOf('_genes') != -1)
    {
			// Set the mode for the Genes Tab control
			setGenesTabMode("Search");
			
      // store in session as root phrase name
      SetSessionProperty('GenesSearch_PhraseName', itemName); 
            
      // callback to GenesTabControl
      GenesTabControl_CallbackTrigger();
    }else if(globalVisibleTab.toLowerCase().indexOf('_web') != -1)
    {
			// Set the mode for the Web Tab control
			setWebTabMode("Search");
			
      // store in session as root phrase name
      SetSessionProperty('WebSearch_PhraseName', itemName); 
            
      // callback to GenesTabControl
      WebTabControl_CallbackTrigger();
    }
  }
  else 
  {
    if(searchBox != null && searchBox.value!=null && searchBox.value!='' && searchBox.value.replace(/^\s*/, '').replace(/\s*$/, '') == '')
    {
      searchBox.value = '';
    }
    
  }
}

function ToolStrip_SearchBoxKeyPress(e)
{
  e = e || window.event;
  //if(e && e.type == "keydown")
  //{
    //alert(e.keyCode);
    if (e.keyCode == 13) // enter
    {
      KGTabSearch_Click();
      return false;
    }
  //}
}

/********************* LEFT PANE TABS ******************************/

function ChangeLeftTab(_tabID, _tabName, _loadContent)
{
//debugger;
	// Grab the Tab & Tabstrip Elements
	var TabID = "LTSC_" + _tabID;
	var Tab = document.getElementById(TabID);
	var TabStrip = Tab.parentNode;
	
	// Grab container
	var currentContainerID = "LTSC_" + _tabID + "Container";
	var currentContainer = document.getElementById(currentContainerID);
	
	// Deselect Current Tab & Select new one
	UpdateTabUI(TabStrip, Tab, true);
	
	// Show/Hide toolstrip
	ChangeLeftTabToolStrip(_tabID);
	
	// Set the global js variable
	globalPreviousTab = globalVisibleLeftTab;
	globalVisibleLeftTab = TabID;
	
	// Hide the other DIV containers
	HideContainers(currentContainer);
	
	// Show the new container
	var wimage = document.getElementById('WhatWhatIsArrowImage');
	if(_tabID == "whats")
	{
		currentContainer.className = "whatsContainer";
		if(wimage != null)
		  wimage.style.display = 'block';
  }
	else
	{
		currentContainer.className = "semTreeContainer";
		if(wimage != null)
		  wimage.style.display = 'none';
	}
}

function ShowHideButton(_show, _btnId)
{
  var btn = document.getElementById(_btnId);
  if (btn)
  {
    if (_show)
      btn.style.display = "";
    else
      btn.style.display = "none";
  }
}

function IsLeftTabShown(_tabID)
{
  var currentContainerID = "LTSC_" + _tabID + "Container";
  var currentContainer = document.getElementById(currentContainerID);
  if (currentContainer != null && currentContainer.className.indexOf("TabContainerHidden") == -1)
    return true;
  else
    return false;
}

/**************** What WhatIs Tab Control *********************/
var globalWhatWhatIsTabKnowdeId;
var globalWhatWhatIsTabDirection; // set this using SetWhatWhatIsTabDirection to toggle the change direction buttons as well
var globalWhatWhatIsTabInheritedKnowde;
var globalWhatWhatIsTabInheritLnkdKnowde;
function SetWhatWhatIsTabDirection(_direction)
{
  // _direction might be integer e.g. WHAT_DIRECTION or string e.g. "What"
  var dirString = (_direction + '').toLowerCase();

  if (_direction == WHAT_DIRECTION || dirString == "what")
  {
    globalWhatWhatIsTabDirection = WHAT_DIRECTION;
    ShowHideButton(true, "KGToolStrip_What");
    ShowHideButton(false, "KGToolStrip_WhatIs");
  }
  else if (_direction == WHATIS_DIRECTION || dirString == "whatis")
  {
    globalWhatWhatIsTabDirection = WHATIS_DIRECTION;
    ShowHideButton(false, "KGToolStrip_What");
    ShowHideButton(true, "KGToolStrip_WhatIs");
  }
}

function ShowHideSelectIntoKnowdeBtn(_show)
{
  ShowHideButton(_show, "KGToolStrip_WhatIntoKnowde")
}

function WhatWhatIsTabControl_ReloadForKnowde(_knowde, _direction)
{ 
  var knowdeID = returnKnowdeID(_knowde);
  var inheritedKnowde = _knowde.getAttribute('isInheritedMethod');
  var inheritLnkdKnowde = _knowde.getAttribute('isInheritLinkedMethod');
  var parentKnowdeID = _knowde.getAttribute('parentKnowdeID');
  var thenPriorKnowdeID = GetThenPriorKnowdeID(_knowde);
  var knowdeDirection = GetCurrentDirectionOfKnowde(_knowde);
  WhatWhatIsTabControl_Reload(knowdeID, inheritedKnowde, inheritLnkdKnowde, _direction, parentKnowdeID, thenPriorKnowdeID, knowdeDirection, true);
}

function WhatWhatIsTabControl_Reload(_knowdeID, _inheritedKnowde, _inheritLnkdKnowde, _direction, _parentKnowdeID, _thenPriorKnowdeID, _knowdeDirection, _focusOnMap)
{
//debugger;
  ShowHideSelectIntoKnowdeBtn(false);
    
  if(_knowdeID == 0 || m_IsEditFromNewKnowde == true)
  {
    WhatWhatIsTabControl_ClearContent();
    return;
  }
  
  // what about the obj knowde?  these will be undefined, but the obj knowde can still have WHATs/WHATISs
  if(!_inheritedKnowde)
    _inheritedKnowde = false;
  if(!_inheritLnkdKnowde)
		_inheritLnkdKnowde = false;
  
  // check whether selected knowde or direction has changed
  // or need to reload as we are not currently showing whats
  if(!_knowdeID != null && (globalWhatWhatIsTabKnowdeId == null || globalWhatWhatIsTabKnowdeId != _knowdeID || 
      globalWhatWhatIsTabDirection != _direction || !(CurrentlyShowingWhats && CurrentlyShowingWhatIss)))
  {
    WhatWhatIsTabControl_ShowLoadingMessage();
    
    var args = 'Action=Reload|KnowdeId=' + _knowdeID;
    args += '|KGId=' + Active_KGID;

    args += '|inheritedKnowde=' + _inheritedKnowde;
    args += '|inheritLnkdKnowde=' + _inheritLnkdKnowde;
    //debugger;
    if(_direction != null)
    {
      args += '|Direction=' + _direction;
    }
    else
    {
      // lets check we have a direction based on the selected tab
      switch(globalLeftPaneSelectedTab)
      {
				case 'LeftPaneExpanderTextWhatIs':
					args += '|Direction=8';
					ChangeArrowClass("WhatIs", false);
					ChangeArrowClass("What", true);
					break;
				case 'LeftPaneExpanderTextWhat':
					args += '|Direction=4';
					ChangeArrowClass("WhatIs", true);
					ChangeArrowClass("What", false);
					break;
				default:
					// This defaults the list to WHATs if the user hasnt selected a direction.
					args += '|Direction=4';
					ChangeArrowClass("WhatIs", true);
					ChangeArrowClass("What", false);
					break;
      }
    }
    if(_parentKnowdeID != null && _parentKnowdeID != 0)
      args += '|ParentId=' + _parentKnowdeID;
    if(_thenPriorKnowdeID != null && _thenPriorKnowdeID != 0)
      args += '|ThenPriorId=' + _thenPriorKnowdeID;
    if(_knowdeDirection != null)
      args += '|KnowdeDirection=' + _knowdeDirection;
    if (_focusOnMap)
      args += '|FocusOnMap=true';
    WhatWhatIsTabControl_CallbackTrigger(args);
    globalWhatWhatIsTabKnowdeId = _knowdeID;
    globalWhatWhatIsTabInheritedKnowde = _inheritedKnowde;
    globalWhatWhatIsTabInheritLnkdKnowde = _inheritLnkdKnowde;
    if(_direction == null)
      SetWhatWhatIsTabDirection(globalWhatWhatIsTabDirection);
    else
      SetWhatWhatIsTabDirection(_direction);
  }
}

function WhatWhatIsTabControl_Edit()
{  
  // check whether selected knowde has changed
    var args = 'Action=Edit|KnowdeId=';
    if(globalWhatWhatIsTabKnowdeId)
			args += globalWhatWhatIsTabKnowdeId;
		else
			args += returnKnowdeID(globalLastSelectedKnowde);
    args += '|KGId=' + Active_KGID;
    WhatWhatIsTabControl_CallbackTrigger(args);

}

function WhatWhatIsTabControl_SwitchDirection(_direction)
{
//debugger;
  // check whether selected knowde has changed
  if(globalWhatWhatIsTabKnowdeId != null)
  {
		var knowde = globalLastSelectedKnowde;
	  var knowdeDirection = GetKnowdeDirection(knowde);
	  var parentKnowdeID = knowde.getAttribute('parentKnowdeID');
	  
    var args = 'Action=SwitchDirection|KnowdeId=' + globalWhatWhatIsTabKnowdeId;
    args += '|KGId=' + Active_KGID;
    if(globalWhatWhatIsTabInheritedKnowde)
			args += '|inheritedKnowde=' + globalWhatWhatIsTabInheritedKnowde;
		else
			args += '|inheritedKnowde=false';
		if(globalWhatWhatIsTabInheritLnkdKnowde)
			args += '|inheritLnkdKnowde=' + globalWhatWhatIsTabInheritLnkdKnowde;
		else
			args += '|inheritLnkdKnowde=false';
    if(_direction != null)
      args += '|Direction=' + _direction;
    if(parentKnowdeID != null)
      args += '|ParentId=' + parentKnowdeID;
    if(knowdeDirection != null)
			args += '|KnowdeDirection=' + knowdeDirection;
    
    CurrentlyShowingWhats = false;
    CurrentlyShowingWhatIss = false;
    m_SelectedWhatEditing = false;
    m_IsEditFromNewWhat = false;
    WhatWhatIsTabControl_CallbackTrigger(args);
    SetWhatWhatIsTabDirection(_direction);
    RemoveBottomWhatEditBox();
    ActivateAddWhatsLink(true);
  }
  else
  {
    CurrentWhatRootKnowde = globalLastSelectedKnowde;
    var inheritedKnowde = CurrentWhatRootKnowde.getAttribute('isInheritedMethod');
    var inheritLnkdKnowde = CurrentWhatRootKnowde.getAttribute('isInheritLinkedMethod');
    setTimeout('WhatWhatIsTabControl_Reload(' + returnKnowdeID(globalLastSelectedKnowde) + ', ' + inheritedKnowde + ', ' + inheritLnkdKnowde + ', ' + _direction +', null, null, null, true)', 100);
  }
}

function WhatWhatIsTabControl_CallbackTrigger_Wrapped(_args, _cbref)
{
	var args = _args;
  if(m_bEditable == true) // in edit mode
      args +=  '|MapEditing=true';
	eval(_cbref);
}

function WhatWhatIsTabControl_CallbackDone_Wrapped(_args, _context)
{ 
  // Check for a session time out before completing the callback and before checking for exceptions
  if (CheckSessionTimeout())
    return;

  // check for exceptions
  if (_args.indexOf("Exception") == 0 || _args.length == 0)
  {
    WhatWhatIsTabControl_ProcessCallBackError(_args, _context);
    return;
  }

  // get the parameters
  var argsSplit = _args.split('[@|@]');
  var json = argsSplit[0];
  var retMsg = eval( '(' + json + ')' );
  
  // don't keep the iframe; do load the contents
  var javascripts = argsSplit[1];
  var htmlContent = _args.substr(argsSplit[0].length + argsSplit[1].length + 10);
  
  var holderId = retMsg.HolderId;

  var holder = document.getElementById(holderId);
  if (!holder)
  {
    WhatWhatIsTabControl_ProcessCallBackError('The holder doesn\'t exist ' + holderId);
    return;
  }
  
  // fill the control
  SetOuterHtml(holder, htmlContent);
  
  // eval any javascripts
  if (javascripts)
    eval(javascripts);
    
  if (window.InitialiseWhatList)
  {
    InitialiseWhatList(retMsg.Direction);
    // sometimes we don't want the what list to steal the focus, e.g. knowde click
    //    but sometimes we do, e.g. click here to add a what
    if (retMsg.FocusOnMap.toLowerCase() == "true" && window.MapViewDefaultFocus)
      MapViewDefaultFocus();
  }
  
  // don't show the no-whats message if there's a selected-in what
  var whatTextDiv = GetWhatTextDiv(globalLastSelectedKnowde);
  if (whatTextDiv) // means there is a selected-in what - copied from all the checks to stop you editing a knowde with a selected-in what
  {
    var messageEl = document.getElementById("WhatWhatIsTabMessageDiv"); 
    if (messageEl) // there might not be a message
    {
      var messageMode = messageEl.getAttribute("MessageMode");
      if ( messageMode == "KnowdeNoWhat"
        || messageMode == "KnowdeNoWhatIs"
        || messageMode == "KnowdeNoWhatAuthoring"
        || messageMode == "KnowdeNoWhatIsAuthoring")
      {// check the MessageMode attribute incase we have a different type of message
        messageEl.style.display = "none";
      }
    }
  }
}

function WhatWhatIsTabControl_ProcessCallBackError_Wrapped(_args, _context, _clientId)
{
  var alertMessage = "The KGWhatWhatIsTabControl has encountered an error. \n\n" + _args;
  alert(alertMessage);
} 

function WhatWhatIsTabControl_GetHolder_Wrapped(_holderId)
{
  var holder = document.getElementById(_holderId);
  return holder
}

function WhatWhatIsTabControl_ShowLoadingMessage()
{
  var holder = WhatWhatIsTabControl_GetHolder();
  if(holder != null)
    holder.innerHTML = '<table class=\"TabLoadingIcon\" ><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
}

function WhatWhatIsTabControl_ClearContent()
{
  var holder = WhatWhatIsTabControl_GetHolder();
  if(holder != null)
    holder.innerHTML = '<table class=\"TabLoadingIcon\" ><tr><td align=\"center\" style=\"font-size: xx-small\"></td></tr></table>';
    
    ShowHideSelectIntoKnowdeBtn(false);
    ShowHideButton(false, "KGToolStrip_What");
    ShowHideButton(false, "KGToolStrip_WhatIs");
}

function ActivateSelectInKnowde(_activate)
{
	if(_activate == true)
		document.getElementById("LTSC_KGWhatWhatIsTabCtrl_selectIntoKnowde").className = "enabledLink";
	else
		document.getElementById("LTSC_KGWhatWhatIsTabCtrl_selectIntoKnowde").className = "disabledLink";
}

function mouseOverArrow(_direction)
{
	switch(_direction)
	{
		case "WhatIs":
			ChangeArrowTooltip(_direction, ShouldArrowBeGrey(_direction));
			ChangeArrowClass(_direction, false);
			break;
		case "What":
			ChangeArrowTooltip(_direction, ShouldArrowBeGrey(_direction));
			ChangeArrowClass(_direction, false);
			break;
		case "How":
		case "Why":
		  ChangeArrowTooltip(_direction, ShouldArrowBeGrey(_direction));
		  if (!IsHowWhyArrowDisabledForEdit())
		    ChangeArrowClass(_direction, false);
			break;	
	}
}

function mouseOutArrow(_direction)
{
	switch(_direction)
	{
		case "WhatIs":
			if(globalWhatWhatIsTabDirection == WHATIS_DIRECTION)
				ChangeArrowClass(_direction, false);
			else
				ChangeArrowClass(_direction, true);
			break;
		case "What":
			if(globalWhatWhatIsTabDirection == WHAT_DIRECTION)
				ChangeArrowClass(_direction, false);
			else
				ChangeArrowClass(_direction, true);
			break;
		case "How":
		case "Why":
	    ChangeArrowClass(_direction, ShouldArrowBeGrey(_direction));
	}
}

function ChangeArrowClass(_direction, _greyed)
{
	switch(_direction)
	{
		case "WhatIs":
			if(_greyed == true)
				document.getElementById("WhatIsArrow").className = "LeftPaneExpanderWhatIsArrow";
			else
				document.getElementById("WhatIsArrow").className = "LeftPaneExpanderWhatIsArrow";
			break;
		case "What":
			if(_greyed == true)
				document.getElementById("WhatArrow").className = "LeftPaneExpanderWhatArrow";
			else
				document.getElementById("WhatArrow").className = "LeftPaneExpanderWhatArrow";
			break;
		case "How":
	    if(_greyed == true)
			  document.getElementById("HowArrow").className = "HowArrowGrey";
		  else
			  document.getElementById("HowArrow").className = "HowArrow";
			break;
		case "Why":
	    if(_greyed == true)
			  document.getElementById("WhyArrow").className = "WhyArrowGrey";
		  else
			  document.getElementById("WhyArrow").className = "WhyArrow";
			break;	
	}
}

function ChangeArrowTooltip(_direction, _greyed)
{
	// get arrow and directionText
	switch(_direction)
	{
		case "How":
		  ChangeHowWhyArrowTooltip(_greyed, "HowArrow", "HOW");
		  break;
		case "Why":  
		  ChangeHowWhyArrowTooltip(_greyed, "WhyArrow", "WHY");
		  break;
		case "What":  
		  ChangeHowWhyArrowTooltip(_greyed, "WhatArrow", "WHAT");
		  break;
		case "WhatIs":  
		  ChangeHowWhyArrowTooltip(_greyed, "WhatIsArrow", "WHAT-IS");
		  break;
	}
}

function ChangeHowWhyArrowTooltip(_greyed, _arrowId, _dirnText)
{
  // change the tooltip and cursor on the arrow	  
  var arrow = document.getElementById(_arrowId);
	if (arrow)
	{
    if(_greyed) 
    {
      if(IsHowWhyArrowDisabledForEdit()) 
      {
        arrow.title = m_tooltips.arrowDisabledForEdit.replace(/\[direction\]/g, _dirnText);
  	    arrow.style.cursor = "default";
      }
      else // can click it
      {
		    arrow.title = m_tooltips.greyArrow.replace(/\[direction\]/g, _dirnText);
		    arrow.style.cursor = "pointer";
		  }
		}
	  else // can't click it
	  {
  	  arrow.title = m_tooltips.arrow.replace(/\[direction\]/g, _dirnText);
  	  arrow.style.cursor = "default";
  	}  
	}
}

function ShouldArrowBeGrey(_direction)
{
  switch(_direction)
	{
	  case "How": // arrow is grey if we're not already showing children in that direction
		  return (globalLastSelectedKnowde.getAttribute('knowdeType') == "why");
			break;
		case "Why": // arrow is grey if we're not already showing children in that direction
      return (globalLastSelectedKnowde.getAttribute('knowdeType') == "how");
      break;
    case "What":
      return (CurrentlyShowingWhats == false);
      break;
    case "WhatIs":
      return (CurrentlyShowingWhatIss == false);
      break;
  }
}

function IsHowWhyArrowDisabledForEdit()
{
  // can't refocus on new knowde
  return (m_IsEditFromNewKnowde == true || globalLastSelectedKnowde.IsNewKnowde == true);
}

function ResetHowWhyArrow()
{
  //SetArrow('How');
  //SetArrow('Why');
}

function SetArrow(_direction)
{
  var greyed = ShouldArrowBeGrey(_direction);
  ChangeArrowClass(_direction, greyed);
  ChangeArrowTooltip(_direction, greyed); // it's also set on mouseover to check, but without this Opera is always one behind with the cursor
}

function HowWhyArrowClick(_direction, e)
{
  e = e || window.event;
  CancelBubble(e);

  // we might already be showing children in that direction,
  // each arrow has this onclick method, but only grey arrows should do anything 
  // alternative = reset onclick in SetArrow
  if (globalLastSelectedKnowde && ShouldArrowBeGrey(_direction) && !IsHowWhyArrowDisabledForEdit())
  {
    ReCenterFromKeyboard();
  }
}

function selectIntoKnowdeMouseOver()
{
}

function selectIntoKnowdeClick(e)
{
  if (!e) var e = window.event;
	var targ = e.target || e.srcElement;
	
	// only proceed if the link is not disabled
	if (targ.className.indexOf("disabledLink") == -1)
	{
	  RefocusOnHighlightedWhatOrWhatIs();
	}
}

/************* Repopulation ***********************************/
// Waits until any scrolling has finished before repopulating 
function RepopulateTabbedWindow(_action, _knowdeID)
{
	// repopulate if the tab windows are visible
	var PaneC = Splitter1.Panes[1];
	if(PaneC.element.style.display != "none")
	{
		if(globalVisibleTab != null)
		{
			// repopulate open tab only
			switch(globalVisibleTab)
			{
				case "TSC_moretext":
					AutoLoadTextViewForKnowde(_action, _knowdeID);
					break;
				case "TSC_web":
					WebTabControl_CallbackTrigger();
					break;
				case "TSC_genes":
					GenesTabControl_CallbackTrigger();
					break;
				case "TSC_communities":
				  KGCommunityTabControl_Activate();
				  // need to also callback on the left hand options for the tabs
		      TabScriptControl_CallbackTrigger('CurrentSelectedTab=' + globalVisibleTab);      
					break;
				case "TSC_myprofile":
					break;
			}
		}
  }
}

// Waits until any scrolling has finished before repopulating 
function RepopulateTextView()
{
  /*if (globalAutoScrollDirection != null)
  {
    clearTimeout(repopulate);
    repopulate = setTimeout("RepopulateTextView()", 200); 
  }
  else
    KGTabbedWindowsControl_CallbackTrigger('KnowdeHover-ReloadTextView'); */
}


function LeftPaneChangeTab(_tabID, _tabName, _loadContent)
{
//debugger;
    // Grab the Tab & Tabstrip Elements
	var TabID = "LTHC_" + _tabID;
	var Tab = document.getElementById(TabID);
	var TabStrip = Tab.parentNode;
	var currentContainerID = "LTSC_" + _tabID + "Container";
	var currentContainer = document.getElementById(currentContainerID);
	
	// Deselect Current Tab & Select new one
	LeftPaneUpdateTabUI(TabStrip, Tab);
	//LeftPaneExpanderOptionBox_ToggleVisibility('Hide', 'Show', 'LeftPaneExpanderText');
	
	// Set the global js variable
	//var previousTab = globalVisibleTab;
	//globalVisibleTab = TabID;
	

	// Call-back necessary control
	// we may need to callback tab as they have different modes... new check required.
	if(_loadContent == null || _loadContent != false)
	  TabContainerControl_CallbackDirection(_tabID);
	
	// Hide the other DIV containers
	LeftPaneHideContainers(currentContainer);
	
	// Show the new container
	LeftPaneShowContainer(currentContainer);
	
}

function LeftPaneUpdateTabUI(_tabStrip, _tab)
{
	// deselect all Tabs
	for(tabCounter = 0; tabCounter < _tabStrip.childNodes.length; tabCounter++)
	{
		_tabStrip.childNodes[tabCounter].isSelected = false;
		_tabStrip.childNodes[tabCounter].className = _tabStrip.childNodes[tabCounter].className.replace("Selected","Visible");
		
	}

	// select new tab
	_tab.isSelected = true;
	_tab.className = _tab.className.replace("Visible","Selected");

}
  
function LeftPaneHideContainers(_currentContainer)
{
	var parentContainer = _currentContainer.parentNode;
	for(containerCounter = 0; containerCounter < parentContainer.childNodes.length; containerCounter++)
	{
		parentContainer.childNodes[containerCounter].className = "TabContainerHidden";
	}
}

function LeftPaneShowContainer(_currentContainer)
{
	_currentContainer.className = "TabContainerShown";
}

function LeftPaneMyKnowledgeControl_CallbackTrigger_Wrapped(_args, _cbReference)
{ 
  CallbackTrigger_Wrapped(_args, _cbReference);
}
var globalFavouriteKGs;
function LeftPaneMyKnowledgeControl_CallbackDone_Wrapped(_args, _context)
{ 
  //KGListViewControl_CallbackDone(_args, _context);
    // check for exceptions
  if (_args.indexOf("Exception") == 0 || _args.length == 0)
  {
    KGListViewControl_CallbackError(_args, _context);
    return;
    // looking for indexOf == 0 instead of > -1 incase it's genuine html that happens to contain 'Exception' in there
    // e.g. a user called "... Exceptional ..." 
  }

  // get the parameters
  var argsSplit = _args.split('[@|@]');
  var json = argsSplit[0];
  var javascripts = argsSplit[1];
  var htmlContent = argsSplit[2];
  
  var retMsg = eval( '(' + json + ')' );
  var holderId = retMsg.HolderId;
  
  var holder = document.getElementById(holderId);
  if (!holder)
  {
    KGListViewControl_CallbackError('The holder doesn\'t exist ' + holderId);
    return;
  }
  
  // fill the control
  SetOuterHtml(holder, htmlContent);
  
   // eval any javascripts
  if (javascripts)
    eval(javascripts);
  
  // fire the callbackCompleteMethod, if required
  var callbackCompleteMethod = retMsg.CallbackCompleteMethod;
  if (callbackCompleteMethod)
    eval(callbackCompleteMethod);
    //debugger;
  globalFavouriteKGs = retMsg.FavouriteKGs;
  //debugger;
  if(retMsg.Action == 'unsub' && retMsg.Kgid == Active_KGID)
  {
		//basically what just happened here is the user removed the kg they are currently viewing from the lefthandpane.
		// this means we need to update the 'keep this KG' tool bar option
		KGMapToolbar.EnableLink('addToMaps');
		KGMapToolbar.ShowLink('addToMaps'); 
		
		//dont forget to enable the popup again.
		globalShowKeepKGPrompt = true;
  }
  //debugger;
  if(retMsg.Action == 'repopulate' && retMsg.HighlightedKgid > 0 && Active_KGOwnerKey != WM_readCookie('UserID'))
  {
		//basically what just happened here is the user removed the kg they are currently viewing from the lefthandpane.
		// this means we need to update the 'keep this KG' tool bar option
								
		KGMapToolbar.DisableLink('addToMaps');
		KGMapToolbar.ShowLink('addToMaps');
	
		//dont forget to enable the popup again.
		globalShowKeepKGPrompt = false;
  }
  else if (Active_KGOwnerKey == WM_readCookie('UserID') && Active_KGOwnerKey != '')
  {
		globalShowKeepKGPrompt = false;
  }
  else if (Active_KGOwnerKey == '')
  {
    globalShowKeepKGPrompt = true;
  }
  CloseUOSMessageBox();
}

var globalLeftPaneSelectedTab = "";
var globalShowLeftPaneWhatWidget = false;
var globalViewingFavourite = false;
function LeftPaneExpanderOptionBox_ToggleVisibility(_mapVisibility, _whatVisibility, _tabId)
{

//debugger;
	// first deselect the selected tab
	if(globalLeftPaneSelectedTab != "" && globalLeftPaneSelectedTab != _tabId && _tabId)
	{
		document.getElementById(globalLeftPaneSelectedTab).className = document.getElementById(globalLeftPaneSelectedTab).className.replace("_Selected", "");
	}
	
	if(_tabId && globalLeftPaneSelectedTab != _tabId)
	{
		globalLeftPaneSelectedTab = _tabId;
		document.getElementById(globalLeftPaneSelectedTab).className = document.getElementById(globalLeftPaneSelectedTab).className + "_Selected";
	}

  DisplayLeftPaneMyMapsWidget(_mapVisibility);
  
  DisplayLeftPaneWhatWidget(_whatVisibility);
}

function DisplayLeftPaneMyMapsWidget(_mapVisibility)
{
	document.getElementById("LeftPaneExpanderOptionBox").className = "LeftPaneExpandOptionBox" + _mapVisibility;
  document.getElementById("LeftPaneExpanderArrow").className = "LeftPaneExpandOptionArrow" + _mapVisibility;
  
}

function DisplayLeftPaneWhatWidget(_whatVisibility)
{
  // only show the WHAT/WHATIS widget if it is safe to do so
  if(globalShowLeftPaneWhatWidget)
  {
		document.getElementById("LeftPaneExpanderWhatOptionBox").className = "LeftPaneExpandWhatOptionBox" + _whatVisibility;
		document.getElementById("LeftPaneExpanderArrowWhats").className = "LeftPaneExpandOptionArrow" + _whatVisibility;
  }
}

function LeftPaneExpanderOptionBox_OpenWhats()
{
  LeftPaneExpanderOptionBox_OpenWhatWhatIsList(WHAT_DIRECTION);
  var txtEl = document.getElementById("LeftPaneExpanderTextWhat");
  txtEl.className='LeftPaneExpandWhatOptionText_Selected';
  
  //WhatWhatIsTabControl_SwitchDirection(4); 
}

function LeftPaneExpanderOptionBox_OpenWhatIs()
{
  LeftPaneExpanderOptionBox_OpenWhatWhatIsList(WHATIS_DIRECTION);
  var txtEl = document.getElementById("LeftPaneExpanderTextWhatIs");
  txtEl.className='LeftPaneExpandWhatIsOptionText_Selected';
  
  //WhatWhatIsTabControl_SwitchDirection(8); 
}

function LeftPaneExpanderOptionBox_OpenWhatWhatIsList(_direction)
{
  if (!_direction) // default to what direction
    _direction = WHAT_DIRECTION;
    
  LeftPaneExpanderOptionBox_Clicked('whats');
  
  if (_direction == WHAT_DIRECTION)
    LeftPaneExpanderOptionBox_ToggleVisibility('Show', 'Hide', 'LeftPaneExpanderTextWhat');
  else if (_direction == WHATIS_DIRECTION)
    LeftPaneExpanderOptionBox_ToggleVisibility('Show', 'Hide', 'LeftPaneExpanderTextWhatIs'); 
  
  CurrentWhatRootKnowde = globalLastSelectedKnowde;
  m_SelectedWhatEditing = false;
  m_IsEditFromNewWhat = false;

  WhatWhatIsTabControl_ReloadForKnowde(CurrentWhatRootKnowde, _direction);
}


function LeftPaneExpanderOptionBox_Clicked(_tabToOpen)
{
  // expand the left pane
  OpenLeftPanel();
  // and select the required tab
  LeftPaneChangeTab(_tabToOpen, 'Knowledge Genes');
}

function LeftPaneMyKnowledgeControl_RemoveKG()
{
	m_UosMessageBox.innerHTML= '<div style=\"position:absolute;width:400px;height:120px;border:gray solid 1pt;background:white\"><table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" />Removing Knowledge Gene....</td></tr></table></div>';
  
  var args='Action=unsub|kgid='+ selectedKGForDelete;
  eval("LeftPaneMyKnowledgeControl_CallbackTrigger('" + args + "')");
}

function LeftPaneMyKnowledgeControl_DislayDeleteKGMessage(_mode, _kgId, _groupId, _controlDivClientID, e)
{
  selectedKGForDelete = _kgId;
  selectedGroupIdForKGDelete = _groupId;
  LeftPaneMyKnowledgeControl_EnsureDeleteKGMessage(_mode);
  PositionUosMessageBox(_controlDivClientID, false, e);
}

function LeftPaneMyKnowledgeControl_DeleteKG()
{
//debugger;
  m_UosMessageBox.innerHTML= '<div style=\"position:absolute;width:400px;height:120px;border:gray solid 1pt;background:white\"><table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" />Deleting Knowledge Gene....</td></tr></table></div>';
  
	var args = 'Action=deleteKG|kgId=' + selectedKGForDelete + '|groupId='+ selectedGroupIdForKGDelete;
	eval("LeftPaneMyKnowledgeControl_CallbackTrigger('" + args + "')");
	
	if(selectedKGForDelete == Active_KGID)
	{
		// Callback the map-view
		KGTabbedWindowsControl_MyHK_KGSelected("", WM_readCookie('UserID'), globalHelpKG, null, "0");
	}
}

///////////////////////
// Ensures that the delete message box is on the page
function LeftPaneMyKnowledgeControl_EnsureDeleteKGMessage(_mode)
{
  m_UosMessageBox = document.getElementById("DeleteKGMessageBox");
  
  if(m_UosMessageBox == null)
  {
    m_UosMessageBox = document.createElement("div");
    m_UosMessageBox.setAttribute("id", "DeleteKGMessageBox");
    m_UosMessageBox.style.display = "none";
    m_UosMessageBox.style.width = "400px"
    m_UosMessageBox.style.height = "160px";
    m_UosMessageBox.style.position = "absolute";
    m_UosMessageBox.style.zIndex = TopZIndex();
    
    switch(_mode)
    {
			case "remove":
				m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>You are about to remove this Map from your Knowledge Genes<sup>&#174;</sup></td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>Are you sure you wish to proceed?</td></tr><tr><td align='right'><button type='button' onclick='LeftPaneMyKnowledgeControl_RemoveKG()'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";
				break;
			case "delete":
				if(selectedKGForDelete == Active_KGID)
				{
					m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Do you want to delete this Knowledge Gene<sup>&#174;</sup>?</td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>Deleting this Knowledge Gene&reg; will remove it from the database. Any attachments and other information associated with this Knowledge Gene<sup>&#174;</sup> will also be removed. <br/>Any published versions will also be lost. <br/><br/> After deleting this Knowledge Gene, the home page map will load.</td></tr><tr><td align='right'><button type='button' onclick='LeftPaneMyKnowledgeControl_DeleteKG()'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";
				}
				else
				{
					m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Do you want to delete this Knowledge Gene<sup>&#174;</sup>?</td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>Deleting this Knowledge Gene&reg; will remove it from the database. Any attachments and other information associated with this Knowledge Gene<sup>&#174;</sup> will also be removed. <br/>Any published versions will also be lost.</td></tr><tr><td align='right'><button type='button' onclick='LeftPaneMyKnowledgeControl_DeleteKG()'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";
				}
				break
    }
    
    document.body.appendChild(m_UosMessageBox);
  }
  else
  {
    switch(_mode)
    {
			case "remove":
				m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>You are about to remove this Map from your Knowledge Genes<sup>&#174;</sup></td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>Are you sure you wish to proceed?</td></tr><tr><td align='right'><button type='button' onclick='LeftPaneMyKnowledgeControl_RemoveKG()'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";
				break;
			case "delete":
				if(selectedKGForDelete == Active_KGID)
				{
					m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Do you want to delete this Knowledge Gene<sup>&#174;</sup>?</td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>Deleting this Knowledge Gene&reg; will remove it from the database. Any attachments and other information associated with this Knowledge Gene<sup>&#174;</sup> will also be removed. <br/>Any published versions will also be lost. <br/><br/> After deleting this Knowledge Gene, the home page map will load.</td></tr><tr><td align='right'><button type='button' onclick='LeftPaneMyKnowledgeControl_DeleteKG()'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";
				}
				else
				{
					m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Do you want to delete this Knowledge Gene<sup>&#174;</sup>?</td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>Deleting this Knowledge Gene&reg; will remove it from the database. Any attachments and other information associated with this Knowledge Gene<sup>&#174;</sup> will also be removed. <br/>Any published versions will also be lost.</td></tr><tr><td align='right'><button type='button' onclick='LeftPaneMyKnowledgeControl_DeleteKG()'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";
				}
				break
    }
    m_UosMessageBox.style.zIndex = TopZIndex(); //Show on top of other items
  }
}

function CommunitiesFilterChanged()
{  
  var dropList = document.getElementById("TSC_TabStripControl_CommunityFilter");
  
  if ( dropList != null && dropList != undefined )
  {
    var value = dropList.value;
    
    var sessionValue = "";
    
    if ( value == "KG" )
    {
      sessionValue = value + "|" + Active_KGID;    
    }
    else if ( value == "Knowde" )
    {
      sessionValue = value + "|" + Active_KGID;    
    }
        
    SetSessionProperty("CommunityTabFilterChange", sessionValue);
    
    // now need to call the KGCommunityControl callback trigger
    var args = "Action=QueryHasLink";
    KGCommunityControl_CallbackTrigger(args);    
  }
}

function AlertOptionCheckboxClicked()
{
  var checkBox = document.getElementById("TSC_TabStripControl_AlertOptionCheckbox");
  
  if ( checkBox != null && checkBox != undefined )
  {
    if ( checkBox.checked == true )
      SetSessionProperty("AlertOptionCheckboxChange", "true" + "|" + Active_KGID);
    else
      SetSessionProperty("AlertOptionCheckboxChange", "false" + "|" + Active_KGID);
  }
}

function TabScriptControl_CallbackTrigger_Wrapped(_args, _cbReference)
{ 
  CallbackTrigger_Wrapped(_args, _cbReference);
}

function TabScriptControl_CallbackDone_Wrapped(_args, _context)
{ 
  var argsSplit = _args.split('[@|@]');
  
  var holderID = argsSplit[0];
  var selectedTab = argsSplit[1];
  var htmlContent = argsSplit[2];
  
  var holder = document.getElementById(holderID);
  
  if ( holder != null && holder != undefined )
  {
    SetOuterHtml(holder, htmlContent);
  }
  
  // select the correct tab
  if ( selectedTab != "none" )
  {
    ChangeTab(selectedTab.replace('TSC_',''), '', false );
    
    if ( selectedTab == "TSC_communities" )
    {
      var iframeTab = document.getElementById("TCC_ctl01_IFrameTab");
      if ( iframeTab != null && iframeTab != undefined )
      {
        if ( iframeTab.style.display == "block" )
        {
          // need to show the community options
          var communitiesOptionsDiv = document.getElementById("TSC_TabStripControl_OptionDiv");
          if ( communitiesOptionsDiv != null )
          {
            communitiesOptionsDiv.style.display = "block";
          }           
        }     
      }    
    }
  }
}







  
  
  
  
  
  
  
  
