﻿// 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 && globalLeftPaneOpen && IsLeftTabShown("whats"))
  {
    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("LTSC_KGWhatWhatIsTabCtrl_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("LTSC_KGWhatWhatIsTabCtrl_addMyOwn");
	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("LTSC_KGWhatWhatIsTabCtrl_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.innerText = "Add WHATs";
	}
	else if(_direction == WHATIS_DIRECTION)
	{
		_link.innerText = "Add WHAT-IS";
	}
	else
	{
		if(CurrentlyShowingWhats)
		{
			_link.innerText = "Add WHATs";
		}
		else if(CurrentlyShowingWhatIss)
		{
			_link.innerText = "Add WHAT-IS";
		}
	}
}

function IsActivateAddWhatsLinkActivated()
{
	if(document.getElementById("LTSC_KGWhatWhatIsTabCtrl_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 what = CreateNewWhat();
  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 whatis = CreateNewWhatIs();
  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);
}

