﻿// JScript File
var globalVisibleTab = ''; 
var globalPreviousTab;
var globalVisibleLeftTab;
var globalAutoLoadTextView = true;
var globalLoadTabOnPageLoad = true;
var globalLoadUserProfile = false;
var globalLoadMoreTextOnPageLoad = false;
var globalCurrentKnowdeIDForTab;
var globalDrawInitial = false;
var globalTabStripHCCWidth = 1000;
var globalAppUrl = "";
var globalTabIDPrefix = '';
var globalTabManuallyClose = true;
var globalTabManualSelect = '';

var counter = 0;
function LoadTabContentForPageLoad()
{
  if (globalLoadTabOnPageLoad == true && globalVisibleTab != null)
  {
    var lhTabContainer = globalTabIDPrefix;
    var tab = document.getElementById(lhTabContainer);
    if (tab == null || !window.objectiveID) {
    	if (globalVisibleTab.indexOf("genes") == -1) {
    		if (globalVisibleTab.indexOf("myprofile") == -1) {
    			if (globalVisibleTab.indexOf("user") == -1) {
    				globalVisibleTab = "web";
    			}
    		}
    	}
    }

    if (globalVisibleTab != null && globalVisibleTab != '') 
		{
			if (globalVisibleTab == "myprofile" || globalVisibleTab == "genes" || globalVisibleTab == "web" || globalVisibleTab == "communities") {
				ChangeTab(globalVisibleTab);
				globalApplicationsPaneOpen = true;
			}
    }
    else
      globalVisibleTab = null;

  }
}

var loadTextOnInitCount = 0;
function LoadMoreTextTabPageLoadOnInit()
{
  if ((!window.objectiveID || objectiveID == null) && loadTextOnInitCount < 30)
  {
    loadTextOnInitCount++; // prevent a infinite loop
    window.setTimeout('LoadMoreTextTabPageLoadOnInit()', 1000);
  } else
  {
    LoadMoreTextTabPageLoad(false);
  }
}

function LoadMoreTextTabPageLoad(_loadContent)
{
  OpenApplicationPaneToTab('h', 'moretext', 'Text', _loadContent);
	//LHNav_ChangeTab('moretext', 'Text', '');
}

function LoadGenesSearchTabPageLoad() {

	OpenApplicationPaneToTab('h', 'genes', 'Genes Search');
	LHNav_ChangeTab('genes', 'Genes Search', '');
}

function LoadWebSearchTabPageLoad() {
	OpenApplicationPaneToTab('h', 'web', 'Web Search');
	LHNav_ChangeTab('web', 'Web', '');
}

function ChangeAppTabFromMapView(_tabID, _tabName, _url, _full)
{
//	document.getElementById("BottomPaneExpanderOptionBox").className = "BottomPaneExpandOptionBoxHide";
	// Hide Map View Strip Control & expand splitter
	HideTabWidget();
	if (_full == 'true')
	{
	  globalSplitterSetting = 'single';
//////	  DoExpandMapViewPane('applications');
//	  ShowSplitterArrowDown();
	  
	}
	else
	{
//////	  DoExpandMapViewPane("split");
	  globalSplitterSetting = "split";
//	  ShowSplitterArrowDown();
	}
	
	// Run Change Tab Code
	ChangeAppTab(_tabID, _tabName, _url);
}

function ChangeTabFromMapView(_tabID, _tabName, _full, _checkExistingTab)
{
  if (_checkExistingTab != null && _checkExistingTab == true)
  {
    // open previous open tab unless it's profile
    if (globalVisibleTab != null && globalVisibleTab.indexOf('myprofile') == -1)
    {
      _tabID = globalVisibleTab;
      _tabName = ''; // this input param isnot been used anymore

    }
  }

//	document.getElementById("BottomPaneExpanderOptionBox").className = "BottomPaneExpandOptionBoxHide";
	// Hide Map View Strip Control & expand splitter
	HideTabWidget();
	if (_full == 'true')
	{
	  globalSplitterSetting = 'single';
//////	  DoExpandMapViewPane('applications');
//	  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
//////  DoExpandMapViewPane('map');

  globalTabManuallyClose = true;
}

function ShowTabWidget()
{
//  document.getElementById("BottomPaneExpanderOptionBox").className = "BottomPaneExpandOptionBoxShow";
  // deselect left hand option links
  LHNav_UpdateTabUI('');
  LHNav_UpdateChangeTabHandler(true);
}

function HideTabWidget()
{
//  document.getElementById("BottomPaneExpanderOptionBox").className = "BottomPaneExpandOptionBoxHide";
  LHNav_UpdateChangeTabHandler(false);
}

function ChangeAppTab(_tabID, _tabName, _url, _loadContent)
{
	// Grab the Tab & Tabstrip Elements
	//var TabID = "TSC_" + _tabID;
	//var Tab = document.getElementById(TabID);
	
	//if ( Tab == null || Tab == undefined )
	  //return;

	if (_url != null) globalAppUrl = _url

	//var TabStrip = Tab.parentNode;

	//var currentContainerID = "TCC_" + _tabID;
	var currentContainerID = "TCC_app";
	var currentContainer = document.getElementById(currentContainerID);
	
	// Deselect Current Tab & Select new one
	UpdateTabUI(null, null, false, _tabID);
	// Show/Hide toolstrip
	ChangeTabToolStrip(_tabID);
	
	// Set the global js variable
	globalPreviousTab = globalVisibleTab;
	globalVisibleTab = _tabID;
	
	// Perform Splitter Manipulation
	AdjustSplitterOnTabChange();

	if (_tabID == '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);
    }
    }
}

