﻿// JScript File
var isMultiVersionTextViewReadOnly = true;

var KGMapToolbar = {
	tooltips: {
		StartEdit: 'Start editing map',
		StopEdit: 'Stop editing map',
		//    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,
	DocVersionCount: 0,

	EnableLink: function (_id) {
		var link = document.getElementById(this.clientIDs[_id]);
		if (link != null) {
			// ungrey the link and update 'enabled' Attribute
			//    	link.className = 'MapToolbarLink'
			$(link).toggleClass('MapToolbarLink', true);
			$(link).toggleClass('MapToolbarLinkDisabled', false);
			link.setAttribute('enabled', 'true');
			$(link).attr('disabled', '');
			link.style.display = 'block';
		}
		else
			alert('link ' + _id + ' not found');
	},

	DisableLink: function (_id) {
		var link = document.getElementById(this.clientIDs[_id]);
		if (link != null) {
			$(link).attr('disabled', 'disabled');
			$(link).attr('disabled', 'true');
			// grey the link and update 'enabled' Attribute
			link.setAttribute('enabled', 'false');
			$(link).toggleClass('MapToolbarLinkDisabled', true);
			$(link).toggleClass('MapToolbarLink', false);
			link.style.display = 'none';

		}
		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) {


			if (_id == 'details') {
				// This is apparently the test for a signed in user so show the link otherwise do nothing and it will not show
				if (Active_UserPublishPermission && globalShareMessageFromUniqueActive == false) {
					link.style.display = ''; // back to default/css class is better than forcing e.g. block
					link.removeAttribute('shown');
				}
			}
			else {
				// 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');
				// Put something in here to check if it's the detail button because i cannot be bothered
			}
		}
		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);
	},

	BackgroundClick: function (e) {
		e = e || window.event;
		ChooseMapBackground(e);
	},

	StartMapEditing: function () {
		if (Map_MultiVersionTextView == 1) {
			isMultiVersionTextViewReadOnly = false;

			if (m_buttonToolbar_docVersionSelect.DocVersionCount > 0 && Map_TextEditOnly == 0) {
				m_buttonToolbar_docVersionSelect.AddDeleteOption();
			}
			if (Map_TextEditOnly == 0 && Active_KGID > 0) {
				m_buttonToolbar_docVersionSelect.AddCreateOption();
			}

			// If not a superuser then we will remove the Default version when they start editing
			if (m_isSuperUser == false) {
				m_buttonToolbar_docVersionSelect.Remove("default");
				m_buttonToolbar_docVersionSelect.Changed(event);
			}
		}


		var link = document.getElementById(this.clientIDs.edit);
		//		link.innerHTML = 'Stop Editing';
		if (globalDisableEditLink != true)
			this.SetIsClicked('edit', true);
		else {
			globalDisableEditLink = false;
		}
		link.setAttribute('title', this.tooltips.StopEdit);

		$(link).toggleClass('MapToolBarEdit', false);
		$(link).toggleClass('MapToolBarEditHover', true);


		this.UpdateCopyingLinks();
		this.ShowEditingLinks();

		$('.logicalConnectorImage').toggleClass('logicalConnectorImageHide', false);

		/*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 = 'Edit Map';
		this.SetIsClicked('edit', false);
		link.setAttribute('title', this.tooltips.StartEdit);

		if (Map_MultiVersionTextView == 1) {
			isMultiVersionTextViewReadOnly = true;
			if (Map_TextEditOnly == 0) {
				m_buttonToolbar_docVersionSelect.Remove("new");
			}

			if (m_buttonToolbar_docVersionSelect.DocVersionCount > 0 && Map_TextEditOnly == 0) {
				m_buttonToolbar_docVersionSelect.Remove("delete");
			}

			if (m_isSuperUser == false)
				m_buttonToolbar_docVersionSelect.AddDefaultOption();

			// Reload and markedited versions
			if (window.event)
				m_buttonToolbar_docVersionSelect.Changed(event);
			m_buttonToolbar_docVersionSelect.Populate(m_KGDocVersionArray);
			m_buttonToolbar_docVersionSelect.MarkEditedVersions(m_KnowdeDocVersionArray);
		}
		
		$(link).toggleClass('MapToolBarEditHover', false);
		$(link).toggleClass('MapToolBarEdit', true);

		this.HideEditingLinks();
		this.UpdateCopyingLinks();

		// disable change objective button
		KGMapToolbar.DisableLink('changeObj');

		$('.logicalConnectorImage').toggleClass('logicalConnectorImageHide', true);

	},

	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)) {
			// Cancel any outstanding cut/copy
			cancelCut();
			cancelCopy();
			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();
			AppOptionsNavigationControl_CallbackTrigger('CurrentSelectedTab=' + globalVisibleTab);

			/*if(WM_readCookie('AuthorHelp') != "true")
			setTimeout("ShowTheAuthorHelp()", 1000);*/
		}
	},

	RefocusClick: function () {
		AuthorStepRefocus();
		if (this.IsLinkEnabled(this.clientIDs.refocus)) {
			doSingleClickRefocus(globalLastSelectedKnowde);
			// Cancel outstanding cut/copy and update links
			cancelCut();
			cancelCopy();
		}
	},

	CutClick: function () {
		if (this.IsLinkEnabled(this.clientIDs.cut)) {
			CutKnowde();
		}
	},

	CopyClick: function () {
		if (this.IsLinkEnabled(this.clientIDs.copy)) {
			CopyKnowde();
		}
	},

	UpdateCopyingLinks: function () {
		this.EnableLink('copy');
		this.ShowLink('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 || m_CutCopyData.m_Action == CutCopyAction.DragCut) {
				this.SetIsClicked('copy', false);
				this.SetIsClicked('cut', true);
			}
		}

		if (m_CopyLinkData != null && Active_KGID != m_CopyLinkData.KGID)
			this.SetIsClicked('copy', true);

		if (m_bEditable) {
			this.EnableLink('cut');
			this.ShowLink('cut');
			if (m_CutCopyData != null || m_CopyLinkData != null) {
				this.EnableLink('paste');
				this.ShowLink('paste');
			}
			else {
				this.HideLink('paste');
				this.DisableLink('paste');
			}

			// Make sure we cannot cut or copyy if we are on the refocussed knowde or objective knowde
			if (globalLastSelectedKnowde.getAttribute('knowdeType') == "centered" || globalLastSelectedKnowde.getAttribute("RefocussedKnowde") == "true") {
				this.DisableLink('cut');
				this.DisableLink('copy');
				this.DisableLink('paste');
			}

			if (m_CopyLinkData != null && m_CopyLinkData.KGID != Active_KGID) {
				this.EnableLink('linkGene');
				this.ShowLink('linkGene');
			}
			else {
				this.DisableLink('linkGene');
				this.HideLink('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 
		this.EnableLink('details');
		this.ShowLink('details');
		this.EnableLink('deleteBtn');
		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();
		}
  },

  PosterClick: function (e) {
    if (this.IsLinkEnabled(this.clientIDs.poster)) {
      KGButtonToolbar_ShowMapPosterOption();     

    }
  },


	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);

				AppOptionsNavigationControl_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 = "kg";
