﻿// JScript File
var m_addMyOwnWhat = '';

function InitialiseWhatList(_direction)
{
  if (_direction == WHAT_DIRECTION)
  {
    AttachWhatListToKnowde();
    CurrentlyShowingWhats = true;
    CurrentlyShowingWhatIss = false;
  }
  else if (_direction == WHATIS_DIRECTION)
  {
    AttachWhatIsListToKnowde();
    CurrentlyShowingWhatIss = true;
    CurrentlyShowingWhats = false;
  }
  // if editing map, start editing what list
  var editable = false;
  if((m_bEditable == true && Map_TextEditOnly == 0))
    editable = true;

	var myGene = true;
  if(AllowWhatEditOnly == 1)
  {
		editable = true;
		myGene = false;
	}

  SwitchWhatListControlMode(editable, _direction, myGene);
  
  
  if (navigator.userAgent.indexOf('Safari') > -1 || navigator.userAgent.indexOf('Opera') > -1)
  {
    // in Safari, the Whats div won't accept the focus so it won't get the keydown event.
    // so I've added a tinyInput element that can take the focus (in FocusWhatPanel() method)
    // and fire the whatListKeyPress event as usual
    // the target element will be wrong, but it isn't used unless it's a text box
    // if it's the text box then the Whats will still get the event as usual (as long as it isn't a div)
    // JPC: Use it in Opera as well, otherwise every time the mapview receives focus the text is highlighted (bug 4678)
    var tinyInput = SetTinyInput('tinyInputWhat');
    tinyInput.onkeydown = whatListKeyPress;
  }
  
  // no highlighted whats, so rest the global var
  globalLastHighlightedWhat = null;
}

function AttachWhatListToKnowde()
{
  var knowdeDiv = CurrentWhatRootKnowde;
  if(!knowdeDiv)
		knowdeDiv = globalLastSelectedKnowde;
  var whatDivID = Active_KGID + KGIDPrefixSeperator + "WhatsOf" + returnKnowdeID(knowdeDiv);
  var whatsDiv = document.getElementById(whatDivID); 
  
  AddWhatIndicatorToKnowde(knowdeDiv);

  if (whatsDiv != null)
  {
    // set the whatDivID on the parentKnowdeDiv
    knowdeDiv.setAttribute('whatDivID', whatDivID); 
    // attach whatsDiv to knowde
    knowdeDiv.whatDiv = whatsDiv;
    whatsDiv.parentKnowdeDiv = knowdeDiv;
    CurrentlyShowingWhats = true;
  }
  else
    CurrentlyShowingWhats = false;
}

function AttachWhatIsListToKnowde()
{
  var knowdeDiv = CurrentWhatRootKnowde;
  if(!knowdeDiv)
		knowdeDiv = globalLastSelectedKnowde;
  var whatIsDivID = Active_KGID + KGIDPrefixSeperator + "WhatIsOf" + returnKnowdeID(knowdeDiv);
  var whatIsDiv = document.getElementById(whatIsDivID); 
  
  // add the what is indicator to the Knowde
  AddWhatIsIndicatorToKnowde(knowdeDiv);
  
  if (whatIsDiv != null)
  {
    // set the whatIsDivID on the parentKnowdeDiv
    knowdeDiv.setAttribute('whatIsDivID', whatIsDivID);
    // attach whatIsDiv to knowde
    knowdeDiv.whatIsDiv = whatIsDiv;
    whatIsDiv.parentKnowdeDiv = knowdeDiv;
    CurrentlyShowingWhatIss = true;
  }
  else
    CurrentlyShowingWhatIss = false;
}