function ShowCorrectHomePageDiv(_tabID) {
	if (!_tabID)
		_tabID = '';	// set this to the default

	if ((_tabID == "myprofile") && !globalDrawInitial) {
		// We want to do something else here
		$('#CategoriesControl').css('display', 'none');
		$('#myprofile').css('display', 'none');
		$('#communities').css('display', 'block');
		$('#MySplitter').css('display', 'none');
		globalVisibleTab = _tabID;
		//		return;
	}
	else if (_tabID == "genes" && globalLoadCategories == true) {

		$('#CategoriesControl').css('display', 'block');
		$('#myprofile').css('display', 'none');
		$('#MySplitter').css('display', 'none');
		$('#communities').css('display', 'none');
		globalLoadCategories = false;
	}
	else if (_tabID == "communities") {
		$('#CategoriesControl').css('display', 'none');
		$('#myprofile').css('display', 'none');
		$('#MySplitter').css('display', 'block');
		$('#communities').css('display', 'none');
	}
	else {
		$('#CategoriesControl').css('display', 'none');
		$('#myprofile').css('display', 'none');
		$('#MySplitter').css('display', 'block');
		$('#communities').css('display', 'none');
//		_tabID == "genes"
	}

	globalVisibleTab = _tabID;
}

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;

	ShowCorrectHomePageDiv(_tabID);


	var currentContainerID = "TCC_" + _tabID;
	var currentContainer = document.getElementById(currentContainerID);
	if (currentContainer == null) currentContainer = document.getElementById("TCC_app");

	// Deselect Current Tab & Select new one
	UpdateTabUI(null, null, false, _tabID);
	// Show/Hide toolstrip
	ChangeTabToolStrip(_tabID);
	
	// Set the global js variable
	globalPreviousTab = globalVisibleTab;
	if (globalPreviousTab == '')
		globalPreviousTab = globalVisibleTab;
	globalVisibleTab = _tabID;
	
	// Perform Splitter Manipulation
//	AdjustSplitterOnTabChange();

	if (_tabID == '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) && !globalDrawInitial)
	 	 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("communities") == -1 )
  {
//  	var communitiesOptionsDiv = document.getElementById("LeftHandSortableNavigationControl_AppOption_AppOptionsNavigationControl_OptionDiv");
//    var communitiesOptionsDiv = document.getElementById(appOptionsNavControlPrefix + "AppOptionsNavigationControl_OptionDiv");
//  	
//    if ( communitiesOptionsDiv != null )
//    {
//      communitiesOptionsDiv.style.display = "none";
//    }   
  }
	else 
	{
		SetSessionProperty('CurrentlySelectedTab', "communities");
	}
    
  
}

// Just update the selected tab UI of the TabStrip
function UpdateTabUI(_tabStrip, _tab, _LeftPaneTabs, _tabID) {
  //debugger;
  // Update LeftHande Nav Option Tabs
//  if (_LeftPaneTabs != true && _tabID != null)
//    LHNav_UpdateTabUI(_tabID);

  if (_tabStrip != null && _tab != null)
  {
    // 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");
		}
	}
}

function GetTabNameFromID(_tabID)
{
  var tabName = '';

  if (_tabID)
  {
    switch (_tabID)
    {
      case "web":
        tabName = "Web";
        break;
      case "genes":
        tabName = "Genes";
        break;
      case "communities":
        tabName = "Discussion";
        break;
      case "moretext":
          tabName = "Text";
        break
    }
  }
  return tabName;

}