var globalShareDelay;

//function KGButtonToolbar_ShowShare()
//{
//	var ShareBox = document.getElementById("KGButtonToolbar_ShareBox");
//	if(ShareBox != null)
//	{
//		ShareBox.style.display = "block";
//	}
//}

function KGButtonToolbar_ShowShare() {
	var ShareBox = document.getElementById("KGButtonToolbar_ShareBox");
	if (ShareBox != null) {
		var ShareIcon = document.getElementById("KGMapToolbar1_share");
		if (ShareIcon != null) {
			var coords = findPosNoAdjust(ShareIcon);
			ShareBox.style.left = coords[0];
		}
		else {
			ShareBox.style.left = '355px';
		}
		ShareBox.style.top = '140px';
		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";
		    ShareKGLinks.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");


		    if (Active_UserHasEditPermission == true && Active_UserHasEditPermission == true && Active_KGOwnerKey != "" && Active_KGOwnerKey == WM_readCookie('UserID')) // editable KG such as private KG or published KG that user has KG Edit permission
		    {
		      ShareLinks.style.display = "none";
		      ShareKGLinks.style.display = "block";
		      ShareLinksMsg.style.display = "none";
		      ShareLinksFromUniqueMsg.style.display = "none";
		    }
		    else
		    {
		      ShareLinks.style.display = "none";
		      ShareKGLinks.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";
		    ShareKGLinks.style.display = "none";
		    ShareLinksMsg.style.display = "none";
		    ShareLinksFromUniqueMsg.style.display = "none";
		  }
		}
		ShareBoxOptions.style.display = "block";
		if(_num != 0)
		{
//			ShareBoxOptions.style.top = _num;
			if (_num < 75) {
				globalShareType = "site";
				ShareBoxOptions.style.top = '140px';
			}
			else {
				globalShareType = "kg";
				ShareBoxOptions.style.top = '165px';
			}

			var coords = findPosNoAdjust(ShareBox);
			ShareBoxOptions.style.left = coords[0] + 175;

		}
	}
}

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_ShowPDFExporter() {
	var PDFBox = document.getElementById("KGButtonToolbar_PDFExporter");
	if (PDFBox != null) {
		var PDFIcon = document.getElementById("KGMapToolbar1_print");
		if (PDFIcon != null) {
			var coords = findPosNoAdjust(PDFIcon);
			PDFBox.style.left = coords[0];
		}
		else {
			PDFBox.style.left = '380px';
		}
		PDFBox.style.top = '140px';
		PDFBox.style.display = "block";

	}
}

