﻿// JScript File
var KGMapToolbar = {
  tooltips : {
    StartEdit : 'Add to this Knowledge Gene',
    StopEdit : 'Finish Adding to this Knowledge Gene',
    ArithConn : 'Use Arithmetic Connectives',
    LogicalConn : 'Use Logic Connectives',
    paste : 'Paste Knowde',
    link : 'Link Copied Knowledge Gene'
  },
  
  ActiveColor : '#00B050',
  
  // clientIDs object populated by control when it renders (see KGMapToolbar.cs RegisterJavascripts).
  // After population this object will contain the clientIds for the links
  // stored agaisnt the link ids (set for each link in the MapToolbar.xml file).
  // e.g. the client ID for a link with id="edit" can be obtained by:
  // this.clientIDs['edit'];
  // this.clientIDs.edit;
  clientIDs : null,
  KGID : null,
  GroupID : null,
  
  EnableLink : function(_id)
  {
    var link = document.getElementById(this.clientIDs[_id]);
    if (link != null)
    {
      // ungrey the link and update 'enabled' Attribute
      link.className = 'MapToolbarLink';
      link.setAttribute('enabled', 'true');
    }
    else
      alert('link ' + _id + ' not found');
  },
  
  DisableLink : function(_id)
  {
    var link = document.getElementById(this.clientIDs[_id]);
    if (link != null)
    {
      // grey the link and update 'enabled' Attribute
      link.className = 'MapToolbarLinkDisabled';
      link.setAttribute('enabled', 'false');
    }
    else
      alert('link ' + _id + ' not found');
  },
  
  HideLink : function(_id)
  {
    var link = document.getElementById(this.clientIDs[_id]);
    if (link != null)
    {
      // hide the link - not using a css class, because don't want to overwrite enabled/disabled
      link.style.display = 'none';
      link.setAttribute('shown', 'false');
    }
    else
      alert('link ' + _id + ' not found');
  },
  
  ShowLink : function(_id)
  {
    var link = document.getElementById(this.clientIDs[_id]);
    if (link != null)
    {
      // show the link - not using a css class, because don't want to overwrite enabled/disabled
      link.style.display = ''; // back to default/css class is better than forcing e.g. block
      link.removeAttribute('shown');
    }
    else
      alert('link ' + _id + ' not found');
  },
  
  IsLinkEnabled : function(_clientID)
  {
    var link = document.getElementById(_clientID);
    if (link.getAttribute('enabled') == "true" && link.getAttribute('shown') != "false")
      return true;
    else
      return false;
  },
  
  EditClick : function(e)
  {
    e = e || window.event;
    if (this.IsLinkEnabled(this.clientIDs.edit))
      SwitchEditableFlag(false, e); 
  },
  
  StartMapEditing : function()
  {  
    var link = document.getElementById(this.clientIDs.edit);
    link.innerHTML = 'Stop Adding';
    this.SetIsClicked('edit', true);
    link.setAttribute('title', this.tooltips.StopEdit);
    
    this.UpdateCopyingLinks();
    this.ShowEditingLinks();
    
    // show the docversion dropdown list
    //if(Map_MultiVersionTextView == 1)
      //m_buttonToolbar_docVersionSelect.Show();
    
    /*if(!PanesAreSplit())
	  {
		  DoExpandMapViewPane("split");
		  DoExpandMapViewPane("split");
		  var splitterArrowDown = document.getElementById('SplitterArrowDown');
		  if(splitterArrowDown != null)
			  splitterArrowDown.className = 'arrowDown';
	  }*/
    
    // show the change objective button if the currently selected knowde is not the objective
    var currentKnowdeID = returnKnowdeID(globalLastSelectedKnowde);
    if(originalCentreKnowdeID != "" && originalCentreKnowdeID != currentKnowdeID)
    {
      // enable change objective button
      KGMapToolbar.EnableLink('changeObj');
      
      if (globalLastMapDirection == HOW_DIRECTION)
      {
        var howChain;
        if (currentMapViewType == MAP_TYPE_LCONNECTOR)
          howChain = globalLastSelectedConnector.parentNode;
        else
          howChain = globalLastSelectedKnowde.parentNode;
        if (howChain.numberOfItems != null && howChain.numberOfItems <= 1)
        {
          if (globalLastSelectedKnowde.getAttribute('CalcType') == "true")
            m_arithmeticConnectorMode = true;
          else
            m_arithmeticConnectorMode = false;
        }
      }
    }    
    if(WM_readCookie('AuthorHelp') != "true")
			setTimeout("ShowTheAuthorHelp()", 1000);        
  },
  
  StopMapEditing : function()
  {
    var link = document.getElementById(this.clientIDs.edit);
    link.innerHTML = 'Add to Map';
    this.SetIsClicked('edit', false);
    link.setAttribute('title', this.tooltips.StartEdit);
    
    this.HideEditingLinks();
    this.UpdateCopyingLinks();
    
    // disable change objective button
    KGMapToolbar.DisableLink('changeObj');
    
    // hide the docversion dropdown list
    //m_buttonToolbar_docVersionSelect.Hide();
  },
  
  ShowDetails : function()
  {
    if (this.IsLinkEnabled(this.clientIDs.details))
      KGDetailsControl_CallbackTrigger(Active_KGID);
  },
  
   KnowdePermission : function()
  {
    if (this.IsLinkEnabled(this.clientIDs.KnowdePermission))
			HideKnowde();
  },
  
  DeleteBtnClick : function()
  {
    if (this.IsLinkEnabled(this.clientIDs.deleteBtn))
    {
      if(m_bEditable == false || Map_TextEditOnly == 1)
        return;
      if (globalLastHighlightedWhat != null) // If a what is selected
        DeleteCurrentWhat();
      else
        DeleteCurrentKnowde();
    }
  },
  
  ResetClick : function()
  {
    if (this.IsLinkEnabled(this.clientIDs.reset))
      ResetMapView();
  },
  
  ChangeObjectiveClick : function()
  {
    if (this.IsLinkEnabled(this.clientIDs.changeObj))
      ChangeMapViewObj();
  },
  
  ConnTypeClick : function()
  {
    if (this.IsLinkEnabled(this.clientIDs.connType))
    {
      SwitchConnectorType();
      FocusMap();
    }
  },
  
  SwitchConnType : function(_arithType)
  {
    var link = document.getElementById(this.clientIDs.connType);
    if (_arithType)
    {
      link.innerHTML = 'Logic';
      link.setAttribute('title', this.tooltips.LogicalConn)
    }
    else
    {
      link.innerHTML = "Arithmetic";
      link.setAttribute('title', this.tooltips.ArithConn)
    }
  },
  
  NewKGClick : function()
  {
    if (this.IsLinkEnabled(this.clientIDs.newKG))
    {
      CreateNewKG();
		  TabScriptControl_CallbackTrigger('CurrentSelectedTab=' + globalVisibleTab);      
      if(WM_readCookie('AuthorHelp') != "true")
				setTimeout("ShowTheAuthorHelp()", 1000);
    }
  },
  
  RefocusClick : function()
  {
    if (this.IsLinkEnabled(this.clientIDs.refocus))
    {
      // we need to check the knowde they are trying to refocus on isnt currently being 'cut'
      if(m_CutCopyData != null)
      {
				if (m_CutCopyData.m_Action == CutCopyAction.Cut && m_CutCopyData.m_KnowdeID == returnKnowdeID(globalLastSelectedKnowde))
				{
					// if it is, then cancel the 'cut'
					cancelCut();
				}
			}
      doSingleClickRefocus(globalLastSelectedKnowde);
    }
  },
  
  CutClick : function()
  {
    if (this.IsLinkEnabled(this.clientIDs.cut))
    {
      CutKnowde();
    }
  },
  
  CopyClick : function()
  {
    if (this.IsLinkEnabled(this.clientIDs.copy))
    {
      CopyKnowde();
    }
  },
  
  UpdateCopyingLinks : function()
  {
    this.ShowLink('copy');
    this.EnableLink('copy');
    
    this.SetIsClicked('cut', false);
    this.SetIsClicked('copy', false);
    
    if (m_CutCopyData != null)
    {
      if (m_CutCopyData.m_Action == CutCopyAction.Copy)
      {
        this.SetIsClicked('copy', true);
        this.SetIsClicked('cut', false);
      }
      else if (m_CutCopyData.m_Action == CutCopyAction.Cut)
      {
        this.SetIsClicked('copy', false);
        this.SetIsClicked('cut', true);
      }
    }
    
    if (m_CopyLinkData != null)
      this.SetIsClicked('copy', true);
    
    if (m_bEditable)
    {
      this.ShowLink('cut');
      this.EnableLink('cut');
      if (m_CutCopyData != null)
      {
        this.ShowLink('paste');
        this.EnableLink('paste');
      }
      else
      {
        this.HideLink('paste');
        this.DisableLink('paste');
      }
      
      if (m_CopyLinkData != null && m_CopyLinkData.KGID != Active_KGID)
      {
        this.ShowLink('linkGene');
        this.EnableLink('linkGene');
      }
      else
      {
        this.HideLink('linkGene');
        this.DisableLink('linkGene');
      }
    }
    else // m_bEditable == false
    {
      this.HideLink('cut');
      this.DisableLink('cut');
      this.HideLink('paste');
      this.DisableLink('paste');
      this.HideLink('linkGene');
      this.DisableLink('linkGene');
    }
  },
  
  ShowEditingLinks : function()
  {
    // show the link - enable or disable might still need changing
    this.ShowLink('details');
    this.ShowLink('deleteBtn');
    this.ShowLink('changeObj');
    this.ShowLink('connType');
    this.ShowLink('cut');
    this.UpdateCopyingLinks();
  },
  
  HideEditingLinks : function()
  {
    this.HideLink('details');
    this.HideLink('deleteBtn');
    this.HideLink('changeObj');
    this.HideLink('connType');
    this.HideLink('cut');
    this.HideLink('paste');
    this.HideLink('linkGene');
  },
  
  SetIsClicked : function(_id, isClicked)
  {
    var link = document.getElementById(this.clientIDs[_id]);
    if (link != null)
    {
      if (isClicked)
        link.style.color = this.ActiveColor;
      else
        link.style.color = '';
    }
    else
      alert('link ' + _id + ' not found');
  },
  
  PasteClick : function()
  {
    if (this.IsLinkEnabled(this.clientIDs.paste))
    {
      PasteKnowde();
    }
  },
  
  LinkGeneClick : function()
  {
    if (this.IsLinkEnabled(this.clientIDs.linkGene))
    {
      LinkGene();
    }
  },
  
  ShareClick : function()
  {
    if (this.IsLinkEnabled(this.clientIDs.share))
    {
      // TODO
      KGButtonToolbar_ShowShare();
    }
  },
  
  SetKGPublishData : function(_kgid, _groupID)
  {
    this.KGID = _kgid;
    this.GroupID = _groupID;
  },
  
  PublishClick : function(e)
  {
    if (this.IsLinkEnabled(this.clientIDs.publish))
    {
			if (!e) 
			{
        e = window.event? event : e;
			}

      KGPublishOptionControl_CallbackTrigger('gen_menu', this.KGID, -1, this.GroupID ,null,null,0,null,e);
    }
  },
  
  PrintClick : function(e)
  {
    if (this.IsLinkEnabled(this.clientIDs.print))
    {
      KGButtonToolbar_ShowPDFExporter();
    }
  },
  
  AddToMapsClick : function()
  {
		//alert('AddToMapsClick');
  	if (this.IsLinkEnabled(this.clientIDs.addToMaps))
    {
			if (!isAuthenticated())
			{
			  //lets make a note the user wants to save this KG.
			  KeepKGPopupControl_Submit('save2', 'KeepKGPopupControl_CallbackTrigger');
			  // show the sign-in/register prompt
				SetSessionProperty('ReturnURL', window.location.href);
				ToggleLoginControl(SrmControl_SetInitial('ViewLoginBox'));
				UpdateKGSignInControlPos('absolute', event.x<450?0:event.x-450, event.y+10);
				return false;
			}
			else
			{
				this.DisableLink('addToMaps');
				LeftPaneMyKnowledgeControl_CallbackTrigger('Action=sub|kgid=' + Active_KGID);
				TabScriptControl_CallbackTrigger('CurrentSelectedTab=' + globalVisibleTab);
				globalShowKeepKGPrompt = false;
			}
		}
  },
  
  ViewAuthorClick : function()
  {
		//alert('ViewAuthorClick: ' + Active_KGOwnerKey);
		if (this.IsLinkEnabled(this.clientIDs.viewAuthor))
    {
			window.location='home.aspx?user=' + Active_KGOwnerKey;
		}
  },
  
  HideToolbar : function()
  {
    var KGMapToolbarContainer = document.getElementById("KGMapToolbar1_container");
    if(KGMapToolbarContainer != null)
				KGMapToolbarContainer.style.display = "none";
  },
  
  ShowToolbar : function()
  {
    var KGMapToolbarContainer = document.getElementById("KGMapToolbar1_container");
    if(KGMapToolbarContainer != null)
				KGMapToolbarContainer.style.display = "block";
  }
};