// 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); 
  if (IsPortletContentOpen('MyHK'))
    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;
		case "whymostobjective":
			break;
		//case "rasci":
		default:
		    // new to refresh rasci app
		    KGApplicationTabControl_CallbackTrigger();
			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.indexOf("myprofile") != -1) || (globalVisibleTab.indexOf("communities") != -1 && globalHideTabs) || (globalVisibleTab.indexOf("genes") != -1 && globalHideTabs) || (globalVisibleTab.indexOf("web") != -1 && globalHideTabs))
  {

    globalHideTabs = false;
  }
  
	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)
{
  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
    {
      if (toolStrip.childNodes[tidx] != null && toolStrip.childNodes[tidx].style)
        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);

      ShowToolStrip(toolStrip, m_toolStripUCIDPrefix + 'KGToolStrip_SearchDiv');
      break;
    case 'web':
      SetTooStripSearchButton(_tabID);
      ShowToolStrip(toolStrip, m_toolStripUCIDPrefix + 'KGToolStrip_SearchDiv');
      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'); // 15 for show full document
      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;
			*/
		case 'myprofile':
			break;
    default:
      // show the categories control
      ShowCategories(globalTabStripHCCWidth, false);
      // hide tool strip
      toolStrip.style.display = 'none';
      toolStrip.style.height = '0px';
      if (toolstrip.parentNode != null)
        toolstrip.parentNode.style.height = '0px';
      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, _height)
{
 // show tools
 if(_toolDivId != null)
 {
   var toolDiv = document.getElementById(_toolDivId);
   /*if (_toolDivId.indexOf('_TextDiv') != null) // only allow to show tools for more text tab 
   {
     if (toolDiv != null)
       toolDiv.style.display = 'block';
   }*/
 }
 // show strip
 if (_toolStrip.parentNode)
 {
   if (_height != null)
   {
     _toolStrip.parentNode.style.height = _height + 'px'; // quick change before release to allow more text tab to see full doc
     _toolStrip.parentNode.style.display = 'block';
     _toolStrip.style.height = '100%';
   }
   else
   {
     _toolStrip.parentNode.style.height = '0px';
     _toolStrip.parentNode.style.display = 'none';
     _toolStrip.style.height = '0px';
   }
 }

  _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 == "whymostobjective")
	{
		currentContainer.className = "whymostobjectivecontainer";
		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;
}




/************* Repopulation ***********************************/
// Waits until any scrolling has finished before repopulating 
function RepopulateTabbedWindow(_action, _knowdeID)
{
//	var PaneC = Splitter1.Panes[1];
	//	if(PaneC.element.style.display != "none")
//	if (globalApplicationsPaneOpen == true)
	//	{
	if ($("#ApplicationPaneContentHolder").css("display") != "none")
		{

		if(globalVisibleTab != null)
		{
			// repopulate open tab only
			switch(globalVisibleTab)
			{
				case "moretext":
					AutoLoadTextViewForKnowde(_action, _knowdeID);
					break;
				case "web":
					WebTabControl_CallbackTrigger();
					break;
				case "genes":
					GenesTabControl_CallbackTrigger();
					break;
				case "communities":
				  KGCommunityTabControl_Activate();
				  // need to also callback on the left hand options for the tabs			  
          //AppOptionsNavigationControl_CallbackTrigger('CurrentSelectedTab=' + globalVisibleTab);   
					break;
				case "myprofile":
					break;
		     default:
		        // new to refresh rasci app		          
		        KGApplicationTabControl_CallbackTrigger();
			    break;		
		//default:
			//break;			        				
			}
		}
  }
}

function KGApplicationTabControl_CallbackDone_Wrapped(_args, _context)
{
  var argsSplit = _args.split('[@|@]');
  var holderId = argsSplit[0];
  var htmlContent = argsSplit[1];
  var holder = document.getElementById(holderId);
  if (!holder)
  {
    return;
  }
  // fill the control
  SetOuterHtml(holder, htmlContent);
}

function KGApplicationTabControl_ProcessCallBackError_Wrapped(_args, _context, _clientId)
{
}
function KGApplicationTabControl_ProcessCallBackError_Wrapped(_args, _context, _clientId)
{
}
function KGApplicationTabControl_CallbackTrigger_Wrapped(_cbref)
{
    var whatId = GetGlobalHighlightedWhatId();
	// 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);
        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);
        kndTxt = nounText;
    }    
 	//var args = "Mode=Genes|SearchPhrase=" + kndTxt + "|IsMapEdit=false";
 	//debugger;
 	var args = "KnowdeID=" + knowdeID;    // CHRIS ADDED THIS LINE
    // get the two chain strings
    if (globalLastMapDirection == 1) args = args + "|expandpath=" + returnHowChainArrayPostbackString("0","0");
    if (globalLastMapDirection == 2) args = args + "|expandpath=" + returnWhyChainArrayPostbackString("0","0");
    //if (globalAppId != null) args = args + "|AppId=" & globalAppId;
    args = args + "|url=" + globalAppUrl;
    // WHICH MEANS THIS LINE CAN COME OUT
    // AND WE CAN GET THE KNOWDEID THROUGH THE AJAX ARGS
    //SetSessionProperty('CurrentKnowdeIDForTab', knowdeID);

	eval(_cbref);
}