function OpenMapPosterPrint(_mode) {
  var posterUrl = 'mapimagegeneration.aspx?kgid=' + Active_KGID + '&skc=true';
  if(_mode != null)
    posterUrl += '&mode=' + _mode;
  // get secure qs
  var currentLocation = window.location.href;
  var hostURL = "MapImageLoadOnDemand.aspx";//currentLocation;
  var loadURL = hostURL + '?getqs=' + Active_KGID;
  $.get(loadURL,
    function (data)
    {
      if(data != '' && data.indexOf('k') != -1)
      {
        posterUrl += '&' + data;
        
        window.open(PosterViewDomain + posterUrl, 'KGPosterView');
      }
    }
    )
}

function KGButtonToolbar_ShowMapPosterOption() {
  //debugger;
  var boxID = "KGButtonToolbar_MapPosterOptionMessage";
  
  if (PosterViewAccess == true) {
    boxID = "KGButtonToolbar_MapPosterOption";
  }

  var optionBox = document.getElementById(boxID);
  if (optionBox != null) {
    var icon = document.getElementById("KGMapToolbar1_poster");
    if (icon != null) {
      var coords = findPosNoAdjust(icon);
      optionBox.style.left = coords[0];
    }
    else {
      optionBox.style.left = '340px';
    }
    optionBox.style.top = '140px';
    optionBox.style.display = "block";

  }
}


function KGButtonToolbar_HidePDFExporter()
{
	var PDFBox = document.getElementById("KGButtonToolbar_PDFExporter");
	if(PDFBox != null)
	{
		PDFBox.style.display = "none";
	}
}


function KGButtonToolbar_HideMapPosterOption() {
  var boxID = "KGButtonToolbar_MapPosterOptionMessage";

  if (PosterViewAccess == true) {
    boxID = "KGButtonToolbar_MapPosterOption";
  }
  var optionBox = document.getElementById(boxID);
  if (optionBox != null) {
    optionBox.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;
		if (m_buttonToolbar_docVersionSelect.select.options.selectedIndex != null) {
		    if (m_buttonToolbar_docVersionSelect.select.options[m_buttonToolbar_docVersionSelect.select.options.selectedIndex].value == 'default') {
		        args = args + '|DocVersionID=0';
		    }
		    else {
		        args = args + '|DocVersionID=' + m_buttonToolbar_docVersionSelect.select.options[m_buttonToolbar_docVersionSelect.select.options.selectedIndex].value;
		    }
		}
		else {
		    args = args + '|DocVersionID=0';
		}
		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();

    FileExporterControl_Handler("GenerateFile.aspx?load=pdf");
}

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);
}