var globalLinkClicked = false;
function SwitchWhatListControlMode(_editMode, _direction, _myGene)
{
  // check if whatlist is open
  if (_editMode && globalWhatOpen == true)
  {
    if (globalLastSelectedKnowde.getAttribute("isInheritLinkedMethod") == "true")
      ActivateAddWhatsLink(false, _direction);
    else
		  ActivateAddWhatsLink(true, _direction);
    if (_direction == WHAT_DIRECTION && CurrentlyShowingWhats)
    {
			if(globalLinkClicked)
			{
				globalLinkClicked = false;
				InsertNewWhat();
				ActivateAddWhatsLink(false);
				ActivateAddMyOwnLink(false);
			}
    }
    else if (_direction == WHATIS_DIRECTION && CurrentlyShowingWhatIss)
    {
			if(globalLinkClicked)
			{
				globalLinkClicked = false;
				InsertNewWhatIs();   
				ActivateAddWhatsLink(false); 
				ActivateAddMyOwnLink(false);  
			}
    }
    if(_myGene != null || _myGene != "undefined")
    {
			if(!_myGene && _direction == WHAT_DIRECTION)
			{
				ActivateAddMyOwnLink(true);
			}
    }
  }
}

function addMyOwnClick()
{
	if(IsActivateAddMyOwnLinkActivated())
	{
		ActivateAddMyOwnLink(false);
		globalLinkClicked = true;
		WhatWhatIsTabControl_Edit();
	}
}

function IsActivateAddMyOwnLinkActivated()
{
    if (document.getElementById("KGWhatControl1_KGWhatWhatIsControl_addMyOwn").className == "enabledLink")
		return true;
	else
		return false;
}

function WhatTextBoxHidden()
{
	var textBox = document.getElementById("MapViewTextBoxBottomWhat");
	if(textBox != null)
	{
		if(textBox.style.display == "none")
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return true;
	}
}

function UpdateAddMyOwnWhatTooltip()
{
    var addOwnWhat = null;
    if(m_addMyOwnWhat != null && m_addMyOwnWhat != '')
      addOwnWhat = document.getElementById(m_addMyOwnWhat);
      
    if(addOwnWhat != null && addOwnWhat.className == "enabledLink")
    {
      if(m_kgInMyHK == 1)
      {
        addOwnWhat.title = 'Click to add your own WHATs.';
      }else
      {
        addOwnWhat.title = 'Click to add your own WHATs. This Knowledge Gene will be added to the My Knowledge Genes section of your Profile.';
      }
    }

}

function ActivateAddMyOwnLink(_activate)
{
    var link = document.getElementById("KGWhatControl1_KGWhatWhatIsControl_addMyOwn");
    if (link)
    {
        if (!m_bEditable && AllowWhatEditOnly == 1)
        {
            if (_activate == true && WhatTextBoxHidden())
            {
                link.className = "enabledLink";
                UpdateAddMyOwnWhatTooltip();
            }
            else
            {
                link.className = "disabledLink";
                link.title = "";
            }
        }
        else
        {
            link.className = "hiddenLink";
            link.title = "";
        }
    }
}

function ActivateAddWhatsLink(_activate, _direction)
{
    var link = document.getElementById("KGWhatControl1_KGWhatWhatIsControl_addWhat");
	if(link != null)
	{
		if(m_bEditable)
		{
			EnsureLinkText(link, true, _direction);
			if(_activate == true && WhatTextBoxHidden())
				link.className = "enabledLink";
			else
				link.className = "disabledLink";
		}
		else
		{
			link.className = "hiddenLink";
		}
	}
}

function EnsureLinkText(_link, _edit, _direction)
{
	//check direction
	if(_direction == WHAT_DIRECTION)
	{
		_link.innerHTML = "Add WHATs";
	}
	else if(_direction == WHATIS_DIRECTION)
	{
		_link.innerHTML = "Add WHAT-IS";
	}
	else
	{
		if(CurrentlyShowingWhats)
		{
			_link.innerHTML = "Add WHATs";
		}
		else if(CurrentlyShowingWhatIss)
		{
			_link.innerHTML = "Add WHAT-IS";
		}
	}
}

function IsActivateAddWhatsLinkActivated()
{
	if(document.getElementById("KGWhatControl1_KGWhatWhatIsControl_addWhat").className == "enabledLink")
		return true;
	else
		return false;
}