// 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)
{
    // 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(_tabID != 'concepts'  && (_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);
  
    if (globalGroupId != null && globalGroupId > -1) {
      if (globalVisibleTab != null)
        var ajaxargs = 'CurrentSelectedTab=' + globalVisibleTab + '|' + 'GroupId=' + globalGroupId;

//      window.setTimeout("AppOptionsNavigationControl_CallbackTrigger('" + ajaxargs + "')", 100);
    }

}

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 && window.Active_KGOwnerKey && 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.HideLink('addToMaps');
	
		//dont forget to enable the popup again.
		globalShowKeepKGPrompt = false;
  }
  else if (window.Active_KGOwnerKey && Active_KGOwnerKey == WM_readCookie('UserID') && Active_KGOwnerKey != '')
  {
		globalShowKeepKGPrompt = false;
  }
  else if (window.Active_KGOwnerKey && Active_KGOwnerKey == '')
  {
    globalShowKeepKGPrompt = true;
  }
  CloseUOSMessageBox();
}


function LeftPaneExpanderOptionBox_CopyKG(_kgId, _controlDivClientID, e)
{
  //debugger;
  EnsureCopyKGMessage(_controlDivClientID);
  PositionUosMessageBox(_controlDivClientID, false, e);

  var args = 'Action=copyKG|kgid=' + _kgId;

  LeftPaneMyKnowledgeControl_CallbackTrigger(args);
}



var globalLeftPaneSelectedTab = "";
var globalShowLeftPaneWhyMostObjectiveWidget = false;
var globalShowLeftPaneConceptWidget = false;
var globalViewingFavourite = false;
function LeftPaneExpanderOptionBox_ToggleVisibility(_mapVisibility, _whyMostobjectiveVisibility, _conceptVisibility, _tabId) {

	// first deselect the selected tab
	if(globalLeftPaneSelectedTab != "" && ((globalLeftPaneSelectedTab != _tabId && _tabId) || _tabId == null))
	{
//		document.getElementById(globalLeftPaneSelectedTab).className = document.getElementById(globalLeftPaneSelectedTab).className.replace("_Selected", "");
		if(_tabId == null)
		  globalLeftPaneSelectedTab = "";
		  SetSessionProperty('globalLeftPaneSelectedTab', '');
	}
	
	if(_tabId && globalLeftPaneSelectedTab != _tabId)
	{
	  globalLeftPaneSelectedTab = _tabId;
	  SetSessionProperty('globalLeftPaneSelectedTab', globalLeftPaneSelectedTab);
//		document.getElementById(globalLeftPaneSelectedTab).className = document.getElementById(globalLeftPaneSelectedTab).className + "_Selected";
	}

//  DisplayLeftPaneMyMapsWidget(_mapVisibility);
//  DisplayLeftPaneWhyMostObjectiveWidget(_whyMostobjectiveVisibility);
//  DisplayLeftPaneConceptWidget(_conceptVisibility);
  
//  var currentLocation = window.location.href.toLowerCase();    
//	if(currentLocation.indexOf("welcome") > 0)
//	{
//		// What List doesnt exist here - yet!
//	}
//	else
//	{
//		PositionWhatListDropDown();  
//	}
  
}

//function PositionWhatListDropDown()
//{ // nga get rid of this
////	try
////	{
////	  var isLeftPaneOpen = IsLeftPanelOpen();
////	  var dropDown = document.getElementById("KGWhatOptionDropDown");
////	  if (dropDown) {
////	    if (isLeftPaneOpen == true) {
////	        dropDown.style.left = 5;
////	    }
////	    else {
////	        dropDown.style.left = 65;
////	    }
////	  }
////	}
////	catch(e)
////	{
////	}

//}


function DisplayLeftPaneMyMapsWidget(_mapVisibility)
{
	document.getElementById("LeftPaneExpanderOptionBox").className = "LeftPaneExpandOptionBox" + _mapVisibility;
  document.getElementById("LeftPaneExpanderArrow").className = "LeftPaneExpandOptionArrow" + _mapVisibility;
  
}