var m_buttonToolbar_docVersionSelect; //the document version drop down list object
var m_KGDocVersionArray; // stores the document versions for the current KG
var m_KnowdeDocVersionArray; // stores any document versions for the current KGs knowdes
var m_repopulate = "true";
var m_isSuperUser;

// callback trigger
function KGMapToolbarControl_CallbackTrigger_Wrapped(_cbreference, _KGID)
{
    try
    {
        var args = 'KGID='+Active_KGID;		
	    eval(_cbreference);
	}
	catch(e)
	{
	    alert(e);
	}
}



// callback done
function KGMapToolbarControl_CallbackDone_Wrapped(_args, _context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  // if the string "Exception:" occurs or it is zero length then something has gone wrong
  if(_args.length == 0 || _args.indexOf("Exception") >= 0)
  {
    alert("AJAX Failure:\n\n" + _args);
    return;
  }
  
  // First off is to convert our arguments into a proper object. What comes back should be JSON 
  // so we simply evaluate it into an object
  var retMessage = eval( '(' + _args + ')');

    // This must come first
    m_isSuperUser = retMessage.IsSuperUser;
    m_showDefault = retMessage.ShowDefault;
    m_KGDocVersionArray = retMessage.KGDocumentVersions;
    m_KnowdeDocVersionArray = retMessage.KnowdeDocumentVersions;
    if (Map_MultiVersionTextView == 1)
    {
    	// Check to see if we should populate the list without reloading display
    	if (m_repopulate == "true")
    	{
    		m_buttonToolbar_docVersionSelect.Populate(m_KGDocVersionArray);
    	}
    	else
    	{
    		m_buttonToolbar_docVersionSelect.PopulateWithoutReload(m_KGDocVersionArray);
    	}
    
			m_buttonToolbar_docVersionSelect.MarkEditedVersions(m_KnowdeDocVersionArray);
			m_buttonToolbar_docVersionSelect.KGID = retMessage.CurrentHistoryItem.KGID;
   }

  
  if (!retMessage.CurrentHistoryItem.KGID)
    m_buttonToolbar_docVersionSelect.Hide();
  else if (Map_MultiVersionTextView == 1)
    m_buttonToolbar_docVersionSelect.Show();

  $('#KGMapToolbarOuterDiv').css('visibility', 'visible');
  $('#KGWhatOptionDropDownOuterDiv').css('visibility', 'visible');
  

}


function KGMapToolbarControl_ProcessCallBackError_Wrapped(_args, _context, _KGButtonToolbarClientID)
{
  var holder = document.getElementById(_KGButtonToolbarClientID);
  if (holder != null)
      holder.innerHTML = 'Exception occurred.';
}


function KGButtonToolbar_GetDocVersionSelect_Wrapped(_id)
{
  return document.getElementById(_id);
}