function addWhatsClick()
{
	if(IsActivateAddWhatsLinkActivated())
	{
	  if (TestAnonEditLimit())
      return; // no more editing, user needs to register
    
		RemoveBottomWhatEditBox();
		if(CurrentlyShowingWhats)
		{
			try
			{
				InsertNewWhat();
				ActivateAddWhatsLink(false);
			}
			catch(e)
			{
				globalLinkClicked = true;
				WhatWhatIsTabControl_Edit();
				ActivateAddWhatsLink(false);
			}
		}
		else if(CurrentlyShowingWhatIss)
		{
			try
			{
				InsertNewWhatIs();  
				ActivateAddWhatsLink(false); 
			}
			catch(e)
			{
				globalLinkClicked = true;
				WhatWhatIsTabControl_Edit();
				ActivateAddWhatsLink(false);
			}
		}
		else
		{
			globalLinkClicked = true;
			WhatWhatIsTabControl_Edit();
			ActivateAddWhatsLink(false);
		}
	}
}

function addWhatsMouseOver()
{
}

function addMyOwnMouseOver()
{
}

function GetGlobalHighlightedWhatId()
{
  var whatId = '';
  try
  {
	  if( globalLastHighlightedWhat != null )
	  {
	    var hwid = returnKnowdeID(globalLastHighlightedWhat);
	    if(hwid != null && hwid != '')
	      whatId = hwid;
    }
  }
  catch (e)
  {
  }
  
  return whatId;
}

///////////////////////
// Inserts a new what item at the bottom of the what list
function InsertNewWhat(_knowdeDiv, _allowRecursive)
{
  if (TestLinkEdit())
    return;
    
  if (!_allowRecursive && globalLastHighlightedWhat != null && TestRecursion(globalLastHighlightedWhat))
    return;
  
  var knowdeDiv;
  if (_knowdeDiv != null)
    knowdeDiv = _knowdeDiv;
  else
    knowdeDiv = CurrentWhatRootKnowde;

  var parentChainContext = returnParentChainContext(knowdeDiv);
	var what = CreateNewWhat(parentChainContext);
  var WhatPanel = document.getElementById(knowdeDiv.getAttribute('whatDivID')); 
  
  var whatsHolder = QueryWhatsHolder(WhatPanel);
  InsertAdjacentElement(whatsHolder,"beforeEnd", what);
  if(AllowWhatEditOnly == 1)
  {
    what.setAttribute('IsUserKI', 'true'); // allow edit
    what.setAttribute('IsLocked', 'false'); 
  }
  
  WhatPanel.numberOfItems++;
  PlaceBottomWhatIntoEditMode(what);
}

///////////////////////
// Inserts a new whatis item at the bottom of the whatis list
function InsertNewWhatIs(_knowdeDiv, _allowRecursive)
{
  if (TestLinkEdit())
    return;
    
  if (!_allowRecursive && globalLastHighlightedWhat != null && TestRecursion(globalLastHighlightedWhat))
    return;
  
  var knowdeDiv;
  if (_knowdeDiv != null)
    knowdeDiv = _knowdeDiv;
  else
    knowdeDiv = CurrentWhatRootKnowde;

  var parentChainContext = returnParentChainContext(knowdeDiv);
  var whatis = CreateNewWhatIs(parentChainContext);
  var WhatPanel = document.getElementById(knowdeDiv.getAttribute('whatIsDivID')); 
  
  var whatsHolder = QueryWhatsHolder(WhatPanel);
  InsertAdjacentElement(whatsHolder,"beforeEnd", whatis);
  
  WhatPanel.numberOfItems++;
  PlaceBottomWhatIntoEditMode(whatis);
}