//function DisplayLeftPaneWhyMostObjectiveWidget(_whyMostObjectiveVisibility)
//{
//  // only show the WHAT/WHATIS widget if it is safe to do so
////  if (globalShowLeftPaneWhyMostObjectiveWidget)
////  {
////      document.getElementById("LeftPaneExpanderWhyMostObjectiveOptionBox").className = "LeftPaneExpandWhyMostObjectiveOptionBox" + _whyMostObjectiveVisibility;
////      document.getElementById("LeftPaneExpanderArrowWhyMostObjective").className = "LeftPaneExpandOptionArrow" + _whyMostObjectiveVisibility;
////  }
//}

//function DisplayLeftPaneConceptWidget(_conceptVisibility)
//{
////  if(globalShowLeftPaneConceptWidget && document.getElementById("LeftPaneExpanderConceptOptionBox") != null)
////  {
////	  document.getElementById("LeftPaneExpanderConceptOptionBox").className = "LeftPaneExpandConceptOptionBox" + _conceptVisibility;
////    document.getElementById("LeftPaneExpanderArrowConcept").className = "LeftPaneExpandOptionArrow" + _conceptVisibility;
////  }
//}

function LeftPaneExpanderOptionBox_OpenConcepts()
{
   KGConceptsContainerControl_InitialLoad();
}

function LeftPaneExpanderOptionBox_OpenWhyMostObjectives()
{
//    globalShowLeftPaneWhyMostObjectiveWidget = true;
//    HideOrShowWhyMostObjectiveControlLoadingDiv(false);
//    LeftPaneExpanderOptionBox_Clicked('whymostobjective');
////    LeftPaneExpanderOptionBox_ToggleVisibility('Show', 'Hide', 'Show', 'LeftPaneExpanderWhyMostObjectiveText'); 
//    GetKGWhyMostObjectives();

  }

function LeftPaneExpanderOptionBox_OpenMyMaps()
{
  LeftPaneExpanderOptionBox_Clicked('mykg');
  LeftPaneExpanderOptionBox_ToggleVisibility('Hide', 'Show', 'Show', 'LeftPaneExpanderText');
}


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");
	}
}

function LeftPaneMyKnowledgeControl_EnsureCopyKGMessage(_parentControlDivId)
{
  m_UosMessageBox = document.getElementById("CopyKGMessageBox");
  
  if(m_UosMessageBox == null)
  {
    m_UosMessageBox = document.createElement("div");
    m_UosMessageBox.setAttribute("id", "CopyKGMessageBox");
    m_UosMessageBox.style.display = "none";
    m_UosMessageBox.style.width = "400px"
    m_UosMessageBox.style.height = "120px";
    m_UosMessageBox.style.position = "absolute";
    m_UosMessageBox.style.zIndex = TopZIndex();
    
    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\" />Copying Knowledge Gene....</td></tr></table></div>';
    
    document.body.appendChild(m_UosMessageBox);
  }
  else
  {
    m_UosMessageBox.style.zIndex = TopZIndex(); //Show on top of other items
  }
}

///////////////////////
// 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(appOptionsNavControlPrefix + "AppOptionsNavigationControl_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);      

		// From now on call the community comments control callbacktrigger
    var args = 'Action=' + 'loadcomments';
    args = args + '|KGID=' + Active_KGID;
    KGCommunityCommentsControl_CallbackTrigger(args);

  }
}

function AlertOptionCheckboxClicked()
{
  var checkBox = document.getElementById(appOptionsNavControlPrefix + "AppOptionsNavigationControl_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 && selectedTab != "none" )
  {

    if ( selectedTab.indexOf("communities") != -1)
    {
      var iframeTab = document.getElementById(appOptionsNavControlPrefix + "IframeTab");
      if ( iframeTab != null && iframeTab != undefined )
      {
        if ( iframeTab.style.display == "block" )
        {
          // need to show the community options
          var communitiesOptionsDiv = document.getElementById(appOptionsNavControlPrefix + "AppOptionsNavigationControl_OptionDiv");
          if ( communitiesOptionsDiv != null && communitiesOptionsDiv.style.display != "block")
          {
            communitiesOptionsDiv.style.display = "block";
          }           
        }     
      }    
    }
  }
}

function TabStripControlBottomPane_CallbackTrigger_Wrapped(_args, _cbReference)
{
  CallbackTrigger_Wrapped(_args, _cbReference);
}

function TabStripControlBottomPane_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);
  }

}