var globalShareType;
var globalShareDelay;

function KGButtonToolbar_ShowShare()
{
	var ShareBox = document.getElementById("KGButtonToolbar_ShareBox");
	if(ShareBox != null)
	{
		ShareBox.style.display = "block";
	}
}

function KGButtonToolbar_ShowShareOptions(_num, _id)
{
	clearTimeout(globalShareDelay);
	var highlightElement = document.getElementById(_id);
	if(highlightElement != null)
		highlightElement.style.backgroundColor = "#efefef";
	
	var ShareBox = document.getElementById("KGButtonToolbar_ShareBox");
	var ShareBoxOptions = document.getElementById("KGButtonToolbar_ShareBoxOptions");
	if(ShareBoxOptions != null)
	{
		ShareBox.style.display = "block";
		if(_num != 0)
		{
		  if (globalShareMessageFromUniqueActive == true && _num > 75 )
		  {
				var ShareLinks = document.getElementById("shareLinks");
				var ShareLinksMsg = document.getElementById("shareLinksMessage");
				var ShareLinksFromUniqueMsg = document.getElementById("shareLinksFromUniqueMessage");
				
				ShareLinks.style.display = "none";
				ShareLinksMsg.style.display = "none";
				ShareLinksFromUniqueMsg.style.display = "block";
		  
		  }
			else if(globalShareMessageActive == true && _num > 75)
			{
				var ShareLinks = document.getElementById("shareLinks");
				var ShareLinksMsg = document.getElementById("shareLinksMessage");
				var ShareLinksFromUniqueMsg = document.getElementById("shareLinksFromUniqueMessage");
				
				ShareLinks.style.display = "none";
				ShareLinksMsg.style.display = "block";
				ShareLinksFromUniqueMsg.style.display = "none";

			}
			else
			{
				var ShareLinks = document.getElementById("shareLinks");
				var ShareLinksMsg = document.getElementById("shareLinksMessage");
				var ShareLinksFromUniqueMsg = document.getElementById("shareLinksFromUniqueMessage");
				
				ShareLinks.style.display = "block";
				ShareLinksMsg.style.display = "none";
				ShareLinksFromUniqueMsg.style.display = "none";
			}
		}
		ShareBoxOptions.style.display = "block";
		if(_num != 0)
		{
			ShareBoxOptions.style.top = _num;
			if(_num < 75)
			{
				globalShareType = "site";
			}
			else
			{
				globalShareType = "kg";
			}
		}
	}
}