////////////////////
// handles the keydown event. All it does is pass control over to the appropriate method for the corrosponding key
function whatListKeyPress(e)
{
  e = e || window.event;
  CancelBubble(e);
  if(e && e.type == "keydown")
  {
    // we need to do different things depending on whether the what lists are open or not
    if(CurrentlyShowingWhats || CurrentlyShowingWhatIss)
    {
      // we also need to sort out where the even came from, if it's the input box then we need
      // to do different things than if it were from a what item
      var targ = e.target || e.srcElement;
      if(targ.tagName == "INPUT" && targ.id != 'tinyInputWhat')
      {
        switch(e.keyCode)
        {
          case 13: // Enter Key
            e.returnValue = false;
            if (e.preventDefault) e.preventDefault();
            var what = targ.parentNode;
            if (what != null)
            {
              if(what.getAttribute('HKDirection') == "what")
                ComitWhatEdit(targ);
              else
                ComitWhatIsEdit(targ);
            }    
            break;
          case 27: // Esc
            if (targ.BottomWhat)
            {
              targ.value = '';
              // get out of add my own mode, activate the necessary what subtitle controls (Add my own etc)
              RemoveBottomWhatEditBox();
              ActivateAddWhatsLink(true);
              ActivateAddMyOwnLink(true);
            }
            else 
              CancelWhatEdit(false);
            break;
        }
      }
      else
      {
        /*switch(e.keyCode)
        {
          case 13: // Enter Key
            RefocusOnHighlightedWhatOrWhatIs();
            break;
          case 37: // Left Arrow
            MoveWhatToPreviousPanel()
            break;       
          case 39: // Right Arrow
						//debugger;
            MoveWhatToNextPanel();
            break;
          case 27: // Esc
          //case 118: // F7
            CloseWhatLists();
            break;
          case 38: // Up Arrow
            MoveUpWhatList();
            break;
          case 40: // Down Arrow
            //MoveDownWhatList();
            break;
        }*/
        if (globalLastHighlightedWhat != null) // If a what is selected
        {
          switch(e.keyCode)
          {
            case 45: // insert key
              if (e.preventDefault) e.preventDefault();
              e.returnValue = false;
              if(m_bEditable == true && Map_TextEditOnly == 0 && !TestAnonEditLimit())
              {
                if(globalLastHighlightedWhat.getAttribute('HKDirection') == "what")
                {
                  //if(e.shiftKey == true)
                    //InsertSubWhat();
                  //else
                    InsertWhat();
                }
                else  // what-is direction
                {
                  //if(e.shiftKey == true)
                    //InsertSubWhatIs();
                  //else
                    InsertWhatIs();
                }
              }
              break;
            case 46: // Delete
              // check whether the knowde is focus on whatIs, for AllowWhatEditOnly, user can only delete what in what direction
              var focusOnWhatIs = 0;
              var whatTextDiv = GetWhatTextDiv(globalLastSelectedKnowde);
              if(whatTextDiv != null && whatTextDiv.getAttribute("Direction") != null && whatTextDiv.getAttribute("Direction").toLowerCase() == 'whatis')
                focusOnWhatIs = 1;
              if((m_bEditable == true && Map_TextEditOnly == 0) || (AllowWhatEditOnly == 1 && focusOnWhatIs == 0 && globalLastHighlightedWhat.getAttribute('IsLocked') != 'true' && globalLastHighlightedWhat.getAttribute('HKDirection') == "what"))
                DeleteCurrentWhat();
              break;
            case 113: // F2
              if(m_bEditable == true && Map_TextEditOnly == 0)
              {
                m_IsEditFromNewWhat = false;
                CopyWhatText();
                PlaceWhatIntoEditMode();
              }
              break;
          }
        }
      }

    }
  }
}

// puts the focus to the What(Is)Panel so the key press event is picked up
// currently only works if there's a globalLastHighlightedWhat, but that's ok because the key press is only required when a what is selected (or in one of the text boxes, which is covered separately)
function FocusWhatPanel()
{
  var tinyInput = document.getElementById('tinyInputWhat');
  if (tinyInput) // for safari because the div won't do the key press
  {
    tinyInput.focus();
  }
  else
  {  
    var whatPanel;
    var what = globalLastHighlightedWhat;// || _what;
    if (what)
    {
      var whatPanel = what.parentNode.parentNode.parentNode;
      if (whatPanel != null)
        whatPanel.focus();   
    }    
  }
}