/******************* LeftPane Sortable Navigation ****************************************/
var m_LeftPaneSortableNav_Order = '';
var m_LeftPaneSortableNav_Expanded = '';

// JQuery UI Sortable
function  LeftHandSortableNav_Init() {
  //debugger;
  $(".LHNavColumn").sortable({
    cancel: '.SortDisabled',
    cursor: 'move',
    //connectWith: ".LHNavColumn",
    update: function (event, ui)
    {
      //debugger;
      // remember order state 
      m_LeftPaneSortableNav_Order = '';
      //create an array with the new order
      var order = $(".LHNavColumn").sortable('toArray');
      // only store order for home page
      if (order.length >= 4)
      {
        for (var idx = 0; idx < order.length; idx++)
        {
          var ididx = order[idx].lastIndexOf('_');
          var val = order[idx].substr(ididx + 1);

          m_LeftPaneSortableNav_Order += val + '|';
        }
        //alert(m_LeftPaneSortableNav_Order);
        // store to session
        SetSessionProperty('LeftHandSortableNav_Order', m_LeftPaneSortableNav_Order);
      }
    }
  });

  $(".LHNavPortlet").each(
    function () {
      var controlID = $(this).attr('id');
      var ididx = controlID.lastIndexOf('_');
      var val = controlID.substr(ididx + 1);

      if (m_LeftPaneSortableNav_Expanded.indexOf(val + '|') != -1) 
      {
        // expand this item
        $(this).addClass("LHNav-ui-widget LHNav-ui-widget-content ui-helper-clearfix")
			  .find(".LHNavPortlet-header")
				  .addClass("LHNav-ui-widget-header")
				  .prepend("<span class='KGui-icon ui-icon-minusthick'></span>")
				  .end()
			  .find(".LHNavPortlet-content");
        
        // Load the contents
        //LoadLeftPaneContent(val); - load the contents later when there is a map

      } else {
        $(this).addClass("LHNav-ui-widget LHNav-ui-widget-content ui-helper-clearfix")
			  .find(".LHNavPortlet-header")
				  .addClass("LHNav-ui-widget-header")
				  .prepend("<span class='KGui-icon ui-icon-plusthick'></span>")
				  .end()
			  .find(".LHNavPortlet-content").hide();
      }

    });

    $(".LHNavPortlet-header .KGui-icon").click(function ()
    {
      $(this).toggleClass("ui-icon-minusthick").toggleClass("ui-icon-plusthick");
      $(this).parents(".LHNavPortlet:first").find(".LHNavPortlet-content").toggle();

      // remember expand and collapse state
      var parentID = $(this).parents(".LHNavPortlet:first").attr('id');
      var ididx = parentID.lastIndexOf('_');
      var val = parentID.substr(ididx + 1);

      if ($(this).parents(".LHNavPortlet:first").find(".LHNavPortlet-content").css('display') == 'none')
      {
        m_LeftPaneSortableNav_Expanded = m_LeftPaneSortableNav_Expanded.replace(val + '|', '');
      }
      else
      {
        // due to concept tree not compatible with JQuery sortable yet, avoid auto expand it
        if (val.indexOf('Concept') == -1)
        {
          if (m_LeftPaneSortableNav_Expanded.indexOf(val + '|') == -1)
            m_LeftPaneSortableNav_Expanded += val + '|';
        }

        // Load the contents
        LoadLeftPaneContent(val);
      }

      //alert(m_LeftPaneSortableNav_Expanded);
      // store to session 
      SetSessionProperty('LeftHandSortableNav_Expanded', m_LeftPaneSortableNav_Expanded);
    });


    $(".LHNavColumn").disableSelection();

    // Disable tab links by default, enable map is open
    DisableAllLeftPanelTabLinks();

    

}


function OpenLeftPanelInLastState() {
//  $(".LHNavPortlet").each(
//    function () {
//      var controlID = $(this).attr('id');
//      var ididx = controlID.lastIndexOf('_');
//      var val = controlID.substr(ididx + 1);

//      if (m_LeftPaneSortableNav_Expanded.indexOf(val + '|') != -1) {
//        LoadLeftPaneContent(val);
//      } 

//    });

//  LeftPaneExpanderOptionBox_OpenMyMaps();
//  OpenLeftPanel();
// ngatodo
//	document.getElementById("RightPaneStyle").className = "Welcome_RightPaneStyle_LeftOpen";

}


/******************* LeftPane Option Navigation ****************************************/
var m_changeTabExpandBottomPane = true;
var m_LHOptionTabs = new Array("web", "genes", "moretext", "communities");
var m_LHAppTabs = new Array();
var m_LHOptionCtrlID = new Array("SearchOption", "AppOption");