function KGButtonToolbar_HideShareOptions(_id)
{
	var highlightElement = document.getElementById(_id);
	if(highlightElement != null)
		highlightElement.style.backgroundColor = "white";
	clearTimeout(globalShareDelay);
	globalShareDelay = setTimeout("KGButtonToolbar_HideShareOptionsAfterDelay()", 500);
}

function KGButtonToolbar_HideShareOptionsAfterDelay()
{
	var ShareBox = document.getElementById("KGButtonToolbar_ShareBox");
	var ShareBoxOptions = document.getElementById("KGButtonToolbar_ShareBoxOptions");
	if(ShareBoxOptions != null)
	{
		ShareBox.style.display = "none";
		ShareBoxOptions.style.display = "none";
	}
}

function KGButtonToolbar_ShareOptionClick(_type)
{
	KGButtonToolbar_HideShareOptions();
	try
	{	
		var bkmkUrl;
		switch(_type)
		{
			case "onSiteRefer":
				var referUrl = 'Referral.aspx';
				if(globalShareType == "kg")
					referUrl += '?action=MapReferral&kgid=' + Active_KGID + '&groupid=' + GroupID;
				window.location = referUrl;
				return;
			case "delicious":
				bkmkUrl = "http://del.icio.us/post?url=";
				break;
			case "digg":
				bkmkUrl = "http://digg.com/submit?url=";
				break;
			case "reddit":
				bkmkUrl = "http://reddit.com/submit?url=";
				break;
			case "facebook":
				bkmkUrl = "http://www.facebook.com/sharer.php?u=";
				break;
			case "stumble":
				bkmkUrl = "http://www.stumbleupon.com/submit?url=";
				break;
		}

		var hkUrl = window.location.href;
		hkUrl = hkUrl.substring(0, hkUrl.lastIndexOf('/') + 1); //remove the current page and any query string
		var hkTitle = 'Knowledge Genes';
		if(globalShareType == "kg")
			hkUrl += 'home.aspx?kgid=' + Active_KGID;
		hkTitle += ' - ' + Active_KGName + ' - ' + Active_KGOwner;
		var builtUrl = bkmkUrl + encodeURIComponent(hkUrl) + '&title=' + encodeURIComponent(hkTitle);
		window.open(builtUrl);
	}
	catch(e)
	{
	}
}