// DocVersionSelect class - moved from KGButtonToolBar
function KGButtonToolbar_DocVersionSelect()
{
  this.select = KGButtonToolbar_GetDocVersionSelect();
  this.newOption;
  this.deleteOption;
  this.KGID;
  
  this.Initialise = function()
  {
    // clear all entries in the droplist
    while (this.select.length > 0)
    {
      this.select.remove(this.select.length-1);
    }
  };
  
  // generates an element id for an option in the list
  this.CreateOptionId = function(_value)
  {
    if (_value == null)
      _value = "default";
    
    return this.select.id + "|" + _value;
  };
  
  // add an option to the select drop list
  // _text and _value inputs
  this.AddOption = function(_text, _value, _before)
  {
    // create a new option object
    var docVersion = document.createElement('option');
    docVersion.text = _text;
    docVersion.value = _value;
    docVersion.id = this.CreateOptionId(_value);
    // add to the droplist
    
    if (_before != null)
    {
      try
      {
        this.select.add(docVersion, _before); // standards compliant        
      }
      catch(ex)
      {
        this.select.add(docVersion, _before.index); // IE only
      }
    }
    else
    {
      try
      {
        this.select.add(docVersion, null); // standards compliant        
      }
      catch(ex)
      {
        this.select.add(docVersion); // IE only
      }
    }
    
    return docVersion;
  };
  
  // removes an option from the select drop list
  // _value input
  this.Remove = function(_value)
  {
  //debugger;
    var optionid = this.CreateOptionId(_value);
    var option = document.getElementById(optionid);
    
    if (option)
    {
        var optionindex = option.index;    
        this.select.remove(optionindex);
    }       
  };
  
   // adds each entry in the _docVersions array to the droplist
  this.Populate = function(_docVersions)
  {
    // clear the drop list
    this.Initialise();
        
    // default text version
    if(!(m_bEditable && Map_TextEditOnly == 1) && m_showDefault == true)
      this.AddOption("Default Text Version", "default");
    
    // create new Text Version
    if(Map_TextEditOnly == 0 && !isMultiVersionTextViewReadOnly && Active_KGID !=null)
    { // text edit only permission won't be able to create text version
        this.AddCreateOption();   
    }

    this.DocVersionCount = 0;
    if (_docVersions != null)
    {
      // If there are some non default text versions, add an option to delete
      if (_docVersions.length > 0 && Map_TextEditOnly == 0 && !isMultiVersionTextViewReadOnly)
      {// text edit only permission won't be able to delete text version
        this.AddDeleteOption();
      }
      
     var defaultSelectedValue = 'default';
      var containsCurrentSelection = 0;
      
      var PublishedVersionsList = new Array();
      
      // loop through _docVersions array
      for (var arrayIndex=0; arrayIndex < _docVersions.length; arrayIndex++)
      {                        
        if (m_showDefault==false&& arrayIndex==0)
           defaultSelectedValue = _docVersions[arrayIndex].verID; //this.CreateOptionId(_value);
           
        if (!PublishedVersionsList.Contains(_docVersions[arrayIndex].verID))
        {
            this.AddOption(_docVersions[arrayIndex].name, _docVersions[arrayIndex].verID, this.newOption);
            this.DocVersionCount += 1;
        }
        
        if(m_textViewDocVersion != null && _docVersions[arrayIndex].verID == m_textViewDocVersion)
          containsCurrentSelection = 1;
          
        PublishedVersionsList[arrayIndex] = _docVersions[arrayIndex].verID;  
      }
      
      if(m_textViewDocVersion != null && containsCurrentSelection == 1)
      {
        // auto select the previous selection
        this.select.value = m_textViewDocVersion;
      }else
      {
        if(defaultSelectedValue == 'default')
          m_textViewDocVersion = null;
        else
          m_textViewDocVersion = defaultSelectedValue;
      }    
     
    }

    if (m_bEditable)
    {
        setTimeout('DisplayTextViewInTab("KnowdeSelected-ReloadTextView");', 500)
    }
    else
    {
        setTimeout('DisplayTextViewInTab("TextView");', 500)
    }    
    
  };
  
  
  // adds each entry in the _docVersions array to the droplist
  this.PopulateWithoutReload = function(_docVersions)
  {
    var defaultSelectedValue = this.select.value;
    this.Initialise();
        
    // default text version
    if(!(m_bEditable && Map_TextEditOnly == 1) && m_showDefault == true)
      this.AddOption("Default Text Version", "default");
    
    // create new Text Version
    if(Map_TextEditOnly == 0 && !isMultiVersionTextViewReadOnly && Active_KGID !=null)
    { // text edit only permission won't be able to create text version
        this.AddCreateOption();   
    }

    this.DocVersionCount = 0;
    if (_docVersions != null)
    {
      // If there are some non default text versions, add an option to delete
      if (_docVersions.length > 0 && Map_TextEditOnly == 0 && !isMultiVersionTextViewReadOnly)
      {// text edit only permission won't be able to delete text version
        this.AddDeleteOption();
      }
           
      var containsCurrentSelection = 0;
      var PublishedVersionsList = new Array();
      
      // loop through _docVersions array
      for (var arrayIndex=0; arrayIndex < _docVersions.length; arrayIndex++)
      {
                
        if (!PublishedVersionsList.Contains(_docVersions[arrayIndex].verID))
        {
            this.AddOption(_docVersions[arrayIndex].name, _docVersions[arrayIndex].verID, this.newOption);
            this.DocVersionCount += 1;
        }
        
        if(m_textViewDocVersion != null && _docVersions[arrayIndex].verID == m_textViewDocVersion)
          containsCurrentSelection = 1;
          
        PublishedVersionsList[arrayIndex] = _docVersions[arrayIndex].verID;    
      }

      if (!(defaultSelectedValue == "delete" || defaultSelectedValue == "new"))          
      {          
        m_textViewDocVersion = defaultSelectedValue;
        this.select.value = defaultSelectedValue;
      }
     
    }   
    
  };  
  
  
  
  this.AddCreateOption = function()
  {
      this.newOption = this.AddOption("Create New Text Version", "new");        
      if (m_newTextVersionControl==null)    
          m_newTextVersionControl = new KGNewTextVersionControl();   
  
  }
  this.AddDeleteOption = function()
  {
    this.deleteOption = this.AddOption("Delete Text Version(s)", "delete");
    if (m_deleteTextVersionControl == null)
      m_deleteTextVersionControl = new KGDeleteTextVersionControl();
  };
  
  this.AddDefaultOption = function()
  {
    this.AddOption("Default Text Version", "default");
  };  
  
  // select onchange event handler
  this.Changed = function(e)
  {
    TextVersionChanged_SaveTextView();
    var selectedValue = this.select.value;
    switch(selectedValue)
    {
      case "new":
        if(m_bEditable && Map_TextEditOnly == 1)
          return false;
        UpdateKGNewTextVersionControlPos('absolute', e.x<450?0:e.x-450, e.y+10);
        m_newTextVersionControl.Open();
        // disable drop down list
        m_buttonToolbar_docVersionSelect.select.disabled = true;
        break;
      case "delete":
        if(m_bEditable && Map_TextEditOnly == 1)
          return false;
        UpdateKGDeleteTextVersionControlPos('absolute', e.x<450?0:e.x-450, e.y+10);
        m_deleteTextVersionControl.Open();
        // disable drop down list
        m_buttonToolbar_docVersionSelect.select.disabled = true;
        break;
      case "default":
        if(m_bEditable && Map_TextEditOnly == 1)
          return false;
        m_textViewDocVersion = null;
        m_bLoadSiblingKnowde = false;
        if (m_bEditable)
        {
            DisplayTextViewInTab("KnowdeSelected-ReloadTextView");
        }
        else
        {
            DisplayTextViewInTab("TextView");
        }
        break;
      default: // for all other selectedValues
        m_textViewDocVersion = selectedValue;        
        if (m_bEditable)
        {
            DisplayTextViewInTab("KnowdeSelected-ReloadTextView");
        }
        else
        {
            DisplayTextViewInTab("TextView");
        }

    }
  };
  
  // adds asterisk to any options in _knowdeDocList for currently selected knowde
  this.MarkEditedVersions = function(_knowdeDocList)
  {
//  debugger;
    for (var index in _knowdeDocList)
    {
      if(_knowdeDocList[index].docKnowdeID == returnKnowdeID(globalLastSelectedKnowde)
      && _knowdeDocList[index].changed)
      {
        // non default text version for currently selected knowde
        // if it's edited, update the relevant option name
        var id = this.CreateOptionId(_knowdeDocList[index].verID);
        var docVersion = document.getElementById(id);
        if (docVersion.text.indexOf("*") == -1)
          docVersion.text += ' *';
      }
    }
  };
  
  // marks currently selected version as edited and updates _knowdeDocList
  this.Edited = function(_knowdeDocList)
  {
    var option = this.select.options[this.select.selectedIndex];
    
    if (option.value != "default" && option.value != "new" && option.value != "delete")
    {
      var knowdeDocInList = false;
      // need to update the doc list in memory in case we click away from the knowde and then back again.
      for(var index in _knowdeDocList)
      {
        if(_knowdeDocList[index].verID == option.value && _knowdeDocList[index].docKnowdeID == returnKnowdeID(globalLastSelectedKnowde))
        {
          _knowdeDocList[index].changed = true;
          knowdeDocInList = true;
          break;
        }
      }
      
      if (!knowdeDocInList)
      {
        // insert a new entry into the knowdeDocList
        var newVersion = eval("[{\"verID\":"+option.value+",\"name\":\""+option.text+"\",\"changed\":true,\"docKnowdeID\":\""+returnKnowdeID(globalLastSelectedKnowde)+"\"}]");
        if (_knowdeDocList != null)
          _knowdeDocList = _knowdeDocList.concat(newVersion);
        else
          _knowdeDocList = newVersion;
      }
      
      if(option.text.indexOf("*") == -1)
      {
        option.text += " *";
      }
    }
    return _knowdeDocList;
  };
  
  this.Show = function()
  {
    this.select.className = "KGButtonToolbar_DocVersionSelect";
  };
  
  this.Hide = function()
  {
    this.select.className = "MapToolbarDocVersion_Hidden";
  };
  
  return true;
}