function LHNav_ChangeTab(_tabID, _tabName, _url, _loadContent)
{
  if (Active_KGID)
  {
    SetSessionProperty('globalTabManualSelect', _tabID);
    globalTabManualSelect = _tabID;
    if (_url == null || _url == '')
    {
      if (m_changeTabExpandBottomPane == true)
        ChangeTabFromMapView(_tabID, _tabName);
      else
        ChangeTab(_tabID, _tabName, _loadContent);
    }
    else // applications
    {
      if (m_changeTabExpandBottomPane == true)
        ChangeAppTabFromMapView(_tabID, _tabName, _url);
      else
        ChangeAppTab(_tabID, _tabName, _url);
    }
  }
}

function LHNav_UpdateChangeTabHandler(_expandBottomPane)
{
  m_changeTabExpandBottomPane = _expandBottomPane;
}

function LHNav_UpdateTabUI(_selectedTabID)
{
  // only go into the if block if it's for deselection, or set selection when bottom pane already open
  if (_selectedTabID == null || _selectedTabID == '' || m_changeTabExpandBottomPane == false)
  {
    var allOptionTabs = m_LHOptionTabs.concat(m_LHAppTabs);
    for (var idx = 0; idx < allOptionTabs.length; idx++)
    {
      for (var oidx = 0; oidx < m_LHOptionCtrlID.length; oidx++)
      {
        var link = document.getElementById(globalTabIDPrefix + '_' + m_LHOptionCtrlID[oidx] + '_' + allOptionTabs[idx]);
        if (link != null)
        {
          if (allOptionTabs[idx] == _selectedTabID )
          {

            // set selected style
            if (link.className.indexOf('Selected') == -1)
              link.className = link.className.replace("LinkDiv", "LinkDivSelected");
          }
          else
          {
            // de-select
            link.className = link.className.replace("LinkDivSelected", "LinkDiv");
          }
        }
      }
    }
  }
}

function ExpandableControl_Toggle(_element)
{
  $(_element).find(".ui-icon").toggleClass("ui-icon-uparrow").toggleClass("ui-icon-downarrow");
  $(_element).parents(".LHNav_InfoDiv").find(".LHNav_InfoContent").toggle();
}


function AppOptionsNavigationControl_ProcessCallBackError_Wrapped(_args, _cbReference)
{
  alert("An exception occurred in the  AppOptionsNavigationControl. " + _args);
  //debugger;
}

function AppOptionsNavigationControl_CallbackTrigger_Wrapped(_args, _cbReference)
{
//  debugger;
  CallbackTrigger_Wrapped(_args, _cbReference);
}

function AppOptionsNavigationControl_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);

  // Do we still need to set the outerhtml?
  if (holder != null && holder != undefined) {
    SetOuterHtml(holder, htmlContent);
  }

  // select the correct tab
  if (selectedTab != "none") {
//    ChangeTab(selectedTab.replace('TSC_', ''), '', false);

    if (selectedTab.indexOf("communities") != -1) {
      var iframeTab = document.getElementById(appOptionsNavControlPrefix + "IframeTab");
      if (iframeTab != null && iframeTab != undefined) {
        if (iframeTab.style.display == "block") {
          // need to show the community options
          var communitiesOptionsDiv = document.getElementById(appOptionsNavControlPrefix + "AppOptionsNavigationControl_OptionDiv");
          if (communitiesOptionsDiv != null && communitiesOptionsDiv.style.display != "block") {
            communitiesOptionsDiv.style.display = "block";
          }
        }
      }
    }
  }

}  
  
  


function LoadLeftPaneContent(val)
{
    switch (val)
    {
      case 'UltimateWhys':
        setTimeout("GetKGWhyMostObjectives();", 100);
        break;
      case 'MyHK':
        if (window.LeftPaneMyKnowledgeControl_CallbackTrigger)
          setTimeout("LeftPaneMyKnowledgeControl_CallbackTrigger('Action=repopulate')", 1);
        break;
      case 'Concepts':
        KGConceptsContainerControl_InitialLoad();
        break;
      case 'SearchOptions':
        //Not yet implemented
        break;
      case 'Applications':
        //Not yet implemented
        break;
    } 
 }

 // To show and hide we should call
 // ShowUltimateWhys, HideUltimateWhys
 // ShowMyHK, HideMyHK

 function ShowLeftPanelContent(_contentHolderID) {

   $(".LHNavPortlet").each(
    function () {
      var controlID = $(this).attr('id');
      var ididx = controlID.lastIndexOf('_');
      var val = controlID.substr(ididx + 1);

      if (val == _contentHolderID) {
        $(this).css('display', 'block');
      }

    });

 }


 function HideLeftPanelContent(_contentHolderID) {

   $(".LHNavPortlet").each(
    function () {
      var controlID = $(this).attr('id');
      var ididx = controlID.lastIndexOf('_');
      var val = controlID.substr(ididx + 1);

      if (val == _contentHolderID) {
        $(this).css('display', 'none');
      }

    });
  }