function KGButtonToolbar_ShowPDFExporter()
{
	var PDFBox = document.getElementById("KGButtonToolbar_PDFExporter");
	if(PDFBox != null)
	{
		PDFBox.style.display = "block";
	}
}

function KGButtonToolbar_HidePDFExporter()
{
	var PDFBox = document.getElementById("KGButtonToolbar_PDFExporter");
	if(PDFBox != null)
	{
		PDFBox.style.display = "none";
	}
}

function ShowPDFMessage()
{
	// The message is created in the ShareLinks.ascx
	var message = document.getElementById("CreatingPdfMessage");
	if (message != null)
	{
		KGButtonToolbar_HidePDFExporter();
		message.style.display = "block";
	}
}

function HidePDFMessage()
{
	if(document.getElementById("PDFButtonOptions") != null)
		document.getElementById("PDFButtonOptions").style.display = "none";
		if(document.getElementById("PDFWaiting") != null)
		document.getElementById("PDFWaiting").style.display = "block";
  var message = document.getElementById("CreatingPdfMessage");
  if (message != null)
  {
    message.style.display = "none";
  }
}

function LoadPDFControl_CallbackTrigger_Wrapped(cbreference, _doctype)
{
	try
	{
		// Put out the Loading message
		ShowPDFMessage();
		
		// build the args string to handle in the C# ProcessAJAXCallback function
		var args = 'KGID='+Active_KGID+'|DocType='+_doctype;
		
		eval(cbreference);
		
		// Can't call this in callbackdone as IE says the aspx call is too delayed (so it blocks the download).
		//PDFExporterControl_Handler();
	}
	catch(e)
	{
		alert(e);
	}
}