/********************************** VERY IMPORTANT *****************************************/
/*
The Following code is used to detect when a user navigates away from our site.  A user should not be 
prompted whenever...
1. A link to the same website is clicked
2. Refresh the current page
3. Click mailto anchors
4. Click navigators containing '#' for the same page

Now to avoid these conditions, we need to test the anchors for the pages of the current website and any external links.
So the following code solves all of these problems and prompts the user only when ,

1.They click an external link
2.Closes the current window.

The reason this code appears in the WhatListControl.js is because the IF/FOR loop code MUST appear below all the contents
of the current page.
*/

//window.onbeforeunload = confirmExit;  // maybe move this into the onload function?  
var aClick=false;
//var globalShowPopup = true;

function confirmExit(e)
{

//debugger;
	if(document.all)e = event;

	if(!e)e=window.event;
	
	if (e)
	{
		var posx = 0;
		var posy = 0;
		
		if (e.pageX)
		{
			posx = e.pageX;
		}
		else if (e.clientX)
		{
			posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		}
		
		if (e.pageY)
		{
			posy = e.pageY;
		}
		else if (e.clientY)
		{
			posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
		}

		if(aClick==false && (e.target==document || posx<0 || posy<0) && globalShowKeepKGPrompt == true)//e.clientX<0 || e.clientY<0))
		{
			if(m_bEditable)
				SetSessionProperty("KeepKGControl_CallbackMode", "create");
			else
				SetSessionProperty("KeepKGControl_CallbackMode", "leave");
		  var args = "ACTION=repopulate|REDIRECT=|GENESTABCLICK=false";        
			eval("KeepKGPopupControl_CallbackTrigger('" + args + "')");
			
			// in Firefox and Netscape 7.2+ the setTimeout or setInterval do not wait 
			// to be executed until after the user clicks one of the buttons in the 
			// confirm()-like box.

			//setTimeout("alert('hi from setTimeout()');",500);
			// setTimeout() and setInterval() aren't called when ok is clicked in 
			// IE5-6/Win, but is called in IE7 when the time is short, but not when 
			// it's longer, like 500 (a half second).
			window.unloadTimer = setInterval(
				"SetShowKeepKGPromptStyle();clearInterval(window.unloadTimer);",500);
			window.onunload = function() {clearInterval(window.unloadTimer);}

			return "You are about to leave Knowledge Genes.  If you would like to keep the Knowledge Gene you are viewing then please click Cancel to stay on our site.";
		}
	}
} 

function setAClick()
{
	aClick=true;    
}


function cancelAClick()
{
	aClick=false;
}

var aList=document.getElementsByTagName("a");
//debugger;
if(aList && aList.length>0)
{
	for(i=0;i < aList.length;i++)
	{
		var a=aList[i];

		if(checkForLocal(a.href))
		{
			a.onclick=setAClick;
		}
		else
		{
			a.onclick=cancelAClick;
		}
	}
}

function checkForLocal(src)
{
	return (src.indexOf("KnowledgeGenes")!=-1 ||
	src.indexOf("KnowledgeGenes")!=-1 || src.indexOf("javascript")!=-1 ||src.indexOf("mailto") !=-1 || src.indexOf("#")==0);
}


var globalWhatOpen = false;
function HideOrShowKGWhatControl(visibility)
{
    if (visibility == true)
    {
        KGWhatControl_OpenWhatWhatIsList();
        ShowKGWhatControl();
        globalWhatOpen = true;
    }
    else
    {
        HideKGWhatControl();
        globalWhatOpen = false;
    }
}


function KGWhatControl_OpenWhats() {

    KGWhatControl_OpenWhatWhatIsList(WHAT_DIRECTION);
    HideOrShowKGWhatControl(true);
    WhatWhatIsTabControl_SwitchDirection(4); 
}

function KGWhatControl_OpenWhatIs() {

    KGWhatControl_OpenWhatWhatIsList(WHATIS_DIRECTION);
    HideOrShowKGWhatControl(true);
    WhatWhatIsTabControl_SwitchDirection(8); 
}