function IsPortletContentOpen(_id) {

  var _isOpen = false;

  $(".LHNavPortlet").each(
    function () {
      var controlID = $(this).attr('id');
      var ididx = controlID.lastIndexOf('_');
      var val = controlID.substr(ididx + 1);

      if (val == _id) {
        if ($(this).find(".LHNavPortlet-content").css('display') == 'block')
          _isOpen = true;
      }

    });

    return _isOpen;
  }




function LeftPaneNavigationControlSetStatus(_tabLinkID, _enable)
{

  var link = document.getElementById(_tabLinkID);
  if (_enable == true)
  {
    $('#' + _tabLinkID).attr('disabled', '');
    $('#' + _tabLinkID).attr('title', '');
    $('.LHNav_TextLink').css('color', 'black');
    
  }
  else if (_enable == false)
  {
    $('#' + _tabLinkID).attr('disabled', 'disabled');
    $('#' + _tabLinkID).attr('title', 'Open a Knowledge Gene to enable this functionality');
    $('.LHNav_TextLink').css('color', '#999999');

  }

}


function DisableAllLeftPanelTabLinks()
{
  if (window.LeftPaneNavigationControlSetStatusmoretext)
  {
    LeftPaneNavigationControlSetStatusmoretext(false);
    LeftPaneNavigationControlSetStatusweb(false);
    LeftPaneNavigationControlSetStatuscommunities(false);
    LeftPaneNavigationControlSetStatusgenes(false);
  }

}

function EnableAllLeftPanelTabLinks()
{
  if (window.LeftPaneNavigationControlSetStatusmoretext)
  {
    LeftPaneNavigationControlSetStatusmoretext(true);
    LeftPaneNavigationControlSetStatusweb(true);
    LeftPaneNavigationControlSetStatuscommunities(true);
    LeftPaneNavigationControlSetStatusgenes(true);
  }

  }



function OpenKnowledgePaneInLastState() {

	// Update this if we need to remember anything later on
//	LoadInformationPaneContent('KG');
//	LeftPaneMyKnowledgeControl_CallbackTrigger('Action=repopulate');

}


function InformationPaneChangeTab(_tabID, _tabName, _loadContent) {

  // Call-back necessary control
  // we may need to callback tab as they have different modes... new check required.
  if (_tabID != 'concepts' && (_loadContent == null || _loadContent != false))
  	TabContainerControl_CallbackDirection(_tabID);

	// Hack for now?
  var tab = document.getElementById('tabs-3');
  if (tab) {
		if (navigator.userAgent.indexOf('Firefox') != -1  || navigator.userAgent.indexOf('Chrome') != -1)  {
			$(tab).css('height', '94%');
		}
		else 
		{
			$(tab).css('height', '100%');
		}
	}

  LoadApplicationTab();
}



function LoadApplicationTab(_tabID, _tabName) {


	if (!_tabID && globalVisibleTab && globalVisibleTab != '') {

		switch (globalVisibleTab) {
			case "web":
				WebTabControl_CallbackTrigger();
				LHNav_ChangeTab('web', 'Web Search', '');
				break;
			case "genes":
				GenesTabControl_CallbackTrigger();
				LHNav_ChangeTab('genes', 'Genes Search', '');
				break;
			case "moretext":
				LHNav_ChangeTab('moretext', 'Text', '');
				break;
			case "communities":
				LHNav_ChangeTab('communities', 'Discussion', '');
				break;
		}


	}
	else if (!_tabID || _tabID == '') {
		switch (_tabID) {
			case "web":
				WebTabControl_CallbackTrigger();
				LHNav_ChangeTab('web', 'Web Search', '');
				break;
			case "genes":
				GenesTabControl_CallbackTrigger();
				LHNav_ChangeTab('genes', 'Genes Search', '');
				break;
			case "moretext":
				LHNav_ChangeTab('moretext', 'Text', '');
				break;
			case "communities":
				LHNav_ChangeTab('communities', 'Discussion', '');
				break;
		}

	}

}

// TODO: Complete this
function IsTabContentOpen(_id) {

	var isOpen = false;
	return isOpen;
}