function LoadPDFControl_CallbackDone_Wrapped(_args)
{
	if(document.getElementById("PDFWaiting") != null)
		document.getElementById("PDFWaiting").style.display = "none";
	if(document.getElementById("PDFButtonOptions") != null)
		document.getElementById("PDFButtonOptions").style.display = "block";
}

function LoadPDFControl_ProcessCallBackError_Wrapped(_args, _context, _clientID)
{
	HidePDFMessage();
	alert("Sorry, your PDF failed to load (LoadPDFControl CoreControls)");
}

function PDFExporterControl_Handler()
{
	HidePDFMessage();
  // Create an iFrame to prepare the way to generate and download the PDF file
  var iframe = document.createElement("iframe");
  iframe.src = "GenerateFile.aspx?load=pdf"
  iframe.id = "PDFiFrame";
  // Set the display mode to none so the iFrame will be hidden
  iframe.style.display = "block";
  
  // When the iframe is added to the document DOM, it will trigger the whole process
  // automatically, just like calling the cbReference
  document.body.appendChild(iframe);
}

var m_count = 0;
function PDFExporterControlOpen_Handler()
{
	var thePopup = window.open('','PDFFile'+ m_count,'toolbar=no,location=no,directories=no,status=yes, menubar=no,scrollbars=no,resizable=yes,width=600,height=350,top=180,left=100');
  m_count = m_count + 1;
  
  thePopup.document.location = "GenerateFile.aspx";
  
  setTimeout("HidePDFMessage();",1);
}