function KGWhatControl_OpenWhatWhatIsList(_direction)
{
    if (!_direction) // default to what direction
    {
        if (globalWhatWhatIsTabDirection)
            _direction = globalWhatWhatIsTabDirection
        else
            _direction = WHAT_DIRECTION;
    }

    CurrentWhatRootKnowde = globalLastSelectedKnowde;
    m_SelectedWhatEditing = false;
    m_IsEditFromNewWhat = false;
    WhatWhatIsTabControl_ReloadForKnowde(CurrentWhatRootKnowde, _direction);
}


/**************** What WhatIs Tab Control *********************/
var globalWhatWhatIsTabKnowdeId;
var globalWhatWhatIsTabDirection = 4; // set this using SetWhatWhatIsTabDirection to toggle the change direction buttons as well - default to what direction
var globalWhatWhatIsTabInheritedKnowde;
var globalWhatWhatIsTabInheritLnkdKnowde;
var globalWhatWhatIsTabParentChainContext;


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);
    var parentChainContext = returnParentChainContext(_knowde);
    WhatWhatIsTabControl_Reload(knowdeID, inheritedKnowde, inheritLnkdKnowde, _direction, parentKnowdeID, thenPriorKnowdeID, knowdeDirection, true, parentChainContext);
}


function WhatWhatIsTabControl_Reload(_knowdeID, _inheritedKnowde, _inheritLnkdKnowde, _direction, _parentKnowdeID, _thenPriorKnowdeID, _knowdeDirection, _focusOnMap, _parentChainContext)
{
    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;

        if (_direction != null)
        {
            args += '|Direction=' + _direction;
        }
        else if ( globalWhatWhatIsTabDirection != null)
        {
            args += '|Direction=' + globalWhatWhatIsTabDirection;
        }
        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';
        if (_parentChainContext != null)
        	args += '|ParentChainContext=' + _parentChainContext;

        WhatWhatIsTabControl_CallbackTrigger(args);
        globalWhatWhatIsTabKnowdeId = _knowdeID;
        globalWhatWhatIsTabInheritedKnowde = _inheritedKnowde;
        globalWhatWhatIsTabInheritLnkdKnowde = _inheritLnkdKnowde;
        globalWhatWhatIsTabParentChainContext = _parentChainContext;
        if (_direction == null)
            SetWhatWhatIsTabDirection(globalWhatWhatIsTabDirection);
        else
            SetWhatWhatIsTabDirection(_direction);
    }
}


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_Edit()
{
    // check whether selected knowde has changed
    var args = 'Action=Edit|KnowdeId=';
    if (globalWhatWhatIsTabKnowdeId)
        args += globalWhatWhatIsTabKnowdeId;
    else
        args += returnKnowdeID(globalLastSelectedKnowde);
    args += '|KGId=' + Active_KGID;
    if (globalWhatWhatIsTabParentChainContext)
    	args += '|ParentChainContext=' + globalWhatWhatIsTabParentChainContext;

    WhatWhatIsTabControl_CallbackTrigger(args);

}

function WhatWhatIsTabControl_SwitchDirection(_direction)
{
    // check whether selected knowde has changed
    if (globalWhatWhatIsTabKnowdeId != null)
    {
        var knowde = globalLastSelectedKnowde;
        var knowdeDirection = GetKnowdeDirection(knowde);
        var parentKnowdeID = knowde.getAttribute('parentKnowdeID');
        var parentChainContext = returnParentChainContext(knowde);

        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;
        if (parentChainContext != null)
        	args += '|ParentChainContext=' + parentChainContext; // do we want to use this or globalWhatWhatIsTabParentChainContext

        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');
        var parentChainContext = returnParentChainContext(CurrentWhatRootKnowde);
        setTimeout('WhatWhatIsTabControl_Reload(' + returnKnowdeID(globalLastSelectedKnowde) + ', ' + inheritedKnowde + ', ' + inheritLnkdKnowde + ', ' + _direction + ', null, null, null, true, "' + parentChainContext + '")', 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("KGWhatControl1_KGWhatWhatIsControl_selectIntoKnowde").className = "enabledLink";
    else
        document.getElementById("KGWhatControl1_KGWhatWhatIsControl_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();
    }
}