function TextVersionChanged_SaveTextView()
{
  if(m_bTextViewWritable == true && EditFrameContentWindowExists())
  {
    m_EditFrame.contentWindow.document.contentEditable = "false";
    // save text view
    var saveArgs = 'Action=AutoSave|KGId=' + Active_KGID + '|KnowdeId=' + m_strSelectedKnowdeID; //can't use this, won't work in add knowde, returnKnowdeID(globalLastSelectedKnowde)
    saveArgs += '|Repopulate=false';
    // the line below need to be taken out if we change back to mutliple knowde text view again
    m_bLoadSiblingKnowde = false;

    SaveTextView(saveArgs);
    // only turn off editing mode when click non-sibling knowde
    if(m_bLoadSiblingKnowde == false)
      m_bTextViewWritable = false;
    //setTimeout("handleKnowdeClick('" + _parentKnowdeDiv + "','" + _mapDirection + "','" + _doCallback + "','" + _allowEdit + "')", 500); 

  }
  
   //DisplayHintMessage("KnowdeSelected-ReloadTextView");  // We want the text to be in the pop-up help bo
}

function ChooseMapBackground(e)
{
	// Find element Position
	var targ = document.getElementById("KGMapToolbar1_background");
	var coords = findPosNoAdjust(targ);
	
	// Show the element
	var elementToShow = document.getElementById("MapBGSelector");
	elementToShow.style.top = "75";
	elementToShow.style.left = coords[0];
	elementToShow.style.display = "block";
}

function HideBackgroundOptions()
{
	var elementToShow = document.getElementById("MapBGSelector");
	elementToShow.style.display = "none";
}

function ShowBackgroundOptions()
{
	var elementToShow = document.getElementById("MapBGSelector");
	elementToShow.style.display = "block";
}

function SwitchMapBackground(_type)
{
	// Set latest cookie
	WM_setCookie('MapBackground', _type, 720);
	
	// Perform the switch
	switch(_type)
	{
		case "WC":
			document.getElementById("WhyCodeBGOption").style.listStyleType = "disc";
			document.getElementById("EnterpriseBGOption").style.listStyleType = "circle";
			document.getElementById("MindMapBGOption").style.listStyleType = "circle";
			document.getElementById("NoneBGOption").style.listStyleType = "circle";
			
			document.getElementById("MM_1").style.display = "none";
			document.getElementById("MM_2").style.display = "none";
			document.getElementById("MM_3").style.display = "none";
			document.getElementById("MM_4").style.display = "none";
			document.getElementById("MM_5").style.display = "none";
			document.getElementById("FYO_1").style.display = "none";
			document.getElementById("FYO_2").style.display = "none";
			document.getElementById("FYO_3").style.display = "none";
			document.getElementById("FYO_4").style.display = "none";
			document.getElementById("FYO_5").style.display = "none";
			document.getElementById("WC_1").style.display = "block";
			/*document.getElementById("WC_2").style.display = "block";
			document.getElementById("WC_3").style.display = "block";*/
			document.getElementById("WC_4").style.display = "block";
			document.getElementById("WC_5").style.display = "block";
			break;
		case "FYO":
			document.getElementById("WhyCodeBGOption").style.listStyleType = "circle";
			document.getElementById("EnterpriseBGOption").style.listStyleType = "disc";
			document.getElementById("MindMapBGOption").style.listStyleType = "circle";
			document.getElementById("NoneBGOption").style.listStyleType = "circle";
			
			document.getElementById("MM_1").style.display = "none";
			document.getElementById("MM_2").style.display = "none";
			document.getElementById("MM_3").style.display = "none";
			document.getElementById("MM_4").style.display = "none";
			document.getElementById("MM_5").style.display = "none";
			document.getElementById("FYO_1").style.display = "block";
			document.getElementById("FYO_2").style.display = "block";
			document.getElementById("FYO_3").style.display = "block";
			document.getElementById("FYO_4").style.display = "block";
			document.getElementById("FYO_5").style.display = "block";
			document.getElementById("WC_1").style.display = "none";
			document.getElementById("WC_2").style.display = "none";
			document.getElementById("WC_3").style.display = "none";
			document.getElementById("WC_4").style.display = "none";
			document.getElementById("WC_5").style.display = "none";
			break;
		case "MM":
			document.getElementById("WhyCodeBGOption").style.listStyleType = "circle";
			document.getElementById("EnterpriseBGOption").style.listStyleType = "circle";
			document.getElementById("MindMapBGOption").style.listStyleType = "disc";
			document.getElementById("NoneBGOption").style.listStyleType = "circle";

			document.getElementById("FYO_1").style.display = "none";
			document.getElementById("FYO_2").style.display = "none";
			document.getElementById("FYO_3").style.display = "none";
			document.getElementById("FYO_4").style.display = "none";
			document.getElementById("FYO_5").style.display = "none";			
			document.getElementById("MM_1").style.display = "block";
			document.getElementById("MM_2").style.display = "block";
			document.getElementById("MM_3").style.display = "block";
			document.getElementById("MM_4").style.display = "block";
			document.getElementById("MM_5").style.display = "block";
			document.getElementById("WC_1").style.display = "none";
			document.getElementById("WC_2").style.display = "none";
			document.getElementById("WC_3").style.display = "none";
			document.getElementById("WC_4").style.display = "none";
			document.getElementById("WC_5").style.display = "none";
			break;
		case "None":
			document.getElementById("WhyCodeBGOption").style.listStyleType = "circle";
			document.getElementById("EnterpriseBGOption").style.listStyleType = "circle";
			document.getElementById("MindMapBGOption").style.listStyleType = "circle";
			document.getElementById("NoneBGOption").style.listStyleType = "disc";
			
			document.getElementById("MM_1").style.display = "none";
			document.getElementById("MM_2").style.display = "none";
			document.getElementById("MM_3").style.display = "none";
			document.getElementById("MM_4").style.display = "none";
			document.getElementById("MM_5").style.display = "none";
			document.getElementById("FYO_1").style.display = "none";
			document.getElementById("FYO_2").style.display = "none";
			document.getElementById("FYO_3").style.display = "none";
			document.getElementById("FYO_4").style.display = "none";
			document.getElementById("FYO_5").style.display = "none";
			document.getElementById("WC_1").style.display = "none";
			document.getElementById("WC_2").style.display = "none";
			document.getElementById("WC_3").style.display = "none";
			document.getElementById("WC_4").style.display = "none";
			document.getElementById("WC_5").style.display = "none";
			break;
	}
}

function KGMapToolbarControl_Toggle(_show) 
{
  var containerID = KGMapToolbarControl_GetContainerID();
  var whatContainer = document.getElementById('KGWhatOptionDropDown');
  if (containerID != null)
  {
    var container = document.getElementById(containerID);
    if (container != null)
    {
      if (_show == null || _show == true) {
        container.style.display = "block";
        if (whatContainer != null)
          whatContainer.style.display = "block";
      }
      else {
        container.style.display = "none";
        if (whatContainer != null)
          whatContainer.style.display = "none";
      }
    }
  }

}





