// body onload doesn't fire in non IE browsers, so the following window onload function is used instead
// (this one doesn't fire in IE...)
window.onload = function(){windowLoad();};
window.onresize = windowResize;  

// move from MapView.js to here in case the merged mapview js loaded too late
// for partial editing
var Map_TextEditOnly = 0;
// for multi verson text view
var Map_MultiVersionTextView = 0;
// allow other user to add whats to published KG
var AllowWhatEditOnly = 0;

var globalHideDockButton = false;
var Active_KGID = ""; // must be predefined
var MapViewJSLoaded = 0;

var mSignInControlDivId = "";
var mNewKGControlDivId = "";
var globalSplitterSetting = "single";
var globalFeaturedCategory;
var globalBubbleFullText = "";
var globalEditTimeOut = "";
var global_reloadApp = "true";
var _globalCookieTestResult = new Boolean(true);
var globalBrowserSessionSet = new Boolean(false);
var globalHideIndexedDocs = true;

var mvcCallbackTimeout;
var tabwinCallbackTimeout;

var m_catCookieExpiration = 8760; // cookie expiration date in hours from current time. 8760 = 1 year

// Delay MapView script loading, for performance purpose
if (!window.MapViewDefaultFocus)
{
    function MapViewDefaultFocus(){}; // will get written over when the Mapjs is loaded
}
if (!window.drawInitialMap)
{function drawInitialMap(){}; // will get written over when the Mapjs is loaded
}
if (!window.MapViewControl_ShowLoadingIcon)
{function MapViewControl_ShowLoadingIcon(){}; // will get written over when the Mapjs is loaded
}
if (!window.mouseupMain)
{function mouseupMain(){}; // will get written over when the Mapjs is loaded
}  
if (!window.MapViewControl_CallbackDone_Wrapped)// will get written over when the Mapjs is loaded, then timeout calls the right one
{
  function MapViewControl_CallbackDone_Wrapped(args)
  {
    // Check for a session time out before completing the callback
    if (CheckSessionTimeout())
      return;
    
    if (args != null)
      globalTempArgs=args;
    setTimeout("MapViewControl1_CallbackDone()",100); 
  }
}
// This next little bit of code tests whether the user accepts cookies.
var WM_acceptsCookies = false;
if(document.cookie == '') 
{
	document.cookie = 'WM_acceptsCookies=yes'; // Try to set a cookie.
  if(document.cookie.indexOf('WM_acceptsCookies=yes') != -1) 
  {
		WM_acceptsCookies = true; 
  }
} 
else 
{
  document.cookie = 'WM_acceptsCookies_test2=yes'; // Try to set a cookie.
  if(document.cookie.indexOf('WM_acceptsCookies_test2=yes') != -1) 
  {
		WM_acceptsCookies = true; 
  }
}

function WM_readCookie(name) 
{
	if(document.cookie == '') 
	{ 
		// there's no cookie, so go no further
		return false; 
  } 
  else 
  {
		// there is a cookie
		var firstChar, lastChar;
		var theBigCookie = document.cookie;
		firstChar = theBigCookie.indexOf(name);	// find the start of 'name'
		var NN2Hack = firstChar + name.length;
		if((firstChar != -1) && (theBigCookie.charAt(NN2Hack) == '=')) 
		{ 
			// if you found the cookie
	    firstChar += name.length + 1; // skip 'name' and '='
	    lastChar = theBigCookie.indexOf(';', firstChar); // Find the end of the value string (i.e. the next ';').
	    if(lastChar == -1)
				lastChar = theBigCookie.length;
				return unescape(theBigCookie.substring(firstChar, lastChar));
		} 
		else 
		{ 
			// If there was no cookie of that name, return false.
	    return false;
		}
	}	
}

// This next little bit of code tests whether the user accepts cookies.
var WM_sessionCookie = true;
if(WM_readCookie('WM_sessionCookie') != false) 
{
		WM_sessionCookie = false; 
} 
else 
{
	document.cookie = 'WM_sessionCookie=yes';
  WM_sessionCookie = true;
}

var m_bEditable = false;
var global_newKGCreated = false;
var global_newKGCreatedSplitViewSet = false;
var globalTempArgs = null;
var m_triggerMapCallbackOnload = false;
var m_triggerMapCallbackOnload_IsSet = false;
var m_mapViewCallBackWaitCount = 0;
var m_tabbedWindowCallBackWaitCount = 0;

var globalUpdateBubble = null;

function Set_triggerMapCallbackOnload(_value)
{
  m_triggerMapCallbackOnload_IsSet = true;
  //m_triggerMapCallbackOnload = _value;
  if (_value == "true" || _value == true)
		m_triggerMapCallbackOnload = true;
	else
		m_triggerMapCallbackOnload = false;

}

// walk around for the pending callback error //WebForm_CallbackComplete_SyncFixed
function WebForm_CallbackComplete_SyncFixed() {
     // the var statement ensure the variable is not global
     for (var i = 0; i < __pendingCallbacks.length; i++) {
        qcallbackObject = __pendingCallbacks[i];
        if (callbackObject && callbackObject.xmlRequest && (callbackObject.xmlRequest.readyState == 4)) {
            // SyncFixed: line move below // WebForm_ExecuteCallback(callbackObject);
            if (!__pendingCallbacks[i].async) { 
                __synchronousCallBackIndex = -1;
            }
            __pendingCallbacks[i] = null;
            var callbackFrameID = "__CALLBACKFRAME" + i;
            var xmlRequestFrame = document.getElementById(callbackFrameID);
            if (xmlRequestFrame) {
                xmlRequestFrame.parentNode.removeChild(xmlRequestFrame);
            }
            // SyncFixed: the following statement has been moved down from above;
            WebForm_ExecuteCallback(callbackObject);
        }
    }
}

// window load event handler
function windowLoad()
{
	try
	{
		detect();
		initialiseOverlays();
  }
  catch(e)
  {
		alert('windowLoad() error');
  }
}

var HCCResizeTimer;

// window resize event handler
function windowResize()
{
	try
	{
		// only attempt to adjust the height if the splitter exists
		if (window.Splitter1 && window.Splitter1.Panes)
		{
			// Adjust Splitter Heights
			if(PanesAreSplit())
			{
				setTimeout("DoExpandMapViewPane('split');", 110);
			}
			else
			{
				AdjustSplitterHeight();
				setTimeout('resetHeights()',100);
			}	
		}
		if (window.MapViewDefaultFocus)
			setTimeout('MapViewDefaultFocus()',105);
		if(window.TextViewDivResize)
			setTimeout('TextViewDivResize()',110);
		if(window.HandleTextTabResize)
			setTimeout('HandleTextTabResize()',115);
	  if(m_globalFullDocked  == true)
	    setTimeout('AdjustFullyDockedControlSize()',120);
		if(window.HelpFrameDivResize)
			setTimeout('HelpFrameDivResize()',130);
		if(window.HorizontalCategoriesControl_Resize)
			setTimeout("HorizontalCategoriesControl_Resize(null);", 100);
  }
  catch(e)
  {
  }
}

// shows the sign in and new kg overlays on page load (when needed)
function initialiseOverlays()
{
	if (mSignInControlDivId == "" && window.getSignInControlDivId)
	{
		// get the sign in control div ID
		mSignInControlDivId = getSignInControlDivId();
	}
	if (mNewKGControlDivId == "" && window.getNewKGControlDivId)
	{
		// get the newKG control div ID
		mNewKGControlDivId = getNewKGControlDivId();
	}

  var divSignIn = document.getElementById(mSignInControlDivId);

  if (divSignIn != null)
  {  
    if (divSignIn.attributes.getNamedItem("ShowOverlayOnPageLoad") != null)
    {
      // Toggle Login control if it needs to be shown, or if it is visible when it shouldn't be
      if ( (divSignIn.attributes.getNamedItem("ShowOverlayOnPageLoad").nodeValue == "true" && divSignIn.className == "OverlayPositionHidden")
          || (divSignIn.attributes.getNamedItem("ShowOverlayOnPageLoad").nodeValue == "false" && divSignIn.className == "OverlayPosition") )
      {
        var cookieLoginStatus = WM_readCookie("LoginStatus");

        if(cookieLoginStatus != null && cookieLoginStatus == "NotActivated")
        {
          var resendBtn = document.getElementById("SiteOverlays_LoginView1_KGSignInControl1_ResendBtn");
          if(resendBtn != null)
            resendBtn.className = "ShowResendButton";				      
        }

        wait("ToggleLoginControl();", 1000);
      }
    }
  }
}

var waitFunctionTimer="";

function wait(_exp2execute, _timeDelay)
{
    clearTimeout(waitFunctionTimer);

    if(__pendingCallbacks[0] == null)
    {
	    eval(_exp2execute);
    }
    else
    {
	    waitFunctionTimer = setTimeout("wait('" + _exp2execute + "'," + _timeDelay + ")", _timeDelay);
    }
}

function returnFromEditView()
{
	if(m_bEditable)
	{
		// if the user was in full view before they started editing, put it back to full view
		if (!WM_readCookie('SplitView'))
			SwitchToFullView();
	}
}

function detect()
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
	_globalCookieTestResult = true;
	//	browser detect
	SetSessionProperty("Browser",navigator.appName);
	globalBrowserSessionSet = true;
	
	if(WM_acceptsCookies == false)
	{
		_globalCookieTestResult = false;
		if(document.getElementById("Splitter1") != null)
		{
			Splitter1.disabled = true;
			window.ComponentArt_Splitter_Loaded = false;
		}
		var BrowserDiv = document.createElement("span");
		var CookieContainerDiv = document.createElement("div");
		var CookieDiv = document.createElement("img");

		var width = screen.availWidth;
		var height = screen.availHeight;
		
		BrowserDiv.style.width = width;
		BrowserDiv.style.height = height;
		BrowserDiv.className = "BrowserDiv";
		
		CookieContainerDiv.style.width = width;
		CookieContainerDiv.style.height = height;
		CookieContainerDiv.className = "CookieContainerDiv";
		CookieContainerDiv.appendChild(CookieDiv);
		if (navigator.appName == "Microsoft Internet Explorer")
		{
			CookieDiv.src = "Images/HomePage/CookiesMsg.png";
			CookieDiv.className = "CookieDiv";
		}
		else
		{
			CookieDiv.src = "Images/HomePage/CookiesMsgNonIE.png";
			CookieDiv.className = "CookieDivNonIE";
		}
		
		var page = document.getElementById("Form1");
		page.appendChild(BrowserDiv);
		page.appendChild(CookieContainerDiv);
	}
	
	if(window.HorizontalCategoriesControl_Render)
	  setTimeout("HorizontalCategoriesControl_Render();", 200);
}

function setActiveStyleSheet(title) 
{
	var si, a, main;
	for(si=0; (a = document.getElementsByTagName("link")[si]); si++) 
	{
		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) 
		{
			a.disabled = true;
			if(a.getAttribute("title") == title || a.getAttribute("title") == "default") 
			{
				a.disabled = false;
			}
		}
	}
}

// adjust the splitter fill height  
function AdjustSplitterHeight()
{
  // sets the height adjustment attribute on the splitter to the difference between the window height and the splitter height
  // find the top position of the splitter and add this to the heightAdjustment attribute
  var SplitterPos = findPosNoAdjust(document.getElementById('Splitter1'));
  Splitter1.HeightAdjustment = -(Splitter1.WindowHeight - Splitter1.AvailableHeight - SplitterPos[1]);
}

// Counts the number of times the short string _str appears in the _fullString
function countStringOccurances(_str, _fullString)
{
  var count = 0;
  
  while (_fullString.indexOf(_str) > -1)
  {
    _fullString = _fullString.replace(_str,"")
    count = count + 1;
  }
  
  return count;
}

function SetSessionProperty( _strPropertyName, _strValue, _multiKeyValues)
{
	try
	{
    var localTime = new Date();
    var utc = localTime.getTime() + (localTime.getTimezoneOffset() * 60000 );
    
    var queryStrings = _strPropertyName + '=' + _strValue;
    if(_multiKeyValues == true)
    {
      queryStrings = '';
      var keys = _strPropertyName.split('|');
      var values = _strValue.split('|');
      
      for(var qsidx = 0; qsidx < keys.length; qsidx++)
      {
        if(qsidx < values.length)
        {
          if(keys[qsidx].length > 0)
          {
            if(queryStrings.length > 0)
              queryStrings += '&';
            queryStrings += keys[qsidx] + '=' + values[qsidx];
          }
        }
      }
    }
    var sessionASHXUrl = strSessionPropertiesASHX + '?' + queryStrings + '&utc=' + utc;
    
    if (window.XMLHttpRequest) // Mozilla, Safari, IE7 ...
    {
      var req = new XMLHttpRequest();
      req.open('GET', sessionASHXUrl, false); // third param = asynchronous
      //req.onerror = function(){if (confirm('ssp error, debug?')) debugger;};
      //req.onabort = function(){if (confirm('ssp abort, debug?')) debugger;};
      //req.mozBackgroundRequest = true; // don't cancel it if the  window is closed (maybe for redirect also?)
      req.send(null);
    
      //check the error code that comes back to see if there is anything wrong. If there is then don't do anything
      if(req.status != 0) // 0 if url doesn't have http, 200 if it does
      {}
    }
    else
    {
      var xmlIsland = document.getElementById('HKSetSessionProperties_xmlIsland');
      if( typeof(xmlIsland) == 'object' && xmlIsland != null )
      {
        //set up so we're ready for the load. Including constructing the URL to use
        var dataIsland = xmlIsland.XMLDocument;
        dataIsland.async = false;
        //do the actual load
        dataIsland.load( sessionASHXUrl );
        //check the error code that comes back to see if there is anything wrong. If there is then don't do anything
        var error = dataIsland.parseError;
        if( error.errorCode == 0 )
        {}
      }
    }
  }
  catch(e)
  {
		//alert('SetSessionProperty() error:' + _strPropertyName + ', ' + _strValue);
		//debugger;
  }
}

var strSessionPropertiesASHX = 'ASHX/SessionProperties.ASHX';

function GetHtmlFromAshx(_url, _xmlIsland)
{
  var newHtml = '';
  if (window.XMLHttpRequest) // Mozilla, Safari, IE7 ...
  {
    var req = new XMLHttpRequest();
    req.open('GET', _url, false); // third param = asynchronous
    req.send(null);
    
    //check the error code that comes back to see if there is anything wrong. If there is then don't do anything
    if(req.status == 200)
      newHtml = req.responseText;
    else
      newHtml = 'error';
  }
  else // IE6
  {
    if (!_xmlIsland)
    {
      _xmlIsland = document.createElement("xml");
      _xmlIsland.id = "knowdeId1";
      _xmlIsland.innerHTML = "<span></span>";
      document.body.appendChild(_xmlIsland);
    }
    
   // PL08Dec06 - Added to solved a strange bug where, after a sequence of 
   // quick knowde clicks and floating overs, the XMLDocument attribute is not
   // created when the knowde is created. see Bug 716 
    if(_xmlIsland.XMLDocument == null)
    { 
      _xmlIsland.XMLDocument = new ActiveXObject("Microsoft.XMLDOM");
    }
 
    var dataIsland = _xmlIsland.XMLDocument;
    dataIsland.async = false;

    dataIsland.load(_url); 
  
    if (dataIsland.parseError.errorCode != 0)
      newHtml = 'error';
    else
      newHtml = dataIsland.xml;
  }
  
  return newHtml;
}
    
function LoadMapTabbedView()
{
	try
	{
	  setPaneSize();
		
		// show the more text tab
		/*var Tab = document.getElementById("TSC_moretext");
		var WidgetTab = document.getElementById("TSC1_moretext");
		if(Tab != null)
			ShowTab(Tab, WidgetTab);*/
		// For production 
		importScript('MapViewMinified.js');
		//importScript('MapViewControl.js');
		//importScript('MapEditing.js');
		
		SrmControl_RecordTimes(0);
	  
		var srmIndex = SrmControl_SetInitial('InitialCallbackToKGTabbedWindows');
	  
	  if (m_triggerMapCallbackOnload == false)
	  {
	    if (isAuthenticated() == true)
			{
  			var userID = WM_readCookie('UserID');
				var category = WM_readCookie('User' + userID + '_category');
	    }
	  }
	  var splitter = document.getElementById("Splitter1_pane_0");
		if (global_newKGCreated == true)
		{
			global_newKGCreated = false;
			global_newKGCreatedSplitViewSet = true;
			SwitchToSplitView(false, true); //don't set the cookie 
		}
		else if (m_triggerMapCallbackOnload == true)
		{
			//if the pane is expanded and the map view is not editable, trigger map view callback
			if (m_bEditable == false && splitter.clientHeight > 0)
			{
				setTimeout('MapViewControl1_CallbackTrigger()',1); // timeout for importScript
				globalMapViewControlLoaded = true;
			}
		}
		else if (m_triggerMapCallbackOnload_IsSet == false)
		{
		  if (m_bEditable == false && splitter.clientHeight > 0)
		  {
        m_mapViewCallBackWaitCount = 0;
		    mvcCallbackTimeout = setTimeout('TriggerMapViewCallBackTimeOut()',500);
		  } 
		}
		//ProceedWithTour();
	}
  catch(e)
  {
		alert('LoadMapTabbedView() error');
  }
}

function TriggerMapViewCallBackTimeOut()
{
  if(m_triggerMapCallbackOnload == true)
  {
    m_mapViewCallBackWaitCount = 0;
	  MapViewControl1_CallbackTrigger();
	}
	else if (m_triggerMapCallbackOnload_IsSet == false && m_mapViewCallBackWaitCount < 120)
	{
	   // wait again
	   m_mapViewCallBackWaitCount++;
	   clearTimeout(mvcCallbackTimeout);
		 mvcCallbackTimeout = setTimeout('TriggerMapViewCallBackTimeOut()',500); 
	}else if(m_triggerMapCallbackOnload_IsSet == false && m_mapViewCallBackWaitCount >= 120)
	{
	  //alert('m_triggerMapCallbackOnload still havenot been set yet [' + m_mapViewCallBackWaitCount + ' attemps], no mapview will be loaded.');
	  m_mapViewCallBackWaitCount = 0;
	}
}

function TriggerTabbedWindowCallBackTimeOut()
{
  /*if(m_triggerMapCallbackOnload_IsSet == true)
  {
    m_tabbedWindowCallBackWaitCount = 0;
    if(m_triggerMapCallbackOnload == false)
    {
	    KGTabbedWindowsControl_CallbackTrigger('TabSelected');
	    globalHideIndexedDocs = false;
	  }
	}
	else if (m_triggerMapCallbackOnload_IsSet == false && m_tabbedWindowCallBackWaitCount < 120)
	{
	   // wait again
	   m_tabbedWindowCallBackWaitCount++;
	   clearTimeout(tabwinCallbackTimeout);
		 tabwinCallbackTimeout = setTimeout('TriggerTabbedWindowCallBackTimeOut()',500); 
	}else if(m_triggerMapCallbackOnload_IsSet == false && m_tabbedWindowCallBackWaitCount >= 120)
	{
	  //alert('m_triggerMapCallbackOnload still havenot been set yet [' + m_tabbedWindowCallBackWaitCount + ' attemps], no tabbedwindow callback will be performed.');
	  m_tabbedWindowCallBackWaitCount = 0;
	}*/
}

function findPos(obj) 
{
  var curleft = curtop = 0;
  if (obj.offsetParent) 
  {
	  curleft = obj.offsetLeft
	  curtop = obj.offsetTop
	  while (obj = obj.offsetParent) 
	  {
		  if (obj.id == 'scrolling-section' || obj.id == 'moving-section') // don't want to offset for the HorizontalCategoriesControl outside the splitter
	    {
	      curleft += obj.offsetLeft
	      //curtop -= obj.offsetTop ;
	    }
  	  
	    if (obj.id != 'Splitter1' && obj.id.indexOf('Splitter1') == -1 && obj.id != 'MapContainer' && obj.id != 'scrolling-section' && obj.id != 'moving-section') // don't want to offset for the HorizontalCategoriesControl outside the splitter
	    {
	      curleft += obj.offsetLeft
	      curtop += obj.offsetTop
	    }
	  }
  }
  return [curleft,curtop];
}

function findPosNoAdjust(obj) 
{
  var curleft = curtop = 0;
  if (obj.offsetParent) 
  {
	  curleft = obj.offsetLeft
	  curtop = obj.offsetTop
	  while (obj = obj.offsetParent) 
	  {
	    curleft += obj.offsetLeft
	    curtop += obj.offsetTop
	  }
  }
  return [curleft,curtop];
}

var m_MapHelpBox = null;
var globalHelpTopicKey = null;
var globalHelpTopicParams = null;
var helpWindowTopicKey = null;
var m_Bubble = null;
var globalLastBubbleAction = null;  
//This is also declared in a script at the bottom of home.aspx so for that page it can be assigned any existing session variable.  JPC.

////////////////////////////////////
// Handle's the HelpLink_Clicked event
function HelpLinkClicked(_undock, _firstLoadHelp, e)
{
	try
	{
	  var HelpControl_Callback = false;
    // if we are going to check the visibility of the help control before updating we need to set it up here ready to receive the objective help if necessary
    m_MapHelpBox = document.getElementById("KGHelpControlID1");
    
    if(!globalShowingWebDoc && document.frames)
      document.frames['HelpFrame'].location.reload(true);
    
    //If the control exists on the page
    if (m_MapHelpBox != null)
    {
      // Populate the box   
      //m_bHelpFrameLoadSiblingKnowde = false; 
      var params = GetHelpWindowCallBackArgs();  
      KGHelpControl_CallbackTrigger(globalHelpTopicKey, globalHelpTopicParams + params);
      HelpControl_Callback = true;
      
      // see whether we need to hide the dock button
      var hideDockButton = false;
      if(m_bEditable == true)
        hideDockButton = true;
 
      //if(_undock == true)
      OpenHelpControl(hideDockButton);
      //else
        //DockInPageKGHelpControl();
      
	
			// find x & y coords of all drop lists - hide list if there is an overlay.
			if(navigator.appVersion.match("MSIE 7.0") != "MSIE 7.0" && navigator.appName == "Microsoft Internet Explorer")
			{
				if(m_MapHelpBox.className != "OverlayPositionHidden")
				{
					// find elements x & y coords
					var elemCoords = findElementCoords(m_MapHelpBox);
					var elemCoordsAndWidth = m_MapHelpBox.clientWidth + elemCoords[0];
					var elemCoordsAndHeight = m_MapHelpBox.clientHeight + elemCoords[1];
				}
				// retrieve and hide all droplists.
				var droplist = document.getElementsByTagName("SELECT");
				for(var num=0;num<droplist.length;num++)
				{
					//only hide the visible boxes
					if(droplist[num].className == "list_dropList")
					{
						var dropCoords = findElementCoords(droplist[num])
						var dropCoordsAndWidth = droplist[num].clientWidth + dropCoords[0];
						var dropCoordsAndHeight = droplist[num].clientHeight + dropCoords[1];
						
						if((dropCoords[0] >= elemCoords[0] || dropCoordsAndWidth >= elemCoords[0]) && (dropCoords[0] <= elemCoordsAndWidth || dropCoordsAndWidth <= elemCoordsAndWidth))
						{
							//overlays in the x-range
							if((dropCoords[1] >= elemCoords[1] || dropCoordsAndHeight >= elemCoords[1]) && (dropCoords[1] <= elemCoordsAndHeight || dropCoordsAndHeight <= elemCoordsAndHeight))
							{
								//overlays in the x & y ranges
								droplist[num].style.display = "none";
							}
						}
					}
				}
			}
		
			//check to see if it is the first load 'Help'... if so - reposition & grey the background
			if(_firstLoadHelp)
			{
				m_MapHelpBox = document.getElementById("KGHelpControlID1");
				m_MapHelpBox.style.top = screen.height/5;
				m_MapHelpBox.style.height = screen.height/2;
				m_MapHelpBox.style.left = "30%";
				m_MapHelpBox.style.width = "45%";
				
				var GreyDiv = document.createElement("span");
				
				var width = screen.availWidth;
				var height = screen.availHeight;
				
				GreyDiv.style.width = width;
				GreyDiv.style.height = height;
				GreyDiv.className = "GreyDiv";
				GreyDiv.id = "GreyDiv";
				
				document.getElementById("miniGlobe").className = "firstLoadLogo";
				document.getElementById("m_cookieDiv").className = "m_cookieDiv";
				
				var page = document.getElementById("Form1");
				page.appendChild(GreyDiv);
			}
			else
			{
				m_MapHelpBox.style.top = screen.height/4;//"30%"; //screen.height/3;
				m_MapHelpBox.style.height = screen.height/2;
				
				// in Firefox maintain the previous resize size, otherwise the inner table will go out of place
			  if(resizeInnerEl == null)
			  {
				  m_MapHelpBox.style.left = "5%";
				  m_MapHelpBox.style.width = "45%";
        }
				
			  /*if(resizeInnerEl != null)
        {
          resizeInnerEl.width = '100%';
          resizeInnerEl.height = '100%';
        }*/
			}
      
      // If the box has scrollbars we need to move the buttons into place so they're not hidden.
      if (m_MapHelpBox.clientHeight < m_MapHelpBox.scrollHeight || m_MapHelpBox.clientWidth < m_MapHelpBox.scrollWidth)
      {
        var resizeButton = document.getElementById("ResizeButton");
        
        if (m_MapHelpBox.clientHeight < m_MapHelpBox.scrollHeight)  //There's a vertical scrollbar
        {
          if (resizeButton != null)
            resizeButton.style.bottom = "2px";    
        }
        if (m_MapHelpBox.clientWidth < m_MapHelpBox.scrollWidth)  //There's a horizontal scrollbar
        { 
          if (resizeButton != null)
            resizeButton.style.right = "2px";
            
          var closeButton;
          var method = function(el){if(el.id == "CloseButton_Div_ID") return true; return false;};
          var result = YAHOO.util.Dom.getElementsBy(method,null,m_MapHelpBox);
          closeButton = result[0];
          if (closeButton != null)
            closeButton.style.right = "2px";
        }  //end adjust for width
      } // end check for scrollbars
    }
    CancelBubble(e);
    
    return HelpControl_Callback;
	}
	catch(e)
	{
		alert('HelpLinkClicked() error');
	}
}

// return x and y coords
function findElementCoords(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) 
	{
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) 
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop - obj.scrollTop;
		}
	}
	return [curleft,curtop];
}

// return x and y coords
function findBRElementCoords(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) 
	{
		curleft = obj.offsetLeft + obj.offsetWidth;
		curtop = obj.offsetTop + obj.offsetHeight;
		while (obj = obj.offsetParent) 
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop - obj.scrollTop;
		}
	}
	return [curleft,curtop];
}

////////////////////////////////////
// Displays a message in the hint box
// _message: the message to be displayed, taken from the vars defined in MapHints.js
function DisplayHintMessage(_message, _params, _openText, _kgId)
{
  // Test if the help box is visible
  // YES: Set the global variable for HelpTopicKey 
  //      Do Callback Trigger to update the Help Box
  //  NO: Set the global variable for HelpTopicKey only
  if( _message == "Help")
  {
		if(m_Bubble == null)
			m_Bubble = document.getElementById("KGBubbleControl1");
	        
		if(m_Bubble != null)
		{
			if (_message == "TextView")
				KGBubbleControl_CallbackTrigger("KnowdeSelected");
			if (_message == "TextForSpecifiedKnowde")
				KGBubbleControl_CallbackTrigger("TextForSpecifiedKnowde");
			if (_message == "Help")
				KGBubbleControl_CallbackTrigger('');  // cause Bubble to look up session variable
		}
		return;
  }
  
  if (!(_message == "TextView" ||  _message=="TextForSpecifiedKnowde" || _message.indexOf('ReloadTextView') != -1))
    return;//We're no longer using the xml help

  //debugger;
  /*globalHelpTopicKey = _message;
  //globalHelpTopicParams = _params;  //We're no longer using the xml help

  if (helpWindowTopicKey != "TextView" || _message=="TextForSpecifiedKnowde" || _message.indexOf('ReloadTextView') != -1)
    helpWindowTopicKey = _message;
  
  if(m_MapHelpBox == null)
    m_MapHelpBox = document.getElementById("KGHelpControlID1");
  
  var HelpControl_Callback = false;
  if(_openText == 'true')
  {
    //  by default 
    HelpControl_Callback = HelpLinkClicked();
    //DockInPageKGHelpControl();
    //document.getElementById(_kgId).innerHTML = "Now showing the Map and document";
  }
  
  if(_message.indexOf('ReloadTextView') != -1)
  {
    SwitchTextTabControlMode(true);
    SwitchTextViewViewMode("Single");
  }
  else
    SwitchTextTabControlMode(false);

  if(!HelpControl_Callback &&
  (((m_MapHelpBox != null && m_MapHelpBox.className == "OverlayPosition") || document.getElementById("DockedHelpWindow") !=null) 
    && (globalHelpTopicKey == "TextView" || globalHelpTopicKey == "TextForSpecifiedKnowde" || globalHelpTopicKey.indexOf("ReloadTextView") != -1)))
{
    m_bHelpFrameLoadSiblingKnowde = false;
     var kgid = Active_KGID;
    if(_kgId != null && _kgId > 0)
      kgid = _kgId;
    var params = '';
    if(_message=="TextForSpecifiedKnowde" || _message == "TextView")
    {
      if(m_textViewViewModeChanged == false && m_currentTextViewViewMode == "Full" && m_strFrameSelectedKGID != '' && m_strFrameSelectedKGID == kgid )
        //&& ((m_strFrameSelectedKnowdeID != '' && m_strFrameSelectedKnowdeID == m_tickerKnowdeID) || (m_strFrameSelectedKnowdeDBID != '' && m_strFrameSelectedKnowdeDBID == m_tickerKnowdeID)))
      {
        m_bHelpFrameLoadSiblingKnowde = true;
      }
      
      if(m_tickerKnowdeID != '')
      {
        var kndPathContext = FindSelectedHelpFrameKnowdePathContext(m_tickerKnowdeID);
        var knowdeChanged = ChangeSelectedHelpFrameKnowde(m_tickerKnowdeID, kndPathContext);  
      }
      ///debugger;
      params = GetHelpWindowCallBackArgs(_kgId);
    }
    
     // No point in reloading the text if its already being displayed!
     if(_message.indexOf('ReloadTextView') != -1 || (m_tickerKnowdeID != Active_KnowdeID_Text || m_currentTextViewViewMode == 'Full'))
     {
        KGHelpControl_CallbackTrigger(helpWindowTopicKey, params); //, globalHelpTopicParams); //We're no longer using the xml help
     }
     
   }    
   
  if(HelpControl_Callback == false)
  {
    globalLastTickerAction = "";
  }
   
  // reset the value 
  m_textViewViewModeChanged = false;
  
  //debugger;
  if(globalHideDockButton == true || m_bEditable == true) //globalSplitterSetting == "single" || 
	{
		// hide dock in window option
		var dockInPage = document.getElementById("SiteOverlays_KGHelpControl1_DockInPageButton")
		
		if(dockInPage != null)
		  dockInPage.style.display = "none";
		  
		if(_message == "TextForSpecifiedKnowde")  
		  globalHideDockButton = false;
		
	}
	else 
	{
		// show dock in window option
		document.getElementById("SiteOverlays_KGHelpControl1_DockInPageButton").style.display = "";
	}
	*/
}

function EvalRegisterJavaScripts(javaScripts)
{
  // does the same as RegisterClientScriptBlock at the server, 
  // required because RegisterClientScriptBlock doesn't work in callbacks
  // use this instead of just eval(javaScripts) to give functions global scope
  
  // first split by 'function ' to separate each function
  //   make sure 'function ' isn't written in javaScripts in unusual places, e.g. as a comment/variable
  //   for startup scripts, add 'function ' to the start, so 'function <script>$scriptText$</script>
  
  // start with function $functionName$($parameters$){$functionText$}
  // change to $functionName$ = function($parameters$){$functionText$}
  // using var functionScript = ($parameters$){$functionText$}
  
  // also for start up scripts <script>$scriptText$</script>
  // just eval $scriptText$
  
  var functions = javaScripts.split('function ');
  for (var y = 1; y < functions.length; y++) // start from 1 - functions[0] = '' from the split
  {
    var functiony = functions[y];
    var posScript = functiony.indexOf('<script');
    if (posScript > -1) //Startup script
    {
      var scripts = functiony.split('<script'); // there can be more than one script block
      for (var x = 1; x < scripts.length; x++)
      {
        var scriptx = scripts[x];
        var posStart = scriptx.indexOf('>') + 1;
        var posEnd = scriptx.indexOf('</script>');
        scriptx = scriptx.substring(posStart,posEnd); // lose the start and end <script> tags
        scriptx = scriptx.replace(/var/g,''); //global replace of var to give variables defined here global scope
        eval(scriptx);
      }
    }
    else
    {
      var pos1 = functiony.indexOf('(');
      if (pos1 > 0)
      {
        var functionName = functiony.substring(0,pos1);
        {
          var functionScript = functiony.substring(pos1);
          var newFunction = functionName + '= function' + functionScript;
          eval(newFunction);
        }
      }
      else
        alert('Failed to add function: ' + functiony);
    }
  }
}

function isAuthenticated()
{
  var c_name = 'SignedIn';
  
  // Test if the cookie has been set during the sign in process
  // YES: User has already signed in 
  //  NO: User has not been signed in or does not have an account
  if(document.cookie.length > 0)
  {
    var cookie_content = WM_readCookie(c_name);
    
    if(cookie_content != null && cookie_content.length > 0)
    {
      return true;
    }
    else
    {
      return false; 
    }
  }
  else
    return false;
}

function redirectToSignInSignUpPage(_actionToken, _objectId, _knowdeID)
{
  var returnURL;
  //debugger;
  if(_actionToken.toLowerCase().indexOf('kgid=') == 0)
  {
    // redirect back to Home page and preload the map
    UpdateTour(4);
    returnURL = "home.aspx?" + _actionToken.toLowerCase();
  }
  else
  {
    switch(_actionToken)
    {
      case "AddToMyHK":
        // New format on the return URL parameter
        // action: the action the user is trying to carry out 
        // p: parameters in this format: <CategoryID>.<KGID>
        
        var categoryControlMenu = eval(HorizontalCategoriesControl_getMenuID());
        
        var categoryID = categoryControlMenu.SelectedItem.ID;
        var kgId       = _objectId;

        //remove any existing query string first
        var loc = getNoQueryStringLocation();
          
        returnURL = escape(loc + "?kgid="+kgId+"&action=addToMyHK&p="+categoryID+"."+kgId);
        break;
      case "AddPrivateSpace":
        returnURL = escape(window.location.toString());
        break;
      case "CreateNewKG":
        returnURL = "home.aspx?action=CreateNewKg";
        break;
      case "AddCommunityLink":
        var kgId = _objectId;
        var knowdeId = _knowdeID;
        
        var loc = getNoQueryStringLocation();
        
        returnURL = escape(loc + "?kgid="+kgId+"&knowde="+knowdeId+"&t=communities");
        break;
      default:
        returnURL = escape(window.location.toString());
        break;
    }
  }
  
  // Save the current URL on Session for returning to
  SetSessionProperty("ReturnURL", returnURL);
  
  // Redirect the user to the Sign In / Sign Up Page 
   var currentLocation = window.location.href;
   var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
   window.location = hostURL + "SignInSignUp.aspx";
}

function getNoQueryStringLocation()
{
  var loc = window.location.toString();
  if (loc.indexOf('?') > -1)
    loc = loc.substring(0,loc.indexOf('?'));
  return loc;
}

function processRedirection()
{
  var rawQueryString = window.location.search.substring(1);
  
  if(rawQueryString.length > 0)
  {
    var queryStrings = rawQueryString.split("&");
           
    var actionName = queryStrings[0].split("=")[0];
    var actionValue = queryStrings[0].split("=")[1];
    
    if(actionName == "action")
    {
      switch(actionValue)
      {
        case "addToMyHK":
          var locatorParams = queryStrings[1].split(".");
          
          // This is to allow for the "p=" sequence and need to remove that 
          // from the categoryID
          var categoryID = locatorParams[0].split("=")[1];
          var pageNumber = locatorParams[1];
          var ownerKey   = locatorParams[2];
          var kgId       = locatorParams[3];
          
          LoadMapTabbedView();
          initialiseOverlays();
					//globalUpdateBubble = 'Home Page Load';
          break;
        default:
          LoadMapTabbedView(); 
          initialiseOverlays();
         // globalUpdateBubble = 'Home Page Load';
          break;
      }
    }
    else
    {
      LoadMapTabbedView(); 
      initialiseOverlays(); 
      //globalUpdateBubble = 'Home Page Load';
    }
  }
  else
  {
    LoadMapTabbedView();
    initialiseOverlays();
    //globalUpdateBubble = 'Home Page Load';
  }
}

function HomeLinkClicked()
{
	if(isAuthenticated())
	{
		SetSessionForHomeClick();
	  
		SetSessionProperty('Home_Link_Clicked', 'true');
	  
		//if (window.KGTabbedWindowsControl_SelectTabById)
		//	KGTabbedWindowsControl_SelectTabById('Indexed Documents');
	  
		// new default map will be load, clear old session
		SetSessionProperty('SelectedKnowdeSiblingInfo', '');	
	  
		WM_killCookie('category');
	  
	  
	    
	    var currentLocation = window.location.href;
        var hostURL;
        var currentPage;
        
        if(currentLocation.indexOf("orderSuccessful") > 0)
        {
          currentPage = currentLocation.substring(currentLocation.indexOf("orderSuccessful"));
          hostURL = currentLocation.substring(0, currentLocation.indexOf("orderSuccessful"));
        }
        else if (currentLocation.indexOf("orderFailed") > 0)
        {
          currentPage = currentLocation.substring(currentLocation.indexOf("orderFailed"));
          hostURL = currentLocation.substring(0, currentLocation.indexOf("orderFailed"));
        }
        else
        {
		    //var currentLocation = window.location.href;
		    currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
		    hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);		    
        }
        window.location = hostURL + 'home.aspx';
  }
  else
  {
		SetSessionForHomeClick();
		var currentLocation = window.location.href;
		var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
		var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
		window.location = hostURL + 'Welcome.aspx';
  }
}

function SetSessionForHomeClick()
{
  var keys = 'KG_RedirectFrom|Topics_SelectedTopicName|Topics_SelectedTopicGroupId|GenesTabMode|GenesSearch_PhraseName|CurrentKnowdeIDForTab|WebTabMode|WebSearch_PhraseName|Topics_HomeJustClicked|IndexedDocListMode|KGMapViewCollapsed';
	var values = 'HomeLinkClicked|null|-1||||||true|MyHyperknowledge|false';
  SetSessionProperty(keys, values, true);

}

function PageRedirect(page)
{
	var currentLocation = window.location.href;
	var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
	window.location = hostURL + page;
}

function UpdateBubble(action)
{ 
  globalUpdateBubble = null;
  if (action == 'Load TextView' && globalLastBubbleAction == 'Add Objective')
    return;
  
  if (action == 'Home Page Load' && globalLastBubbleAction == 'View Indexed Docs')
    return; //Don't want the page load to overwrite the Bubble
  
  if (action == 'Hover Map' && m_IsEditFromNewKnowde == true)
    return;
        
  if (action == 'Home Page Load')
  {   
    if (isAuthenticated() == true)
        action = 'Load Home In';
    else
        action = 'Load Home Out';
  }   
  
  if (action == 'Search Click')
  {
    if (isAuthenticated() == true)
        action = 'Search In';
    else
        action = 'Search Out';
  }
  
  if (action == 'Suggestions Open')
  {
    if (isAuthenticated() == true)
        action = 'Suggestion In';
    else
        action = 'Suggestion Out';
  }
  
  // Bubble control trigger 
  SetSessionProperty('TickerAction', action);
  globalLastBubbleAction = action;
  
  var authorBubble = document.getElementById("AuthorTour1");
	if(authorBubble != null)
	{
		if(authorBubble.style.display == "block")
		{
			if(action != "Objective Hover" && action != "How Hover" && action != "Why Hover" && action != "AddChildBoxHow Hover" && action != "AddChildBoxWhy Hover")
				DisplayHintMessage("Help");
		}
		else
		{
			DisplayHintMessage("Help");
		}
	}
	else
	{
		DisplayHintMessage("Help");
  }
}

function highlight_Link(e)
{
  if (!e) var e = window.event;
	var targ = e.target || e.srcElement;
	targ.style.color = "black";
	targ.style.textDecoration = "underline";
}

function unhighlight_Link(e, _color)
{
  if (!e) var e = window.event;
	var targ = e.target || e.srcElement;
	if(_color != 'false')
		targ.style.color = ""; //back to css default
	targ.style.textDecoration = "";
}

var globalHoverUpdateTimerDelay = 400;
var HoverTimerForBubble = null

function setUpBubble()
{
	// just for the cookies stuff
	if(WM_readCookie('TourBubble') == false)
	{
		WM_setCookie('TourBubble','on');
		ShowTourBubble();
	}
	else if(WM_readCookie('TourBubble') == "off")
	{
		HideTourBubble();
	}
	else if(WM_readCookie('TourBubble') == "on")
	{
		ShowTourBubble();
	}

  if (window.HideBubble)
    HideBubbleContainer();
}

// bubble code is for db to know what text to display
// e is the event or the element (element in _editoverride == true case)
// _editoverride is for map editing (slightly diff rules apply)
function bubbleMouseOver(e, _bubbleCode, _editOverride)
{	
	if(!window.HideBubble)
	  return;
	
	var Bubble = document.getElementById("KGBubbleControl1_HelpBubble");
  if(Bubble)
  {
		if(_bubbleCode != "How Hover" && _bubbleCode != "Why Hover")
			HideBubble('true');
		//browser type - for altered positioning
	  var ie = 'true'; 
	  if (navigator.appName != "Microsoft Internet Explorer")
		  ie = 'false';
		  
	  // if help is switched off... dont process.
	  var performBubble = document.getElementById("KGBubbleControl1_BubbleVisibilityContainer");
	  if(performBubble)
	  {
		  if(performBubble.style.display == "none")
		  {
				// dont process
			  return;
		  }
		  else
			{
				// if on, we need some logic for the tour / help combination. Hopefully only a temp sln.
				var authorBubble = document.getElementById("AuthorTour1");
				if(authorBubble != null)
				{
					if(_bubbleCode != null && _bubbleCode != "Add Objective" && _bubbleCode != "How Hover" && _bubbleCode != "Why Hover")
					{
						authorBubble.style.display = "none";
						if(_bubbleCode == "HideAuthor")
						{
							return;
						}
					}
				}
			} 
		}
		// some variables used for specific cases. 
		// Lots of different positioning types.
	  var force;
	  var targElement;
	  if (_editOverride == 'true')
		  targElement = e;
	  else
		  targElement = e.target||e.srcElement;
	  // find coordinates here...
	  var TopLeftPositionArray = findElementCoords(targElement);
	  var BottomRightPositionArray = findBRElementCoords(targElement);
	  var suggBox = "";
	  var borderOffset = 'false';
	  var autoScrollOffset = 'false';
	  if(ie == 'false')
	  {
		  //alternate browser precise positioning
		  if(_editOverride != 'true')
		  {
				switch(_bubbleCode)
				{
					// special cases that require specific coordinate adjustments
					case "Hover Search Item":
						suggBox = document.getElementById("KGSuggestionControl_Div_ID");
						TopLeftPositionArray[0] = suggBox.offsetLeft;
						TopLeftPositionArray[1] = e.clientY;
						BottomRightPositionArray[0] = suggBox.offsetLeft;
						BottomRightPositionArray[1] = e.clientY;	
						break
					case "Semantic Tree Hover":
						TopLeftPositionArray[0] = 250;
						TopLeftPositionArray[1] = 250;
						BottomRightPositionArray[0] = 250;
						BottomRightPositionArray[1] = 250;	
						break
					default:
						// for non-ie browsers... bubble appears at cursor
						TopLeftPositionArray[0] = e.clientX;
						TopLeftPositionArray[1] = e.clientY;
						BottomRightPositionArray[0] = e.clientX;
						BottomRightPositionArray[1] = e.clientY;	
						break;
				}
		  }
	  }
	  
	  // the text boxes on a knowde in edit
	  // some bubble in help wont appear when editing a knowde due to wanting the author bubble up.
	  var editBoxCheck = document.getElementById("MapViewTextBox");
	  
	  // update bubble will callback into the bubble code with correct action.
	  switch(_bubbleCode)
	  {
			// each case handles a different bubble event
			// there are coordinate / positioning adjustments for individual bubbles
		  case "Bookmark Hover":
			  if(ie == 'true')
			  {
				  borderOffset = 'true';
			  }
			  //stop the bubble from covering the menu by pushing it left to the refer icon
			  if (window.BookmarkingControl_GetBkmkText)
			  {
			    var topBkmkText = BookmarkingControl_GetBkmkText();
			    if (topBkmkText)
			    {
			      TopLeftPositionArray = findElementCoords(topBkmkText);
			      TopLeftPositionArray[1] = 50;
	          BottomRightPositionArray = findBRElementCoords(topBkmkText);
	          BottomRightPositionArray[1] = 72;
	          force = 'tr';
			    }
			  }
			  HoverTimerForBubble = setTimeout("UpdateBubble('Bookmark Hover')",globalHoverUpdateTimerDelay);
			  break;
		  case "Referral Hover":
			  if(ie == 'true')
			  {
				  borderOffset = 'true';
			  }
			  //stop the bubble from covering the menu by pushing it left to the bookmark text
			  if (window.BookmarkingControl_GetReferText)
			  {
			    var topReferText = BookmarkingControl_GetReferText();
			    if (topReferText)
			    {
			      var referHolder = topReferText.parentNode;
			      TopLeftPositionArray = findElementCoords(referHolder);
			      TopLeftPositionArray[1] = 50;
	          BottomRightPositionArray = findBRElementCoords(referHolder);
	          BottomRightPositionArray[1] = 72;
	          force = 'tr';
			    }
			  }
			  HoverTimerForBubble = setTimeout("UpdateBubble('Referral Hover')",globalHoverUpdateTimerDelay);
			  break;
		  case "Private Space Hover":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Private Space Hover')",globalHoverUpdateTimerDelay);
			  break;
			case "Web Coach Hover":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Web Coach Hover')",globalHoverUpdateTimerDelay);
			  break;
			case "SignInUp Hover":
			  HoverTimerForBubble = setTimeout("UpdateBubble('SignInUp Hover')",globalHoverUpdateTimerDelay);
			  break;
			case "SignOut Hover":
			  HoverTimerForBubble = setTimeout("UpdateBubble('SignOut Hover')",globalHoverUpdateTimerDelay);
			  break;
			case "HideAuthor":
			  return;
			  break;
			case "SignInUp Welcome":
				if(ie == 'true')
				{
					TopLeftPositionArray[1] = TopLeftPositionArray[1] + 100;
					BottomRightPositionArray[1] = BottomRightPositionArray[1] + 100;	
				}
			  HoverTimerForBubble = setTimeout("UpdateBubble('SignInUp Hover')",globalHoverUpdateTimerDelay);
			  break;
			case "Semantic Tree Title":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Semantic Tree Title')",globalHoverUpdateTimerDelay);
			  break;
			case "PDF Hover":
				force = 'tr';
			  HoverTimerForBubble = setTimeout("UpdateBubble('PDF Hover')",globalHoverUpdateTimerDelay);
			  break;
			case "Print Hover":
				force = 'tr';
			  HoverTimerForBubble = setTimeout("UpdateBubble('Print Hover')",globalHoverUpdateTimerDelay);
			  break;
			case "Key Concepts Hover":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Key Concepts Hover')",globalHoverUpdateTimerDelay);
			  break;
			case "Single View Hover":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Single View Hover')",globalHoverUpdateTimerDelay);
			  break;
			case "Split View Hover":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Split View Hover')",globalHoverUpdateTimerDelay);
			  break;
			case "Reset Hover":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Reset Hover')",globalHoverUpdateTimerDelay);
			  break;
		  case "Index Docs Hover":
			  if(ie == 'false' && _editOverride != 'true')
			  {
				  TopLeftPositionArray[0] = (screen.availWidth / 10) * 6;
				  BottomRightPositionArray[0] = TopLeftPositionArray[0];
				  // for corner position (pointer direction)
				  force = 'bl';
			  }
			  HoverTimerForBubble = setTimeout("UpdateBubble('Index Docs Hover')",globalHoverUpdateTimerDelay);
			  break;
		  case "Indexed Docs Hover":
		  if(ie == 'false' && _editOverride != 'true')
			  {
				  TopLeftPositionArray[0] = (screen.availWidth / 10) * 6;
				  BottomRightPositionArray[0] = TopLeftPositionArray[0];
				  force = 'bl';
			  }
			  HoverTimerForBubble = setTimeout("UpdateBubble('Indexed Docs Hover')",globalHoverUpdateTimerDelay);
			  break;
		  case "Search Click":
				suggBox = document.getElementById("KGSuggestionControl_Div_ID");
				if(suggBox.className == "OverlayPosition")
				{
					return;
				}
			  HoverTimerForBubble = setTimeout("UpdateBubble('Search Click')",globalHoverUpdateTimerDelay);
			  break;
		  case "Hover Search":
				suggBox = document.getElementById("KGSuggestionControl_Div_ID");
				if(suggBox.className == "OverlayPosition")
				{
					return;
				}
			  HoverTimerForBubble = setTimeout("UpdateBubble('Hover Search')",globalHoverUpdateTimerDelay);
			  break;
			case "Hover Search Item":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Hover Search Item')",globalHoverUpdateTimerDelay);
			  break;
			case "Semantic Tree Hover":
				TopLeftPositionArray[0] = 250;
				TopLeftPositionArray[1] = 250;
				BottomRightPositionArray[0] = 250;
				BottomRightPositionArray[1] = 250;	
			  HoverTimerForBubble = setTimeout("UpdateBubble('Semantic Tree Open')",globalHoverUpdateTimerDelay);
			  break;
		  case "Create KG":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Create KG')",globalHoverUpdateTimerDelay);
			  break;
		  case "View Indexed Editing":
			  HoverTimerForBubble = setTimeout("UpdateBubble('View Indexed Editing')",globalHoverUpdateTimerDelay);
			  break;
		  case "Load Profile Self":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Load Profile Self')",globalHoverUpdateTimerDelay);
			  break;
		  case "Load Profile Other":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Load Profile Other')",globalHoverUpdateTimerDelay);
			  break;
			case "Category Hover":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Category Hover')",globalHoverUpdateTimerDelay);
			  break;
			case "MyHK Hover":
			  HoverTimerForBubble = setTimeout("UpdateBubble('MyHK Hover')",globalHoverUpdateTimerDelay);
			  break;
		  case "Show Semantic Tree Other":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Show Semantic Tree Other')",globalHoverUpdateTimerDelay);
			  break;
		  case "Objective Hover":
				if(authorBubble)
					if(authorBubble.style.display == "block")
						return;
				if(editBoxCheck != null)
					if(editBoxCheck.style.visibility == "visible" && editBoxCheck.style.display == "block")
						return;
				HideBubble('true');
			  autoScrollOffset = 'true';
			  HoverTimerForBubble = setTimeout("UpdateBubble('Objective Hover')",globalHoverUpdateTimerDelay);
			  break;
		  case "How Hover":
				if(authorBubble)
					if(authorBubble.style.display == "block")
						return;
				if(editBoxCheck != null)
					if(editBoxCheck.style.visibility == "visible" && editBoxCheck.style.display == "block")
						return;
				HideBubble('true');
			  autoScrollOffset = 'true';
			  HoverTimerForBubble = setTimeout("UpdateBubble('How Hover')",globalHoverUpdateTimerDelay);
			  break;
		  case "Why Hover":
				if(authorBubble)
					if(authorBubble.style.display == "block")
						return;
				if(editBoxCheck != null)
					if(editBoxCheck.style.visibility == "visible" && editBoxCheck.style.display == "block")
						return;
				HideBubble('true');
			  autoScrollOffset = 'true';
			  HoverTimerForBubble = setTimeout("UpdateBubble('Why Hover')",globalHoverUpdateTimerDelay);
			  break;
		  case "AddChildBoxHow Hover":	
				if(authorBubble)
					if(authorBubble.style.display == "block")
						return;
				if(editBoxCheck != null)
					if(editBoxCheck.style.visibility == "visible" && editBoxCheck.style.display == "block")
						return;
				HideBubble('true');
			  autoScrollOffset = 'true';
			  HoverTimerForBubble = setTimeout("UpdateBubble('AddChildBoxHow Hover')",globalHoverUpdateTimerDelay);
			  break;
		  case "AddChildBoxWhy Hover":
				if(authorBubble)
					if(authorBubble.style.display == "block")
						return;
				if(editBoxCheck != null)
					if(editBoxCheck.style.visibility == "visible" && editBoxCheck.style.display == "block")
						return;
				HideBubble('true');
			  autoScrollOffset = 'true';
			  HoverTimerForBubble = setTimeout("UpdateBubble('AddChildBoxWhy Hover')",globalHoverUpdateTimerDelay);
			  break;
		  case "WhatIs Highlighted":
			  autoScrollOffset = 'true';
			  HoverTimerForBubble = setTimeout("UpdateBubble('WhatIs Highlighted')",globalHoverUpdateTimerDelay);
			  break;
		  case "What Highlighted":
			  autoScrollOffset = 'true';
			  HoverTimerForBubble = setTimeout("UpdateBubble('What Highlighted')",globalHoverUpdateTimerDelay);
			  break;
		  case "Add Objective":
				authorBubble.style.display = "block";
				HideBubble();
				return;
		  case "Add MyHK":
			  HoverTimerForBubble = setTimeout("UpdateBubble('Add MyHK')",globalHoverUpdateTimerDelay);
			  break;
	  }
	  // updateBubblePosition
	  updateBubblePosition(TopLeftPositionArray, BottomRightPositionArray, borderOffset, autoScrollOffset, force, ie);
	}
}

var globalHideBubbleTime;
				
function bubbleMouseOut(e)
{
	// clear hover timeout & hide the bubble.
	clearTimeout(HoverTimerForBubble);
	if(window.HideBubble)
	  globalHideBubbleTime = setTimeout("HideBubble('true');", globalHoverUpdateTimerDelay);
}

var globalBubbleBottom = "false";

function updateBubblePosition(_TLPosition, _BRPosition, _borderOffset, _autoScrollOffset, _force, _ie)
{
	//debugger;
	HideBubble();
	var leftOffset = 0;
	var rightOffset = 0;
	var mapViewControlDiv = document.getElementById("main-window"); 
	if(mapViewControlDiv)
	{
		leftOffset = mapViewControlDiv.scrollLeft;
	}
	if(_autoScrollOffset == 'false')
		leftOffset = 0;
	var Bubble = document.getElementById("KGBubbleControl1_HelpBubble");
	var BubblePointer = document.getElementById("KGBubbleControl1_bubblePointer");
	// find width & height midpoint.
	var horizontalMidPoint = (_TLPosition[0] + _BRPosition[0]) / 2;
	var verticalMidPoint = (_TLPosition[1] + _BRPosition[1]) / 2;
	// find what screen quarter that mid-point is in
	var screenHorizontalMidPoint = screen.availWidth / 2;
	var screenVerticalMidPoint = screen.availHeight / 2;
	var route;
	
	
	if(_force)
	{
		route = _force;
		if(route == 'bl')
			if(verticalMidPoint <= screenVerticalMidPoint)
				route = 'tl';
	}
	else
	{
		// load correct bubble shape for that quarter
		if(horizontalMidPoint >= screenHorizontalMidPoint)
		{
			if(verticalMidPoint <= screenVerticalMidPoint)
			{
				//top right
				route = 'tr';
			}
			else
			{
				//bottom right
				if(_force != 'bl')
					route = 'br';
			}
		}
		else
		{
			if(verticalMidPoint <= screenVerticalMidPoint)
			{
				//top left
				route = 'tl';
			}
			else
			{
				//bottom left
				route = 'bl';
			}
		}
	}

	switch(route)
	{
		case 'tr':
			// top right quarter
			var bubbleHeightOffset = 20 + _BRPosition[1];
			Bubble.style.left = _TLPosition[0] - 310 - leftOffset;
			if(_borderOffset == 'true')
				Bubble.style.left = _TLPosition[0] - 310 + 100;
			Bubble.style.top = bubbleHeightOffset;
			globalBubbleBottom = "false";
			break;
		case 'br':
			// bottom right quarter
			var bubbleHeightOffset = _TLPosition[1] - 20;
			Bubble.style.left = _TLPosition[0] - 310 - leftOffset;
			Bubble.style.top = bubbleHeightOffset;
			globalBubbleBottom = "true";
			break;
		case 'tl':
			// top left quarter
			var bubbleHeightOffset = 20 + _BRPosition[1];
			Bubble.style.left = _BRPosition[0] + 10 - leftOffset;
			if(_borderOffset == 'true')
				Bubble.style.left = _BRPosition[0] + 10 + 100;
			Bubble.style.top = bubbleHeightOffset;
			globalBubbleBottom = "false";
			break;
		case 'bl':
			// bottom left quarter
			var bubbleHeightOffset = _TLPosition[1] - 20;
			Bubble.style.left = _BRPosition[0] + 10 - leftOffset;
			Bubble.style.top = bubbleHeightOffset;
			globalBubbleBottom = "true";
			break;
	}
}

function importScript(_fileName)
{
  var tag = document.createElement("script");
  tag.type="text/javascript";
  tag.src = 'JavaScript/' + _fileName;
  document.body.appendChild(tag);
}

function WM_setCookie(name, value, hours, path, domain, secure) 
{
	if (WM_acceptsCookies) 
	{ 
		// Don't waste your time if the browser doesn't accept cookies.
		var not_NN2 = (navigator && navigator.appName 
		       && (navigator.appName == 'Netscape') 
		       && navigator.appVersion 
		       && (parseInt(navigator.appVersion) == 2))?false:true;

		if(hours && not_NN2) 
		{ // NN2 cannot handle Dates, so skip this part
	    if ( (typeof(hours) == 'string') && Date.parse(hours) ) 
	    {
				// already a Date string
				var numHours = hours;
	    } 
	    else if (typeof(hours) == 'number') 
	    { 
				// calculate Date from number of hours
				var numHours = (new Date((new Date()).getTime() + hours*3600000)).toGMTString();
	    }
		}
		document.cookie = name + '=' + escape(value) + ((numHours)?(';expires=' + numHours):'') + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:'') + ((secure && (secure == true))?'; secure':''); // Set the cookie, adding any parameters that were specified.  
	}
} // WM_setCookie

function WM_killCookie(name, path, domain) {
  var theValue = WM_readCookie(name); // We need the value to kill the cookie
  if(theValue) {
      document.cookie = name + '=' + theValue + '; expires=Fri, 13-Apr-1970 00:00:00 GMT' + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:''); // set an already-expired cookie
  }
} // WM_killCookie

function helpBubbleToggle(e)

{

      try

      {

            var toggleElement = document.getElementById("BubbleTourToggle");

            var Element;

 

            switch(toggleElement.className)

            {

                  case "TourBubbleOn" :

                        toggleElement.className = "TourBubbleOff";

                        WM_setCookie('TourBubble','off', m_helpCookieExpiration);

                        ProceedWithTour();

                        break;

                  case "TourBubbleOff" :

                        toggleElement.className = "TourBubbleOn";

                        WM_setCookie('TourBubble','on', m_helpCookieExpiration);

                        ProceedWithTour();

                        break;

            }

      }

      catch(e)

      {

            alert("Exception in helpBubbleToggle(): " + e);

      }

}


function ShowTourBubble()
{
  var toggle = document.getElementById("BubbleTourToggle");
  if (toggle)
  {
    toggle.className = "TourBubbleOn";
  }
}
		
function HideTourBubble()
{
  var toggle = document.getElementById("BubbleTourToggle");
  if (toggle)
  {
    toggle.className = "TourBubbleOff";
  }
}

function TourBackOneStep(_stepToGoTo)
{
  // need to take the tour back one step
  try
  {
    switch(_stepToGoTo)
    {
      case 1:
				WM_setCookie('TourStep', 'step1');
				ProceedWithTour(true);
				break;      

      case 2:
				WM_setCookie('TourStep', 'step2');
				ProceedWithTour(true);
				break; 
				
      case 3:
				WM_setCookie('TourStep', 'step3');
				ProceedWithTour(true);
				break; 
				
      case 4:
				WM_setCookie('TourStep', 'step4');
				ProceedWithTour(true);
				break; 								
				
      case 5:
				WM_setCookie('TourStep', 'step5');
				ProceedWithTour(true);
				break; 				

      case 6:
				WM_setCookie('TourStep', 'step6');
				ProceedWithTour(true);
				break;
				
			case 7:
				WM_setCookie('TourStep', 'step7');
				ProceedWithTour(true);
				break;
				
			case 8:
				WM_setCookie('TourStep', 'step8');
				ProceedWithTour(true);
				break;
    
    }
  }
  catch(e)
	{
		alert("Exception in TourBackOneStep(): " + e);
	}
}

function UpdateTour(_stepCompleted)
{
	try
	{
		if(WM_readCookie('TourBubble') == "on")
		{
			var stepNumber = WM_readCookie('TourStep');
			switch(_stepCompleted)
			{
				case 1:
					if(stepNumber == "step1")
					{
						WM_setCookie('TourStep', 'step2');
						ProceedWithTour(false);
					}
					else if(stepNumber == "step2")
					{
						WM_setCookie('TourStep', 'step3');
						ProceedWithTour(false);
					}
					break;
				case 2:
					if(stepNumber == "step2")
					{
						WM_setCookie('TourStep', 'step3');
						ProceedWithTour(false);
					}
					break;
				case 3:
					if(stepNumber == "step3")
					{
						WM_setCookie('TourStep', 'step4');
						ProceedWithTour(false);
					}
					break;
				case 4:
					if(stepNumber == "step4")
					{
						WM_setCookie('TourStep', 'step5');
						ProceedWithTour(false);
					}
					break;
				case 5:
					if(stepNumber == "step5")
					{
						WM_setCookie('TourStep', 'step6');
						ProceedWithTour(false);
					}
					break;
				case 6:
					if(stepNumber == "step6")
					{
						WM_setCookie('TourStep', 'step7');
						ProceedWithTour(false);
					}
					break;
				case 7:
					if(stepNumber == "step7")
					{
						WM_setCookie('TourStep', 'step8');
						ProceedWithTour(false);
					}
					break;
				case 8:
					if(stepNumber == "step8")
					{
						WM_setCookie('TourStep', 'step9');
						ProceedWithTour(false);
					}
					break;
				case 8:
					if(stepNumber == "step8")
					{
						WM_setCookie('TourStep', 'step1');
						ProceedWithTour(false);
					}
					break;
			}
		}
	}
	catch(e)
	{
		alert("Exception in UpdateTour(): " + e);
	}
}

function ProceedWithTour(_bBack)
{
	try
	{
		var currentLocation = window.location.href;
		var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
		var previousBubble;
		var tourBubble;
		var authorBubble = document.getElementById("AuthorTour1");
		var stepNumber = WM_readCookie('TourStep');
		if(currentPage == "" || currentPage.toLowerCase().match("home") == "home")
		{
			if(m_bEditable == true && Map_TextEditOnly == 0)
			{
				// Hide non author bubbles
				switch(stepNumber)
				{
					case "step1":
					  if ( _bBack == false )
  						previousBubble = document.getElementById("Tour7");
  				  else
  						previousBubble = document.getElementById("Tour2");  				  
						previousBubble.style.display = "none";
						tourBubble = document.getElementById("Tour1");
						tourBubble.style.display = "none";
						break;
					case "step2":
					  if ( _bBack == false )
  						previousBubble = document.getElementById("Tour1");
  				  else
  						previousBubble = document.getElementById("Tour3");  				  
						previousBubble.style.display = "none";
						tourBubble = document.getElementById("Tour2");
						tourBubble.style.display = "none";
						break;
					case "step3":
					  if ( _bBack == false )
  						previousBubble = document.getElementById("Tour2");
  				  else
  						previousBubble = document.getElementById("Tour4");  				  
						previousBubble.style.display = "none";
						tourBubble = document.getElementById("Tour3");
						tourBubble.style.display = "none";
						break;
					case "step4":
					  if ( _bBack == false )
  						previousBubble = document.getElementById("Tour3");
  				  else
  						previousBubble = document.getElementById("Tour5");  				  
						previousBubble.style.display = "none";
						tourBubble = document.getElementById("Tour4");
						tourBubble.style.display = "none";
						break;
					case "step5":
					  if ( _bBack == false )
  						previousBubble = document.getElementById("Tour4");
  				  else
  						previousBubble = document.getElementById("Tour6");  				  
						previousBubble.style.display = "none";
						tourBubble = document.getElementById("Tour5");
						tourBubble.style.display = "none";
						break;
					case "step6":
					  if ( _bBack == false )
  						previousBubble = document.getElementById("Tour5");
  				  else
  						previousBubble = document.getElementById("Tour7");  				  
						previousBubble.style.display = "none";
						tourBubble = document.getElementById("Tour6");
						tourBubble.style.display = "none";
						break;
					case "step7":
					  if ( _bBack == false )
  						previousBubble = document.getElementById("Tour6");
  				  else
  						previousBubble = document.getElementById("Tour8");  				  
						previousBubble.style.display = "none";
						tourBubble = document.getElementById("Tour7");
						tourBubble.style.display = "none";
						break;
					case "step8":
					  if ( _bBack == false )
  						previousBubble = document.getElementById("Tour7");
  				  else
  						previousBubble = document.getElementById("Tour9");  				  
						previousBubble.style.display = "none";
						tourBubble = document.getElementById("Tour8");
						tourBubble.style.display = "none";
						break;
					case "step9":
						previousBubble = document.getElementById("Tour6");
						previousBubble.style.display = "none";
						tourBubble = document.getElementById("Tour9");
						tourBubble.style.display = "none";
						break;
					/*case "step8":
						previousBubble = document.getElementById("Tour7");
						previousBubble.style.display = "none";
						tourBubble = document.getElementById("Tour8");
						tourBubble.style.display = "none";
						break;*/
					default:
						tourBubble = document.getElementById("Tour1");
						tourBubble.style.display = "none";
						WM_setCookie('TourStep','step1');
						break;
				}
				if(WM_readCookie('TourBubble') == "on")
				{
					// Show the authoring bubble
					authorBubble.style.display = "block";
					// update first author cookie (first new kg)
					if(currentLocation.toLowerCase().match("createnewkg") == "createnewkg" && WM_readCookie('FirstAuthor') != "true")
					{
						WM_setCookie('FirstAuthor','true', m_helpCookieExpiration);
					}
				}
				else
				{
					// if creating a new gene turn tour on
					if(currentLocation.toLowerCase().match("createnewkg") == "createnewkg" && WM_readCookie('FirstAuthor') != "true")
					{
						WM_setCookie('FirstAuthor','true', m_helpCookieExpiration);
						var toggle = document.getElementById("BubbleTourToggle");
						if (toggle)
						{
							authorBubble.style.display = "block";
							toggle.className = "TourBubbleOn";
							WM_setCookie('TourBubble','on', m_helpCookieExpiration);
						}
					}
					else
					{
						// Hide the authoring bubble
						authorBubble.style.display = "none";
					}
				}
			}
			else
			{
				authorBubble.style.display = "none";
				if(WM_readCookie('TourBubble') == "on")
				{
					// read cookie for Tour Steps
					switch(stepNumber)
					{
						case "step1": 
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour7");
  				    else
  						  previousBubble = document.getElementById("Tour2");  				  
							previousBubble.style.display = "none";				
							tourBubble = document.getElementById("Tour1");
							tourBubble.style.display = "block";
							break;
						case "step2":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour1");
  				    else
  						  previousBubble = document.getElementById("Tour3");  				  
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour2");
							tourBubble.style.display = "block";
							break;
						case "step3":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour2");
  				    else
  						  previousBubble = document.getElementById("Tour4");  				  
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour3");
							tourBubble.style.display = "block";
							break;
						case "step4":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour3");
  				    else
  						  previousBubble = document.getElementById("Tour5");  				  
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour4");
							tourBubble.style.display = "block";
							break;
						case "step5":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour4");
  				    else
  						  previousBubble = document.getElementById("Tour6");  				  
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour5");
							tourBubble.style.display = "block";
							break;
						case "step6":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour5");
  				    else
  						  previousBubble = document.getElementById("Tour7");  				  
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour6");
							tourBubble.style.display = "block";
							break;
						case "step7":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour6");
  				    else
  						  previousBubble = document.getElementById("Tour8");  				  
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour7");
							tourBubble.style.display = "block";
							break;
						case "step8":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour7");
  				    else
  						  previousBubble = document.getElementById("Tour9");  				  
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour8");
							tourBubble.style.display = "block";
							break;
						case "step9":
							previousBubble = document.getElementById("Tour8");
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour9");
							tourBubble.style.display = "block";
							break;
						/*case "step8":
							previousBubble = document.getElementById("Tour7");
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour8");
							tourBubble.style.display = "block";
							break;*/
						default:
							tourBubble = document.getElementById("Tour1");
							tourBubble.style.display = "block";
							WM_setCookie('TourStep','step1');
							break;
					}
				}
				else
				{
					// read cookie for Tour Steps
					switch(stepNumber)
					{
						case "step1": 
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour7");
  				    else
  						  previousBubble = document.getElementById("Tour2");  				  
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour1");
							tourBubble.style.display = "none";
							break;
						case "step2":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour1");
  				    else
  						  previousBubble = document.getElementById("Tour3");  				  
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour2");
							tourBubble.style.display = "none";
							break;
						case "step3":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour2");
  				    else
  						  previousBubble = document.getElementById("Tour4");  				  
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour3");
							tourBubble.style.display = "none";
							break;
						case "step4":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour3");
  				    else
  						  previousBubble = document.getElementById("Tour5");  				  
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour4");
							tourBubble.style.display = "none";
							break;
						case "step5":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour4");
  				    else
  						  previousBubble = document.getElementById("Tour6");  				  						
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour5");
							tourBubble.style.display = "none";
							break;
						case "step6":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour5");
  				    else
  						  previousBubble = document.getElementById("Tour7");  				  						
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour6");
							tourBubble.style.display = "none";
							break;
						case "step7":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour6");
  				    else
  						  previousBubble = document.getElementById("Tour8");  				  						
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour7");
							tourBubble.style.display = "none";
							break;
						case "step8":
					    if ( _bBack == false )
  						  previousBubble = document.getElementById("Tour7");
  				    else
  						  previousBubble = document.getElementById("Tour9");  				  						
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour8");
							tourBubble.style.display = "none";
							break;
						case "step9":
							previousBubble = document.getElementById("Tour8");
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour9");
							tourBubble.style.display = "none";
							tourBubble = document.getElementById("Tour1");
							tourBubble.style.display = "none";
							WM_setCookie('TourStep', 'step1');
							break;
						/*case "step8":
							previousBubble = document.getElementById("Tour7");
							previousBubble.style.display = "none";
							tourBubble = document.getElementById("Tour8");
							tourBubble.style.display = "none";
							tourBubble = document.getElementById("Tour1");
							tourBubble.style.display = "none";
							WM_setCookie('TourStep', 'step1');
							break;*/
						default:
							tourBubble = document.getElementById("Tour1");
							tourBubble.style.display = "none";
							WM_setCookie('TourStep','step1');
							break;
					}
				}
			}
		}
	}
	catch(e)
	{
		alert("Exception in ProceedWithTour(): " + e);
	}
}

// parent.insertAdjacentElement is an IE method, this is w3
function InsertAdjacentElement(_parent, _where, _element) 
{
  if (_parent.insertAdjacentElement) // may aswell use the IE method if we can
    return _parent.insertAdjacentElement(_where, _element);
  
  switch (_where.toLowerCase()) 
  {
	  case "beforebegin":
		  _parent.parentNode.insertBefore(_element, _parent);
		  break;
	  case "afterbegin":
		  _parent.insertBefore(_element, _parent.firstChild);
		  break;
	  case "beforeend":
		  _parent.appendChild(_element);
		  break;
	  case "afterend":
		  _parent.parentNode.insertBefore(_element, _parent.nextSibling);
		  break;
  }	
  return _element;
}

// Firefox, Opera and Safari include text nodes (nodeType == 3) after some elements (e.g. before and after divs for the break)
function hkNextSibling(_element)
{
  var ns = _element.nextSibling;
  while (ns && ns.nodeType == 3)
    ns = ns.nextSibling;
  return ns;
}

function hkFirstChild(_element)
{
  var ns = _element.firstChild;
  while (ns && ns.nodeType == 3)
    ns = ns.nextSibling;
  return ns;
}

function hkLastChild(_element)
{
  var ns = _element.lastChild;
  while (ns && ns.nodeType == 3)
    ns = ns.previousSibling;
  return ns;
}

function CancelBubble(e)
{
  e = e || window.event;
  if (e)
  {
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
  }
  //else
    //alert('cancel bubble but no event');
}

function GetInnerText(_element)
{
  //var txt = verb.textContent || verb.innerText; //this won't work if the innerText is an empty string
  if (_element.textContent || _element.textContent == '')
    return _element.textContent;
  else
    return _element.innerText;
}

function SetInnerText(_element, _txt)
{
  if (_element.textContent || _element.textContent == '')
    _element.textContent = _txt;
  else
    _element.innerText = _txt;
}

function GetPixelWidth(_element)
{
  if (_element.pixelWidth) // ie only
    return _element.pixelWidth;
    
  var width = _element.style.width;
  if (width.indexOf('px') > -1)
    return parseInt(width);
    
  return _element.offsetWidth;
}

function GetPixelHeight(_element)
{
  if (_element.pixelHeight) // ie only
    return _element.pixelHeight;
    
  var height = _element.style.height;
  if (height.indexOf('px') > -1)
    return parseInt(height);
    
  return _element.offsetHeight;
}

function GetPixelLeft(_element)
{
  if (_element.pixelLeft) // ie only
    return _element.pixelLeft;
    
  var left = _element.style.left;
  if (left.indexOf('px') > -1)
    return parseInt(left);
    
  return _element.offsetLeft;
}

function GetPixelTop(_element)
{
  if (_element.pixelTop) // ie only
    return _element.pixelTop;
    
  var top = _element.style.top;
  if (top.indexOf('px') > -1)
    return parseInt(top);
    
  return _element.offsetTop;
}

function SetOuterHtml(_el, _html)
{
  if (_el.outerHTML)
    _el.outerHTML = _html;
  else
  {
    var newEl = document.createElement("div");
    newEl.innerHTML = _html;
    _el.parentNode.replaceChild(newEl.firstChild, _el);
  }
}


function purge(d) 
{
    var a = d.attributes, x, l, n;
    if (a) 
    {
        l = a.length;
        for (var x = 0; x < l; x += 1) 
        {
            n = a[x].name;
            if (typeof d[n] == 'function') 
            {
                d[n] = null;
            }
        }
    }
    a = d.childNodes;
    if (a) 
    {
        l = a.length;
        for (x = 0; x < l; x += 1) 
        {
            purge(d.childNodes[x]);
        }
    }
}
function HideDropLists()
{
  // retrieve and hide all droplists.
  var droplist = document.getElementsByTagName("SELECT");
  for(var num=0;num<droplist.length;num++)
  {
	  //only hide the visible boxes
	  if(droplist[num].className == "list_dropList")
		  droplist[num].style.display = "none";
  }
}

function ShowDropLists()
{
  // retrieve and show all droplists.
  var droplist = document.getElementsByTagName("SELECT");
  for(var num=0;num<droplist.length;num++)
  {
    if(droplist[num].className == "list_dropList")
	    droplist[num].style.display = "inline";
  }
}

function HCatDiv_MouseEnter()
{
  var editFrameDiv = document.getElementById('TextViewEditFrameDiv');
  if(editFrameDiv != null && window.TextViewControl_onMouseOut)
  {
    TextViewControl_onMouseOut(); // auto save
  }
}

function SiteHeaderDiv_MouseEnter()
{
  var editFrameDiv = document.getElementById('TextViewEditFrameDiv');
  if(editFrameDiv != null && window.TextViewControl_onMouseOut)
  {
    TextViewControl_onMouseOut(); //auto save
  }
}

function UpdateMapViewForApp(_knowdeid)
{   
	global_reloadApp = "false";
	
	var keys = 'SelectedKGID|MapViewDisplayMode|ReloadApplicationControl';
	var values = _knowdeid + '|KGMapView|false';
  SetSessionProperty(keys, values, true);

  //SetSessionProperty('SelectedKGID', _knowdeid);
  //SetSessionProperty('MapViewDisplayMode', 'KGMapView');
  //SetSessionProperty('ReloadApplicationControl', 'false');
  MapViewControl1_CallbackTrigger();
  //KGTabbedWindowsControl_CallbackTrigger('KnowdeSelected');
  DoExpandMapViewPane("fully");
}

function RepopulateProfilePageKGLists()
{
  // repopulate the KGUserObjectSummaryControl
  if (window.Pfl_KGUserObjectSummaryControl_CallbackTrigger)
    Pfl_KGUserObjectSummaryControl_CallbackTrigger('action=refresh|kgId=0');
  
  // repopulate the KGMyKnowledgeControl
  if (window.Pfl_KGMyKnowledgeControl_CallbackTrigger)
    Pfl_KGMyKnowledgeControl_CallbackTrigger('Action=repopulate');
}

function CheckSessionTimeout()
{
  // Check for cookie which tells us if the session has expired
  var cookie_content = WM_readCookie('sessionExpired');
  
  if(cookie_content != null && cookie_content.length > 0)
  {
    // clear cookies
    WM_setCookie('SignedIn', "");
    WM_setCookie('sessionExpired', "");
    WM_killCookie('SignedIn')
    WM_killCookie('sessionExpired');
    window.location = "SessionTimeout.aspx";
    return true;
  }
  else
    return false;
}

function RSS_Check()
{
	//browser check
	if(navigator.appVersion.match("MSIE 6") == "MSIE 6" && navigator.appName == "Microsoft Internet Explorer")
	{
		window.location = "RSSReaderRequired.aspx";
	}
	else
	{
		window.location = "http://blogs.knowledgegenes.com/home/atom.xml";
	}
}

function delayedRedirect(_path, _delay)
{
  setTimeout("window.location = '" + _path + "';", _delay);
}

function CallbackTrigger_Wrapped(_args, _cbReference)
{
  var args = _args;
  if(_cbReference != null && _cbReference != "")
    eval(_cbReference);
}

function BkmkCheckStatus()
{
  // if a map and/or profile is visible (returns an array with both variables)
  var mapVisible = false; 
  var profileVisible = false; 
  var profileTab;
  
  // if it's the options.aspx page, a profile is visible and a map isn't
  // if it's the home page, a map and/or profile may be visible
  // if it's any other page, neither a map nor a profile will be visible
  
  var currentLocation = window.location.href;
	var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
  
	if (currentPage.indexOf('home') > -1 || currentPage.length == 0)
	{
	  var mapCollapsed;
	  if (window.Active_KGID && window.Active_KGName) //otherwise either there's no map or the map hasn't loaded yet
	  {
	    mapCollapsed = PaneBStatus(); //if false or null then map is visible
	    if (!mapCollapsed) 
	      mapVisible = true;
	  }
	  
    // profile is visible if the tabbed windows are visible and the selected tab is the community tab
    // first check the selected tab - it's easier and usually not true, so we don't have to 
    if (globalVisibleTab == "TSC_myprofile")
      profileTab = "Profile";
    else if (globalVisibleTab == "TSC_communities" && globalCommunityVisibleTab == "User")
      profileTab = "Community";
    else
      profileTab = null; // selected tab isn't a profile tab
    
    // now check whether the tab is hidden by the splitter
    if (profileTab)
    {
      if (mapCollapsed) // if map is collapsed, tabbed windows must be visible, then can avoid more splitter checks
        profileVisible = true;
      else
      {
        if (Splitter1.Panes)
        {
          var PaneC = Splitter1.Panes[1]
          if(PaneC.element.style.display != "none") //copied this check from SplitterPaneHandler.js SplitterControl
            profileVisible = true;
        }
      }
    }
	}
	
	return [mapVisible,profileVisible];

}

var m_bkmkMenu;
function BookmarkingOptionControl_ShowMenu_Wrapped(_siteName, _bkmkUrl, _bkmkId, _mapVisible, _profileVisible, _controlDivId, _siteRowId, _mapRowId, _knowdeRowId, _userRowId)
{
  BkmkHighlightTopText(_bkmkUrl);
  if (!m_bkmkMenu)
    m_bkmkMenu = document.getElementById(_controlDivId);
  
  if(m_bkmkMenu)
  {
    var siteRow = document.getElementById(_siteRowId);
    siteRow.title = BkmkGetTooltip('site', _siteName)
    // show/hide the map row
    var mapRow = document.getElementById(_mapRowId);
    if (mapRow)
    {
      if (_mapVisible)
      {
        mapRow.style.display = ''; //default to table row display
        mapRow.title = BkmkGetTooltip('Knowledge Gene', _siteName)
      }
      else
        mapRow.style.display = 'none';
    }

    // show/hide the knowde row
    var knowdeRow = document.getElementById(_knowdeRowId);
    if (knowdeRow)
    {
      if (_mapVisible  && currentMapViewType == MAP_TYPE_KNOWDE)
      {
        knowdeRow.style.display = ''; //default to table row display
        knowdeRow.title = BkmkGetTooltip('Knowde', _siteName)
      }
      else
        knowdeRow.style.display = 'none';
    }
            
    // show/hide the user row
    var userRow = document.getElementById(_userRowId);
    if (userRow)
    {
      if (_profileVisible)
      {
        // get the member name
        var memberNameCtlId;
        if (globalVisibleTab == "TSC_communities" && window.Com_KGProfileHeaderControl_GetMemberNameControlId)
          memberNameCtlId = Com_KGProfileHeaderControl_GetMemberNameControlId();
        else if (globalVisibleTab == "TSC_myprofile" && window.Pfl_KGProfileHeaderControl_GetMemberNameControlId)
          memberNameCtlId = Pfl_KGProfileHeaderControl_GetMemberNameControlId();
          
        if (memberNameCtlId)
        {
          var memberNameCtl = document.getElementById(memberNameCtlId);
          if (memberNameCtl)
          {
            var name = GetInnerText(memberNameCtl);
            m_bkmkMenu.userName = name;
            //SetInnerText(userRow.cells[0], name);
          
            userRow.style.display = ''; //default to table row display
            userRow.title = BkmkGetTooltip('person', _siteName)
          }
          else // memberNameCtl hasn't loaded yet
            userRow.style.display = 'none';
        }
        else // memberNameCtl hasn't loaded yet
          userRow.style.display = 'none';
      }
      else // not profileVisible
        userRow.style.display = 'none';
    }
  
    m_bkmkMenu.bkmkUrl = _bkmkUrl; //save the bookmarking url (e.g. ...facebook.com...) for use in the onclick methods
    
    //position the menu
    
    // top of the menu lines up with the bottom of the hcc
    var topText = BookmarkingControl_GetReferText();
    if (topText)
    {
      var y = findBRElementCoords(topText)[1] + 2;
      m_bkmkMenu.style.top = y + 'px';
    }
    
    //left of menu lines up with bookmarker icon
    var x;
    bkmk = document.getElementById(_bkmkId);
    if (bkmk)
    {
      x = findElementCoords(bkmk)[0]; 
      m_bkmkMenu.style.left = x + 'px';
    }
    
    // show the menu - show before maxX for clientWidth
    m_bkmkMenu.style.display = 'block';
    //make sure the control isn't off the page (m_bkmkMenu.lastChild is the table; m_bkmkMenu.clientWidth is the whole screen)
    var maxX = document.body.clientWidth - m_bkmkMenu.lastChild.clientWidth - 2;  
    if (maxX > 0 && x > maxX) // but don't let it go off the page
      m_bkmkMenu.style.left = maxX + 'px';
  }
}

function BookmarkingOptionControl_HideMenu()
{
  if (m_bkmkMenu)
    m_bkmkMenu.style.display = 'none';
  BkmkUnHighlightTopText();
}

function BookmarkingOptionControl_MouseOver()
{
  clearTimeout(Bookmark_HideMenuTimer);
}

var Bookmark_HideMenuTimer;
var Bookmark_ShowMenuTimer;

function Bookmarker_MouseOver(_bkmk, _url, _siteName)
{
  clearTimeout(Bookmark_HideMenuTimer); //clear the timeouts, otherwise we might show it and then hide it later
  
  // if it's still the same bookmarker and the menu's still showing, just stop the menu from hiding and return
  if (m_bkmkMenu && m_bkmkMenu.style.display != 'none' && _url == m_bkmkMenu.bkmkUrl)
    return;
  
  BookmarkingOptionControl_HideMenu();
  
  // test for map/profile visibility
  var visibilities = BkmkCheckStatus();
  var mapVisible = visibilities[0];
  var profileVisible = visibilities[1];

  
  if (mapVisible || profileVisible) // more than one option, so show the menu - no tooltip or onclick
  {
    _bkmk.title = '';
    _bkmk.onclick = null;
    // use timeout so it doesn't show the menu if you just pass over it
    clearTimeout(Bookmark_ShowMenuTimer); // make sure we're only showing one at once (shouldn't be nec)
    var tempVarString = "'" + _siteName + "', '" + _url + "', '" + _bkmk.id + "', " + mapVisible + ", " + profileVisible;
    Bookmark_ShowMenuTimer = setTimeout("BookmarkingOptionControl_ShowMenu(" + tempVarString + ")",300);
  }
  else // only one option, don't show the menu, set tooltip and onclick goes straight through
  {
    _bkmk.title = BkmkGetTooltip('site', _siteName);
    _bkmk.onclick = function(){Bookmark('site', _url)};
  }
}

function BkmkGetTooltip(_toBkmk, _siteName)
{
  //get the tooltip text - put it in it's own function incase the hard-coded text needs to be changed in future
  //_toBkmk should be site, hyperknowledge map or person
  var tooltip;
  if (_siteName == "Referral")
    tooltip = 'Click to refer someone to this ' + _toBkmk;
  else
    tooltip = 'Click to post this ' + _toBkmk + ' to ' + _siteName;
  return tooltip;
}

function Bookmarker_MouseOut(_bkmk)
{
  clearTimeout(Bookmark_ShowMenuTimer);
  Bookmark_HideMenuTimer = setTimeout("BookmarkingOptionControl_HideMenu()", 600);
  if (_bkmk)
  {
    _bkmk.onclick = null;
    _bkmk.title = '';
  }
}

function BookmarkingOptionControl_MouseOut()
{
  Bookmark_HideMenuTimer = setTimeout("BookmarkingOptionControl_HideMenu()", 500);
}

function Bookmark(_type, _url)
{
  //_type should be site, map, knowde or user
  var bkmkUrl;
  if (_url)
  {
    if (_type != 'user') // should only be here for site anyway; 'user' needs the bookmarker control later to get user name
      bkmkUrl = _url;
    else
      return;
  }
  else if (m_bkmkMenu)
  {
    bkmkUrl = m_bkmkMenu.bkmkUrl;
    BookmarkingOptionControl_HideMenu();
  }
  else
    return;
  
  
  if (bkmkUrl.toLowerCase() == 'referral.aspx')
  {
    var referUrl = 'Referral.aspx'
    switch (_type)
    {
      case ('site'):
        break;
      case ('map'):
        referUrl += '?action=MapReferral&kgid=' + Active_KGID + '&groupid=' + GroupID;
        break;
      case ('user'):
        referUrl += '?action=AuthorReferral&authorid=' + GetSelectedProfileId();
        break;
      case ('knowde'):
        referUrl += '?action=MapReferral&kgid=' + Active_KGID + '&knowde=' + returnKnowdeID(globalLastSelectedKnowde) + '&groupid=' + GroupID;
        break;
      default:
        //handle error or just continue?
        break;
    }
    window.location = referUrl;
  }
  else // bookmark to external site
  {
    //var hkUrl = 'http://www.hyperknowledge.com/';
    var hkUrl = window.location.href;
    hkUrl = hkUrl.substring(0, hkUrl.lastIndexOf('/') + 1); //remove the current page and any query string
    var hkTitle = 'Knowledge Genes';
    switch (_type)
    {
      case ('site'):
        break;
      case ('map'):
        hkUrl += 'home.aspx?kgid=' + Active_KGID;
        hkTitle += ' - ' + Active_KGName + ' - ' + Active_KGOwner;
        break;
      case ('knowde'):
        hkUrl += 'home.aspx?kgid=' + Active_KGID + '&knowde=' + returnKnowdeID(globalLastSelectedKnowde) + '&groupid=' + GroupID;
        hkTitle += ' - ' + Active_KGName + ' - ' + Active_KGOwner;
        break;
      case ('user'):
        hkUrl += 'options.aspx?user=' + GetSelectedProfileId();
        hkTitle += ' - ' + m_bkmkMenu.userName;
        break;
      default:
        //handle error or just continue?
        break;
    }
    
    var builtUrl = bkmkUrl + encodeURIComponent(hkUrl) + '&title=' + encodeURIComponent(hkTitle);
    window.open(builtUrl);
    
    //CM Facebook and Digg can use meta tags in the html for the preview, can't do this until the site is open
    //http://www.facebook.com/share_partners.php open the link 'Making Sure the Preview Works'
    //http://digg.com/tools/thumbnails
    //<meta name="title" content="Remembering Evel Knievel" />
    //<meta name="description" content="For 20 years Evel Knievel thrilled crowds with his death-defying stunts and daredevil antics." />
    //<link rel="image_src" href="http://newsimg.bbc.co.uk/media/images/42440000/jpg/_42440347_evel_ap203i.jpg" />
  }
}

function GetSelectedProfileId()
{
  var selectedProfileID;
  if (globalVisibleTab == "TSC_communities" && window.Com_GetSelectedProfileId)
    selectedProfileID = Com_GetSelectedProfileId();
  else if (globalVisibleTab == "TSC_myprofile" && window.Pfl_GetSelectedProfileId)
    selectedProfileID = Pfl_GetSelectedProfileId();
  return selectedProfileID;
}
      
function BkmkHighlightTopText(_url)
{
  var topText = BkmkGetTopText(_url);
  if (topText)
    topText.style.color = 'Black';//back to default in css
}

function BkmkUnHighlightTopText()
{
  // just unhighlight both - it's easier than trying to figure out which it is, e.g. for mouse out of the options control
  var topReferText = BookmarkingControl_GetReferText();
  if (topReferText)
    topReferText.style.color = '';//back to default in css
  var topBkmkText = BookmarkingControl_GetBkmkText();
  if (topBkmkText)
    topBkmkText.style.color = '';//back to default in css
}

function BkmkGetTopText(_bkmkUrl)
{
  var topText;
  if (!_bkmkUrl || _bkmkUrl.toLowerCase() == 'referral.aspx')
    topText = BookmarkingControl_GetReferText();
  else
    topText = BookmarkingControl_GetBkmkText();

  return topText;
}

function BkmkHighlightOptionText(_text)
{
  if (_text)
	  _text.style.background = "#dddddd";
}

function BkmkUnHighlightOptionText(_text)
{
  if (_text)
    _text.style.background = ""; //back to css default
}

//CM temporary code to show a warning message box before posting to an external site
// probably won't need this when we leave beta
////////////////////////START OF TEMPORARY CODE/////////////////////////////////////////////////////////////////////////////////////////////////////
var m_BkmkMsgBox = null;
var CurrentlyShowingMessageBox;

///////////////////////
// Ensures that the delete message box is on the page
function EnsureBkmrkMessage(_parentControlDivId, _siteName, _builtUrl)
{
  m_BkmkMsgBox = document.getElementById("BookmarkMessageBox");
  
  if(m_BkmkMsgBox == null)
  {
    m_BkmkMsgBox = document.createElement("div");
    var parentControlDiv = document.getElementById(_parentControlDivId);
    InsertAdjacentElement(parentControlDiv,"afterEnd", m_BkmkMsgBox);
    
    m_BkmkMsgBox.setAttribute("id", "BookmarkMessageBox");
    m_BkmkMsgBox.style.display = "none";
    m_BkmkMsgBox.style.width = "400px"
    m_BkmkMsgBox.style.height = "120px";
    m_BkmkMsgBox.style.position = "absolute";
  }
  
  var header = 'Please do NOT bookmark this site while we are still in beta';
  var headerStyle = 'color:red;font-weight:bold;background-color:#f0f0f0;text-align:center';
  var line2 = 'Click OK to continue to the ' + _siteName + ' preview page';
  var onclickOk = 'window.open(\"' + _builtUrl + '\"); CloseBkmkMsgBox()';
  m_BkmkMsgBox.innerHTML = "<div style='border:gray solid 1pt;background:white;'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' style='" + headerStyle + "'>" + header + "</td></tr><tr><td rowspan='2' valign='top'><img src='images/alert.png' height='50' width='50'/></td><td>" + line2 + "</td></tr><tr><td align='right'><button type='button' onclick='" + onclickOk + "'>OK</button><button id = defaultButton type='button' onclick='CloseBkmkMsgBox()'>Cancel</button></td></tr></table></div>";
}

function BkmkTopZIndex()
//Find highest z index in current document and returns this value + 1 (so that
//the control using this value will appear on top of everything currently in  
//the page, but will appear behind everything called subsequently).  JPC.
//(inspired by http://domscripting.com/presentations/atmedia2006/slides/, slide 12)
{
  var maxZindex = 0;
  var elems = document.getElementsByTagName("div");
  
  for (var j=0; j<elems.length; j++)
  {
    if (elems[j].style.zindex > maxZindex)
    {
       maxZindex = parseInt(elems[j].style.zindex);
    }
  }

  return maxZindex + 1;
}

/////////////////////
// Positions the supplied message box relative to the cursor
function PositionBkmkMsgBox()
{
  // display in middle of screen
  m_BkmkMsgBox.style.top = (document.body.clientHeight/2) - (GetPixelHeight(m_BkmkMsgBox)/2);
  m_BkmkMsgBox.style.left = (document.body.clientWidth/2) - (GetPixelWidth(m_BkmkMsgBox)/2);
    
  m_BkmkMsgBox.style.display = "block";
  m_BkmkMsgBox.style.zIndex = BkmkTopZIndex();
  m_BkmkMsgBox.style.visibility = "visible";
  BkmkFocusOn("defaultButton");
  CurrentlyShowingMessageBox = true;
}

function BkmkFocusOn(buttonId)
{
  var focusButton = document.getElementById(buttonId)
  if (focusButton != null)
  {
    // This line is necessary for the code to work with the WhatExists box.  
    // this may be due to my implementation of the box.  JPC
    focusButton.style.visiblity = "visible";  
    try
    {
        focusButton.focus();
    }
    catch(er)
    {
    }
  }
}

//////////////////
// Closes the message box
function CloseBkmkMsgBox()
{
  if(m_BkmkMsgBox != null)
  {
    m_BkmkMsgBox.style.visibility = "hidden";
    m_BkmkMsgBox.style.display = "none";
    CurrentlyShowingMessageBox = false;
  }
}
////////////////////////END OF TEMPORARY CODE/////////////////////////////////////////////////////////////////////////////////////////////////////

 // Splitter Pane Event Handler
 var globalBottomSplitterHeight = "50";
 var globalSplitterState = "1";
 var globalLeftPaneOpen = false;
 var globalMapViewControlLoaded = false; // used in SplitterPaneHandler.js, SetMapViewPaneStatus 
                                        // to decide whether to do a callback when the splitter's opened 
                                        // should be true when the map view is drawn, 
                                        // then set to false for any MapViewControl callbacks that change the map view data
                                        
function Splitter1_onResize(sender, eventArgs)
{
  try
  {
		if(document.getElementById('SplitterArrowDown') != null)
			if(document.getElementById('SplitterArrowDown').className == 'HiddenArrowDown')
				eventArgs.set_cancel(true);
		if(globalSplitterState == 3)
			eventArgs.set_cancel(true);
		if(Splitter1.Panes[1].element.style.display == "none")
			eventArgs.set_cancel(true);
		setPaneSize();
	}
  catch(e)
  {
		alert('Splitter1_onResize() error');
  }
}

function Splitter1_onLoad(sender, eventArgs) 
{
	try
	{
		// Call into the javascript method to process the query string 
		// in the case we have been redirected after a forced sign-in/sign-on
		processRedirection();
		if(window.location.search.toLowerCase().match("kgid") == "kgid")
		{
			SetSessionProperty("Browser",navigator.appName);
			DoExpandMapViewPane('fully');
		}
  }
  catch(e)
  {
		alert('Splitter1_onLoad() error');
  }
}

function setPaneWidths()
{
	try
	{
		if(globalLeftPaneOpen)
		{
			OpenLeftPanel(true);
		}
		else
		{
			if(document.getElementById("Splitter1_pane_1") != null)
			{
				Splitter1_pane_0.lastChild.style.width = Splitter1.Width -5; // firstChild can be a message box
				Splitter1_pane_0.width = Splitter1.Width -5;
				Splitter1_pane_0.style.width = Splitter1.Width -5;
				Splitter1_pane_1.firstChild.style.width = Splitter1.Width -5;
				Splitter1_pane_1.width = Splitter1.Width -5;
				Splitter1_pane_1.style.width = Splitter1.Width -5;
				HorizontalCategoriesControl_Reload();
			}
		}
	}
  catch(e)
  {
		alert('setPaneWidths() error');
  }
}

 // PaneB Collapse Status
 function PaneBStatus()
 { 
    var BCollapsed = null;
    var PaneB = null;
    if(Splitter1!=null && Splitter1.Panes!=null && Splitter1.Panes[0]!=null)
    {
       PaneB = Splitter1.Panes[0];
    }
    if(PaneB != null && PaneB.Collapsed != null){
       BCollapsed = PaneB.Collapsed;
    }
    return BCollapsed;
 }
 
 // Get Show Status of KGFloatingControl by PaneA and PaneB Collaspe Status
 function ShowStatus()
 {
    var IsShow = false;
    var BCollapsed = PaneBStatus();
    if(BCollapsed == null || BCollapsed == false)
    {
      IsShow = BCollapsed;
    }
    else 
    {
      IsShow = false;
    }
    return IsShow;
 }
  
  function SetMapViewPaneStatus()
  {
    var PaneB = null;
    if(Splitter1!=null && Splitter1.Panes!=null && Splitter1.Panes[0]!=null)
    {
       PaneB = Splitter1.Panes[0];
    }
    if(PaneB != null && PaneB.Collapsed != null)
    {
      if (PaneB.Collapsed == false)
      {
        if (globalMapViewControlLoaded == false)
        {
          var srmIndex;
          try
          {
            srmIndex = SrmControl_SetInitial('OpenMapSplitter');
          }
          catch(e){}
          clearTimeout(mvcCallbackTimeout);
          MapViewControl1_CallbackTrigger(srmIndex);
        }
        else
        {
          if (window.Active_KGID && window.Active_KGName) //also check Active_KGID and Active_KGName incase there's no map
            KGButtonToolbar_hideOrShowMapButtons(true);
          if (MapViewDefaultFocus)
            MapViewDefaultFocus();
        }
      }
      else
        KGButtonToolbar_hideOrShowMapButtons(false);
    }
  }
  
  function HideOptionControls()
  {
    // hide KGPublishOption control
    var PaneC = null;
    if(Splitter1!=null && Splitter1.Panes!=null && Splitter1.Panes[0]!=null)
    {
       PaneC = Splitter1.Panes[1];
    }
    if(PaneC != null && typeof CloseKGPublishOptionControl == 'function'){
      CloseKGPublishOptionControl();
    }
  }  
   
  var globalSkipTourHide = "false";
  function DoCollapseMapViewPane()
  {
    var PaneB = null;
    var PaneC = null;
    if(globalSkipTourHide == "false")
    {
			var tour = document.getElementById("TourContainer");
			if(tour)
			{
				tour.style.display = "none";
			}
    }
    else
			globalSkipTourHide = "false";
    if(Splitter1!=null && Splitter1.Panes!=null && Splitter1.Panes[0]!=null)
    {
       PaneB = Splitter1.Panes[0];
       PaneC = Splitter1.Panes[1];
    }
    if(PaneB != null)
    {
			if(PaneB.Collapsed != true)
			{
				Splitter1.CollapsePane(PaneB);
				PaneB.SetHeight(0);
			}
			PaneC.element.style.display = "";
			PaneC.SetHeight(Splitter1.Height - 4);
    }
    setPaneSize();
    document.title = "Knowledge Genes\u00AE - Home";
  }
  
  function DoExpandMapViewPane(_expandType, _keepExistingHeight)
  {
    var PaneB = null;
    var PaneC = null;
    var tour = document.getElementById("TourContainer");
    if(tour)
    {
			tour.style.display = "block";
    }
    if(Splitter1!=null && Splitter1.Panes!=null && Splitter1.Panes[0]!=null)
    {
       PaneB = Splitter1.Panes[0];
       PaneC = Splitter1.Panes[1];
    }
    PaneC.Collapsed = false;
    
    if(PaneB != null)
    {
	   var ptopHeight = PaneB.Height;
	   var pbottomHeight = PaneC.Height;
	   
		 PaneC.SetHeight(0);
		 PaneB.SetHeight(0);
     Splitter1.ExpandPane(PaneB);
     
      if(_expandType == "fully")
      { 
				PaneB.SetHeight(Splitter1.Height - 4);
				PaneC.SetHeight(0);
				PaneC.element.style.display = "none";
				ShowTabWidget();
      }
      else if(_expandType == "split")
      {
	      if(ptopHeight > 0 && pbottomHeight > 0 && _keepExistingHeight)
	      {
	        PaneB.SetHeight(ptopHeight);
          PaneC.SetHeight(pbottomHeight);
				  PaneC.element.style.display = "";		     
	      }
	      else
	      {
          var half = Math.floor(Splitter1.Height/2); // can't set non-integer height
				  PaneB.SetHeight(half - 2);
				  PaneC.SetHeight(half - 2);
				  PaneC.element.style.display = "";
				}
				ShowSplitterArrowUp();
				HideTabWidget();
			}
			setPaneSize();
    }
    
    try
    {
      if (Active_KGName && Active_KGOwner)
        document.title = "Knowledge Genes\u00AE - " + Active_KGName + " - " + Active_KGOwner;
    }
    catch(e)
    {}
     
  }
	
  function SplitterControl(_direction)
  {
  // globalSplitterSetting chooses between split view & single view
  // direction decides what way to move the splitter
		try
		{
		//debugger;
			setPaneSize();
			var PaneB = Splitter1.Panes[0];;
			var PaneC = Splitter1.Panes[1];
			if(globalSplitterSetting == "split")
			{
				if (_direction == 'up')
				{
					if(PaneC.element.style.display == "none")
					{
						// if at bottom
						DoExpandMapViewPane("split");
					}
					else
					{
						// if in middle
						DoCollapseMapViewPane();
					}
				}
				if (_direction == 'down')
				{
					if(PaneB.Height == 0)
					{
						// if at bottom
						DoExpandMapViewPane("split");
					}
					else
					{
						// if in middle
						DoExpandMapViewPane("fully");
					}	
				}
			}
			else
			{
				if (_direction == 'up')
				{
					// single view full snap
					DoCollapseMapViewPane();
				}
				if (_direction == 'down')
				{
					// single view full snap
					DoExpandMapViewPane("fully");
				}
			}
		}
		catch(e)
		{
			alert('SplitterControl() error');
		}
  }
  
  function helpOverlaySplitterResize()
  {
		var SplitterPos = findPosNoAdjust(document.getElementById('Splitter1'));
		
		var footer = document.getElementById("SiteFooterContainer");
		var footerHeight = 0;
		if (footer != null)
		  footerHeight = footer.clientHeight + 2;
		
		var margin = 0;
		if (navigator.userAgent.indexOf('Firefox') == -1)
		{
			 margin = 83;
		}
		
		Splitter1.Height = document.body.clientHeight - SplitterPos[1] - footerHeight - margin;

		Splitter1.element.style.height = Splitter1.Height;
		return Splitter1.Height - 4;
  }
  
  function setPaneSize()
  {
		try
		{
			if(document.getElementById("Splitter1") != null)
			{
				setPaneWidths();

				var paneRight = document.getElementById("Splitter1");
				paneRight.style.height = helpOverlaySplitterResize();
				//paneRight.firstChild.style.height = "100%";
				
				// remove the gap below the map in FF2
				/*var parent = paneRight.parentNode;
        if (parent.style.height == '1px')
          parent.style.height = '2px';
        else
          parent.style.height = '1px';*/
      
				var paneTop = document.getElementById("Splitter1_pane_0");
				if(paneTop)
				{
				  //paneTop.parentNode.style.height = '1px';// remove the gap below the map in FF2
				  //opera height not updated
				  var paneBottom = document.getElementById("Splitter1_pane_1");
				  if (paneBottom) 
				  {
				    if (paneTop.style.display == 'none')
				    {
							var PaneB = null;
							var PaneC = null;
							if(Splitter1!=null && Splitter1.Panes!=null && Splitter1.Panes[0]!=null)
							{
								 PaneB = Splitter1.Panes[0];
								 PaneC = Splitter1.Panes[1];
							}
							if(PaneB != null)
							{
								if(PaneB.Collapsed != true)
								{
									Splitter1.CollapsePane(PaneB);
									PaneB.SetHeight(0);
								}
								PaneC.element.style.display = "";
								PaneC.SetHeight(Splitter1.Height - 4);
							}
				    
				      paneBottom.style.height = Splitter1.Height - 4;
				      paneBottom.firstChild.style.height = "100%";
				    }
				    else if (paneBottom.style.display == 'none')
				    {
				      paneTop.style.height = Splitter1.Height - 4;
				      paneTop.firstChild.style.height = "100%";
				    }
				    else
				    {
				      var ptopHeight = Splitter1.Panes[0].Height;
				      var pbottomHeight = Splitter1.Panes[1].Height;
				      
				      if(ptopHeight > 0 && pbottomHeight > 0)
				      {
                paneTop.style.height = ptopHeight;
				        paneTop.firstChild.style.height = "100%";
				        paneBottom.style.height = pbottomHeight;
				        paneBottom.firstChild.style.height = "100%";				     
				      }else
				      {
				        paneTop.style.height = (Splitter1.Height/2) - 2;
				        paneTop.firstChild.style.height = "100%";
				        paneBottom.style.height = (Splitter1.Height/2) - 2;
				        paneBottom.firstChild.style.height = "100%";
				      }
				    }
				  }
				}
			}
			if (scrollingDivID)
			{
			  var scrollingDiv = document.getElementById(scrollingDivID);
			  if (scrollingDiv)
			    scrollingDiv.style.height = helpOverlaySplitterResize();
			}
		}
		catch(e)
		{
			alert('setPaneSize() error');
		}
	}
	
	// Collaspe PaneA or PaneB
  function CollapseLeftPane()
  {
		var button = document.getElementById("KGButtonToolbar_KeyConceptBtn");
		if(button)
			button.style.display = 'none';//.className = 'ButtonToolbar_Hidden';
		
    SetMapViewPaneStatus();
    HideOptionControls();
    if(window.TextViewDivResize)
      TextViewDivResize();
      
		setPaneWidths()
    return true;
  }

	function PanesAreSplit()
	{
		var paneTop = document.getElementById("Splitter1_pane_0");
		var paneBottom = document.getElementById("Splitter1_pane_1");
		if(paneTop.style.height == "0%" || paneBottom.style.height == "0%" || paneTop.style.display == "none" || paneBottom.style.display == "none" )
			return false;
		return true;
	}
  
  function resetHeights()
  {
		//this code ensures that the splitter pane heights
		//remain correct on a page resize.
		setPaneSize();
		var paneTop = document.getElementById("Splitter1_pane_0");
		var paneBottom = document.getElementById("Splitter1_pane_1");
		
		if(globalSplitterState == "1")
		{
			//no need to change anything
		}
		if(globalSplitterState == "2")
		{
			//no change as of yet - could shrink page to keep splitter in for windowed browsers
		}
		if(globalSplitterState == "3")
		{
			paneTop.style.height = Splitter1.Height - 4;
			paneTop.lastChild.style.height = "100%";
			paneBottom.style.height = "0%";
			paneBottom.firstChild.style.display = "none";
		}
  }
  function HideSplitterArrowDown(_amount)
  {
		if(_amount == "full")	
		{
			var splitterArrowDown = document.getElementById('SplitterArrowDown');
			splitterArrowDown.className = 'HiddenArrowDown'; //arrowDown
			var splitterPaneMap = Splitter1.Panes[0];
			var splitterBar = splitterPaneMap.element.parentNode.nextSibling;
			splitterBar.className = 'HiddenSplitterBar';
			DoCollapseMapViewPane();
    }
    else
    {
			DoCollapseMapViewPane();
    }
  }

  function ShowSplitterArrowDown()
  {
    var splitterArrowDown = document.getElementById('SplitterArrowDown');
    if (splitterArrowDown != null && splitterArrowDown.className.indexOf('idden') > -1)
    {
      splitterArrowDown.className = 'arrowDown';
      var splitterPaneMap = Splitter1.Panes[0];
      var splitterBar = splitterPaneMap.element.parentNode.nextSibling;
      splitterBar.className = 'VerticalSplitterBar';
    }
  }
  
  function ShowSplitterArrowUp()
  {
    var splitterArrowUp = document.getElementById('SplitterArrowUp');
    if (splitterArrowUp != null && splitterArrowUp.className.indexOf('idden') > -1)
    {
      splitterArrowUp.className = 'arrowUp';
      var splitterPaneMap = Splitter1.Panes[0];
      var splitterBar = splitterPaneMap.element.parentNode.nextSibling;
      splitterBar.className = 'VerticalSplitterBar';
    }
  }
  
  
function isOverlayVisible()
{
	if(isHelpVisible()||isSuggestionVisible()||isSuggestionLoggedInVisible()||isLogInVisible())
		return true;
	else
		return false;
}  

function isHelpVisible()
{
	var helpControl = document.getElementById("KGHelpControlID1");
	if(helpControl.className == "OverlayPosition")
		return true;
	else
		return false;
}
function isSuggestionVisible()
{
	if(document.getElementById("KGSuggestionControl") != null)
	{
		var SuggestionControl = document.getElementById("KGSuggestionControl");
		if(SuggestionControl.className == "OverlayPosition")
			return true;
		else
			return false;
	}
}
function isSuggestionLoggedInVisible()
{
	if(document.getElementById("KGSuggestionControl1") != null)
	{
		var Suggestion1Control = document.getElementById("KGSuggestionControl1");
		if(Suggestion1Control.className == "OverlayPosition")
			return true;
		else
			return false;
	}
}
function isLogInVisible()
{
	var LoginControl = document.getElementById("KGSignInControl1");
	if(LoginControl.className == "OverlayPosition")
		return true;
	else
		return false;
}

function OpenLeftPanel(_force)
{
	try
	{
		var treeWalker = document.getElementById("LeftPaneTreeWalker");
		if(treeWalker != null)
		{
			// tree walk to grab panes - couldnt assign id's due to hardcoded ids of inner controls - will update later
			var LeftPane = treeWalker.parentNode.parentNode;
			
			// return if it is already open
			if(_force == false)
				if(LeftPane.style.width == "275px")
					return;
			
			if(LeftPane.style.width != "275px")
				shiftAllKnowdesLeft(-275);
				
			LeftPane.style.display = "block";
			LeftPane.style.width = "275px";
			

			var iIndex;
			for(iIndex=0; iIndex<LeftPane.parentNode.childNodes.length; iIndex++)
			{
				if(LeftPane.parentNode.childNodes[iIndex].style != null && LeftPane.parentNode.childNodes[iIndex] != "undefined")
				{
					if(LeftPane.parentNode.childNodes[iIndex].style.width == "100%" || LeftPane.parentNode.childNodes[iIndex].style.width == "" || LeftPane.parentNode.childNodes[iIndex].style.width != "275px")
					{
						LeftPane.parentNode.childNodes[iIndex].style.width = Splitter1.WindowWidth - 275;
						Splitter1.adjustSize(true);
						globalLeftPaneOpen = true;
					}
				}
			}
			MoveRedButtons("WhatsTab");			
		}
	}
	catch(e)
	{
		alert("Sorry, the Left Panel failed to open: OpenLeftPanel script");
	}
}

function CloseLeftPanel(e)
{
	try
	{
		var targ = document.getElementById("LeftPaneTreeWalker");
		var LeftPane = targ.parentNode.parentNode;
		
		// return if it is already closed
		if(LeftPane.style.width == "0%")
			return;
			
		LeftPane.style.display = "none";
		LeftPane.style.width = "0%";
		shiftAllKnowdesRight(275,null,null,null);
	  
		var iIndex;
		for(iIndex=0; iIndex<LeftPane.parentNode.childNodes.length; iIndex++)
		{
			if(LeftPane.parentNode.childNodes[iIndex].style != null && LeftPane.parentNode.childNodes[iIndex].style != "undefined")
			{
				if(LeftPane.parentNode.childNodes[iIndex].style.width != "0%")
				{
					LeftPane.parentNode.childNodes[iIndex].style.width = "100%";
					globalLeftPaneOpen = false;
				}
			}
		}
		
		Splitter1.adjustSize(true);
		MoveRedButtons("MapView");		
  }
	catch(e)
	{
		alert("Sorry, the Left Panel failed to close: CloseLeftPanel script");
	}

}

function MoveRedButtons(_whereTo)
{
  var redButtons = document.getElementById("RedButtonsContent");
  if (!redButtons)
    return; // we don't always show the buttons - the logic for when is changing
    
  var mapViewRedButtonsHolder = document.getElementById("MapViewRedButtonsHolder");
  var whatsTabRedButtonsHolder = document.getElementById("WhatsTabRedButtonsHolder");
  
  if (_whereTo == "WhatsTab")
  {
    MoveElement(redButtons, whatsTabRedButtonsHolder);
  }
  else if (_whereTo == "MapView")
  {
    MoveElement(redButtons, mapViewRedButtonsHolder);
  }
}

function MoveElement(_element, _toElement)
{
  //_element.parentNode.removeChild(_element); // no need to remove it first, it won't make a copy
  _toElement.appendChild(_element);
}


// JScript File
// Write times to the SRMDB via a callback to SrmControl

var m_srmGetTimes; // whether to record times, set in SrmControl.cs from web.config
var m_srmT0 = new Array(); // when action was first triggered, as now.getTime (easier to convert to string than date-time object)
var m_srmAction = new Array(); // name of the action plus any messages separated by ','
var m_srmCallbacks = new Array(); // number of callbacks triggered by event, to determine which is the last one


// Set the initial variables when the action is triggered
// returns srmIndex, used later to refer back to that event
function SrmControl_SetInitial(_action)
{
  if (m_srmGetTimes!= null && m_srmGetTimes == "True")
  {
    //debugger;
    var now = new Date();
    var srmIndex = m_srmT0.length;
    m_srmT0[srmIndex] = now.getTime();
    m_srmAction[srmIndex] = _action;
    m_srmCallbacks[srmIndex] = 1;
    return srmIndex;
  }
  return 0;
}

// Call SrmControl_CallbackTrigger if this is the final callback
function SrmControl_RecordTimes(_srmIndex)
{
  //debugger;
  if (m_srmGetTimes != null && m_srmGetTimes == "True" && _srmIndex != null && _srmIndex != 'undefined'&& _srmIndex >= 0)
  {
    try
    {
      if (m_srmCallbacks[_srmIndex] != null)
      {
        m_srmCallbacks[_srmIndex]--;
        if (m_srmCallbacks[_srmIndex] == 0)
          setTimeout("SrmControl_CallbackTrigger("+_srmIndex+")", 10);
        
      }
    }
    catch(e) {}
  }
}


//Send the time back to the server to put into the SRMDB
function SrmControl_CallbackTrigger_Wrapped(_cbreference, _srmIndex)
{
  if (m_srmGetTimes!= null && m_srmGetTimes == "True")
  {
    var now = new Date();
    var timingDiff = Math.round(now.getTime() - m_srmT0[_srmIndex]) / 1000;
    var args = "Message=Time," + m_srmAction[_srmIndex] + ":" + timingDiff; 
    //var args = "Message=" + m_srmAction[_srmIndex] + ",Now=" + now.getTime() + ":" + timingDiff; 
    if(_cbreference != null && _cbreference != "")
      eval(_cbreference);
    
    m_srmT0[_srmIndex] = null;
    m_srmAction[_srmIndex] = null;
    m_srmCallbacks[_srmIndex] = null;
  }
}

//Send the time back to the server to put into the SRMDB
function SrmControl_CallbackTrigger_AfterDelay_Wrapped(_cbreference, _srmIndex, _srmDelay)
{
  if (m_srmGetTimes!= null && m_srmGetTimes == "True")
  {
    var now = new Date();
    var timingDiff = Math.round(now.getTime() - m_srmT0[_srmIndex] - _srmDelay) / 1000;
    var args = "Message=Time," + m_srmAction[_srmIndex] + ":" + timingDiff; 
    //var args = "Message=" + m_srmAction[_srmIndex] + ",Now=" + now.getTime() + ":" + timingDiff; 
    if(_cbreference != null && _cbreference != "")
      eval(_cbreference);
    
    m_srmT0[_srmIndex] = null;
    m_srmAction[_srmIndex] = null;
    m_srmCallbacks[_srmIndex] = null;
  }
}

function SrmControl_CallbackDone(args)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  if (args != 'ok')
    SrmControl_ProcessCallBackError(args);
}

function SrmControl_ProcessCallBackError(args)
{
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    //alert("Callback error in SrmControl");
    var temp = 5;
  }
}

function SrmControl_QuickCallback_Wrapped(_cbreference, _message)
{
  args = 'Message=' + _message + '|Category=Troubleshooting';
  eval(_cbreference);
}

// liconceptTreeControl JScript File

var globalConceptTreeTimer;
var conceptTreeControl_preTreeViewID;
var conceptTreeControl_preTreeNodeID;
var scrollingDivID;
var loadingDivOffset = 75;
var m_settingStatus = false;
var m_srmDelay = 800;
var dblClickSearchPhrase;


// Handle tree node expand or collapsed 
function ConceptTreeControl_SetTreeNodeStatus(_node, _hiddenFieldClientID, _sessionNameForExpandedNodes, _scrollFunctionName, _srmIndex) 
{
  if(_node != null)
  {
    var seperator = '@';
    var nodeID = _node.ID.split('_');
    var nodeType = nodeID[0];
    var nodeVal = '[' + nodeType + '_' + _node.Value + ']';
    var box = document.getElementById(_hiddenFieldClientID);
    if(box != null)
    {
      var nodesstatus = box.value;
      
      if (nodeType == "HSO") //an SO ConceptTree Root Node - record if contracted
      {
        if(_node.Expanded)
        {
          // then this node will be collapsed
          if(nodesstatus.indexOf(nodeVal) < 0)
          {
            // not recorded yet
            box.value = nodesstatus + nodeVal + seperator;
          } //end index if
          eval(_scrollFunctionName); //fire the onscroll event incase more nodes are required
          //Currently only SOTree has a valid _scrollFunctionName, but should only be fired if it's a SO node
        }
        else
        {
          // will be expanded
          box.value = nodesstatus.replace(nodeVal+seperator,'');
          
        } //end expanded if
      }
      else // Not an SO ConceptTree Root Node
      {
        if(_node.Expanded)
        {
          // then this node will be collapsed
          box.value = nodesstatus.replace(nodeVal+seperator,'');
          try
          {
            m_srmAction[_srmIndex] = m_srmAction[_srmIndex].replace('Expand','Collapse');
            m_srmAction[_srmIndex] = m_srmAction[_srmIndex].replace(',LOD','');
          }
          catch(e){}
          if (_scrollFunctionName.indexOf('SearchResult') > -1) 
            checkNodeCollapsed(_node, _scrollFunctionName); //fire the onscroll event incase more nodes are required; Make sure the collapse has finished first
            //setTimeout(_scrollFunctionName, 500); //fire the onscroll event incase more nodes are required; Timeout makes sure tree is redrawn first (to check it's new height)
        }
        else
        {
          // will be expanded
          if(nodesstatus.indexOf(nodeVal) < 0)
          {
            // not recorded yet
            box.value = nodesstatus + nodeVal + seperator;
          } //end index if
        } //end expanded if
      }
      setTimeout("SetSessionProperty('" + _sessionNameForExpandedNodes + "', '" + box.value + "')",1);
    }
    else
    {
        alert('Concept tree hidden field not found.');
    } //end box null if
  } 
  try 
  {
    if (m_srmGetTimes!= null && m_srmGetTimes == "True" && _srmIndex != null)
    {
      if (m_srmCallbacks[_srmIndex] == 2)
      {
        m_settingStatus = _srmIndex;
        setTimeout("ResetSettingStatus();",m_srmDelay);
      }
      else
        m_settingStatus = false;
      
      SrmControl_RecordTimes(_srmIndex);
    }
  }
  catch(e){}
  return true; //end node null if
}// end function

function checkNodeCollapsed(_node, _scrollFunctionName, _divId, _counter)
{ // make sure the node is actually collapsed before calling the scrolling function
  if (_node)
  {
    var index = _node.GetCurrentIndex();
    var treeViewId = _node.ParentTreeView.TreeViewID;
    _divId = treeViewId + '_item_' + index + '_div';
  }
  var div = document.getElementById(_divId);
  if (div != null) // div is null if you scroll at the same time
  {
    if (div.style.display != 'none')
    {
      if (_counter != null)
        _counter++;
      else
        _counter = 1;
      if (_counter <= 10) // make sure it doesn't loop forever
        window.setTimeout("checkNodeCollapsed(null, '" + _scrollFunctionName + "', '" + _divId + "', " + _counter + ")", 200);
    }
    else
      window.setTimeout(_scrollFunctionName, 20);
  }
}

function ResetSettingStatus()
{
  if (m_settingStatus)
  {
    try
    {
      m_srmAction[m_settingStatus] = m_srmAction[m_settingStatus].replace('LOD','NoLOD');
      SrmControl_CallbackTrigger_AfterDelay(m_settingStatus, m_srmDelay);
    }
    catch(e){}
    m_settingStatus = false;
  }
}

// Confirm remove concept notification
function ConceptTreeControl_RemoveConceptNotification(_param, _postBackReference)
{  
    var iConfirm= confirm('OK to remove notification?');
    if (iConfirm== true)
    {
      _param = 'RemoveAlertForConcept-' + _param;
    }
    else
    {
      _param = 'FavouriteConceptAlert-' + _param;
    }
    // trigger postback
    eval(_postBackReference);
}// end function

// Process callback error
function ConceptTreeControl_ProcessCallBackError(args, context)
{
  //debugger;

  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    m_scrolling = false;
    //_args =  _args.substring(_args.indexOf('[@|@]') + 5);
    var s = _args.split('='); 
    var holder = document.getElementById(s[0]);
    if(holder != null)
    {
      holder.innerHTML = 'An error has occurred. ' + s[1];
    }
    else
    {
      alert('Exception occurred. '+ s[1]);
    }
  }
}// end function

// Handle tree node checked/unchecked
function ConceptTreeControl_SetTreeNodeCheckedStatus(_node, _callBackReference, _clientSideOnSubscriptionChange, _srmIndex)
{
  try
  {
    if (m_srmGetTimes!= null && m_srmGetTimes == "True")
      m_srmAction[_srmIndex] += ',' + _node.Text + ',' + _node.ID + ',Checked=' + _node.Checked;
  }
  catch(e){}
  
  if(_node != null)
  {
    // SetSessionProperty('PageSession_KGCheckedConceptID', _node.Value);
    if(_clientSideOnSubscriptionChange != null && _clientSideOnSubscriptionChange.length > 0)
    {
      eval(_clientSideOnSubscriptionChange);
    }
    // trigger callback
    var args = 'Concept=' + _node.Value + '|Checked=' + _node.Checked + '|NodeID=' + _node.ID + '|TreeID=' + _node.ParentTreeView.TreeViewID  + '|SrmIndex=' + _srmIndex;
    
    eval(_callBackReference);
  }
  // alert(_node.Value); // for debug
  // alert(_node.get_Checked()); // for debug
  return true;
}// end function

//// Handle tree node checked/unchecked if subscribing concept from KGKnowlegeGeneListControl
//function ConceptTreeControl_SetTreeNodeCheckedStatusByKGList(_aCheckbox, _conceptId, _kgId, _callBackReference , _clientSideOnSubscriptionChange)
//{
//  if(_conceptId != null && _kgId != null && _aCheckbox != null)
//  {
//    if(_clientSideOnSubscriptionChange != null && _clientSideOnSubscriptionChange.length > 0)
//    {
//      eval(_clientSideOnSubscriptionChange);
//    }
//    
//    // trigger callback
//    var args = 'Concept=' + _conceptId + '|Checked=' + _aCheckbox.checked + '|NodeID='+ 'How_'+ _conceptId + '|TreeID=' + 'FT' + _conceptId +'|KGSubscrpition=1|KGID='+_kgId;
//    
//    eval(_callBackReference);
//    
//    _aCheckbox.checked = _aCheckbox.checked;
//  }
//  
//  return true;
//}

// Subscribe Knowlegenes  from KGKnowlegeGeneListControl
function ConceptTreeControl_SubscribeKGByKGListControl(_aCheckbox, _kgId, _callBackReference , _clientSideOnSubscriptionChange)
{
  if( _kgId != null && _aCheckbox != null)
  {
    if(_clientSideOnSubscriptionChange != null && _clientSideOnSubscriptionChange.length > 0)
    {
      eval(_clientSideOnSubscriptionChange);
    }
    
    // trigger callback;
    var args = 'Concept=-1|Checked=' + _aCheckbox.checked + '|KGSubscrpition=1|KGID='+_kgId;
    
    eval(_callBackReference);
    
    _aCheckbox.checked = _aCheckbox.checked;
  }
  
  return true;
}

// Repopulate concept tree control
function ConceptTreeControl_RepopulateCallbackDone(_args, _context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  var start = new Date();

  if(_args.indexOf('Status=Error') > -1)
  {
    var statusInfo = _args.split('[@|@]'); 
    var status = statusInfo[0].split('=');
    if(status[1]=='Error')
    {
      var holderID = statusInfo[1].split('=');
      var exception = statusInfo[2].split('=');
      var callbackerror = holderID[1] + '=' + exception[1];
      ConceptTreeControl_ProcessCallBackError(callbackerror, '');
    }
  }
  else
  {
    var repop = _args.split('[@|@]');
    var repopulateStatus = repop[0].split('=');
    if(repopulateStatus[1] == 'true')
    {
      //_args =  _args.substring(_args.indexOf('[@|@]') + 5);
      _args = repop[2];
      var s = _args.split('='); 
      //debugger;
      // get parent container (multipage in this case)
      var seperatorIndex = s[0].lastIndexOf('_');
      if(s[0].lastIndexOf('Page') > seperatorIndex)
      {
        Global_SemanticTreeHolderID = s[0].substring(0,seperatorIndex);
      }
      var holder = document.getElementById(s[0]);
      if(holder != null)
      {
        holder.innerHTML = _args.substring(_args.indexOf('=')+1);

        // need to redeclare the storage and the main function before calling it
        // therefore get the text of it
        // storage first
        var remainString = _args;
        var continueLoop = 0;

        do
        {
          continueLoop = 0;
          var pos1 = remainString.indexOf('![CDATA[');
          if ( pos1 > - 1)
          {
            var string2 = remainString.substring(pos1, _args.length);
            var pos2 = string2.indexOf('window.ComponentArt_Storage_');
            var pos3 = string2.indexOf('//]]>', pos2 + 1);
            
            if ( pos2 > -1 && pos3 > -1)
            {
              var evalStorageString = string2.substring(pos2, pos3);

              // eval the string
              eval(evalStorageString);

              // now the init string
              var pos4 = string2.indexOf('window.ComponentArt_Init_', pos3 + 5);
              var pos5 = string2.indexOf('//]]>', pos4 + 1);
              var funpos = string2.indexOf('=', pos4 + 1);
              if ( pos4 > -1 && pos5 > -1 && funpos > -1)
              {
                var string3 = string2.substring(0, pos5);
                var pos6 = string3.lastIndexOf('}');
                if ( pos6 > -1 )
                {
                  // init function name
                  var functionName = string2.substring(pos4, funpos-1);
                  functionName = functionName.replace(' ','');
                  functionName = functionName + '()';

                  var evalInitString = string3.substring(pos4, pos6 + 1);

                  // eval the string
                  eval(evalInitString);

                  // now execute it now that we've redefined it
                  eval(functionName);
                  
                  // set status
                  continueLoop = 1;
                } // end if pos6
              } // end if pos4 and pos5
            } // end if pos2 and pos3 and funpos

            // get remain string
            remainString = string2.substring(pos5 + 1);
          } // end if pos1
          else
          {
            remainString = '';
          }
        }while(remainString.length > 0 && continueLoop == 1) // end while length
      }
      else
      {
        ConceptTreeControl_ProcessCallBackError('ConceptTreeControl RepopulationCallBackDone: Holder div not found.', '');
      }
    } // end if need repopulation block
      
    try
    {
      SrmControl_RecordTimes(repop[1]);
    }
    catch(e) 
    {}
  } // end status error else block
  
  // mark the end of the Topic Control Callback
  //if (TopicControlBusyFlag)
    //TopicControlBusyFlag = null;
  
  try
  {
    if (m_srmGetTimes != null && m_srmGetTimes == "True")
    {
      var now = new Date();
      var time = Math.round(now.getTime() - start.getTime()) / 1000;
      var message = 'Time,ConceptTreeControl_RepopulateCallbackDone,' + s[0] +': ' + time;
      setTimeout("SrmControl_QuickCallback('" + message + "')",1);
    }
  }
  catch(e) 
  {}
  m_treeViewIsLoaded = true;
}// end function


// Handle alert toggle
function ConceptTreeControl_ChangeAlertSetting(_event, _status, _value, _callBackReference, _srmIndex)
{
  try
  {
    if (m_srmGetTimes!= null && m_srmGetTimes == "True")
      m_srmAction[_srmIndex] += ',Concept=' + _value + ',AlertSetting=' + _status;
  }
  catch(e){}

  //alert(value); 
  var args = 'Concept=' + _value + '|AlertSetting=' + _status + '|SrmIndex=' + _srmIndex;
  // trigger callback
  eval(_callBackReference);
  CancelBubble(_event);
}// end function

// Handle float over concept with mouse
function ConceptTreeControl_OnNodeMouseOver_Wrapped(_node, _displayMode, _eventArgs)
{
  if (_node != null)
  {
    var refocusImgId = _displayMode + '_' + _node.get_id() + '_refocusCell';
    var refocusImg = document.getElementById(refocusImgId);
    if (refocusImg != null)
      refocusImg.className = 'RefocusCellShown';
  }
}

// Handle move mouse off concept
function ConceptTreeControl_OnNodeMouseOut_Wrapped(_node, _displayMode, _eventArgs)
{
  if (_node != null)
  {
    var refocusImgId = _displayMode + '_' + _node.get_id() + '_refocusCell';
    var refocusImg = document.getElementById(refocusImgId);
    if (refocusImg != null)
      refocusImg.className = 'RefocusCellHidden';
  }
}

function GrabHighlightedMyKnowledgeContext(_treeID)
{
  dblClickSearchPhrase = "";
  var aTreeView = null;
  var aTreeNode = null;
  var nodeId = _treeID.SelectedNode.ID;
  var treeId = _treeID.TreeViewID;
  
  if(treeId != null && treeId !='' && treeId != '-1' && eval('window.'+ treeId+'!=null'))
    aTreeNode = eval(treeId + '.FindNodeById(\'' + nodeId + '\')');

  if(aTreeNode != null)
  { 
    aTreeView = aTreeNode.ParentTreeView;
    
    if(aTreeNode.ID != null && aTreeNode.ID != '')
      conceptTreeControl_preTreeNodeID = aTreeNode.ID;
    
    if(aTreeView != null && aTreeView.TreeViewID != '')
      conceptTreeControl_preTreeViewID = aTreeView.TreeViewID;
  }

  while(aTreeNode != null)
  {
    aTreeNode.SaveState();
    dblClickSearchPhrase = aTreeNode.Text + " " + dblClickSearchPhrase;
    aTreeNode = aTreeNode.ParentNode;
  }
    
} // end function

// Wrapper of ConceptTreeControl_OnNodeSelect - set timeout to separate double and single click
function ConceptTreeControl_OnNodeSelect_Wrapper(_treeView, _conceptID, _mapViewDisplayMode, _clientSideOnConceptSeleted, _srmIndex)
{
  var aTreeView = _treeView;
  var aTreeNode = null;
  var treeViewID = '-1';
  var treeNodeID = '-1';
  
  if(aTreeView != null)
  {
    aTreeNode = aTreeView.SelectedNode;
    treeViewID = aTreeView.TreeViewID;
    if(aTreeNode!= null && aTreeNode.ID != '')
      treeNodeID = aTreeNode.ID;
  }
  
  globalConceptTreeTimer = 1;
  ConceptTreeControl_SelectConcept(treeViewID, treeNodeID, _conceptID, _mapViewDisplayMode, _clientSideOnConceptSeleted, _srmIndex);
	//DoCollapseMapViewPane(); //Need to remove to stop bug 5397
}

// Concept selection
function ConceptTreeControl_SelectConcept(_treeViewID, _treeNodeID, _conceptID, _mapViewDisplayMode, _clientSideOnConceptSeleted, _srmIndex)
{
  if (window.CancelEdit)
    CancelEdit(true);
    
  // Lowlight Previous Tree Node
  ConceptTreeControl_LowlightTreeNode(conceptTreeControl_preTreeViewID, conceptTreeControl_preTreeNodeID);
  
  // Highlight Selected Tree Node
  ConceptTreeControl_HighlightTreeNode(_treeViewID, _treeNodeID);
  
  if (_treeViewID.indexOf('ResultTree') > -1)
    hideRootNode(_treeViewID)
    
  var nodeID = _conceptID.split('-');
  var nodeType = nodeID[0];
  var idvalue = _conceptID.substring(nodeID[0].length + 1);
  try 
  {
    if (m_srmGetTimes!= null && m_srmGetTimes == "True" && _srmIndex != null)
      m_srmAction[_srmIndex] += ',' + _conceptID;
  }
  catch(e){}

  if(nodeType.indexOf('What') != -1)
  {
    // what clicked
    // set selectedKGID session variable for MapView to update the MapView
    SetSessionProperty('SelectedKGID', idvalue);
    SetSessionProperty('PageSession_KGSelectedKnowdeID', idvalue);
    SetSessionProperty('MapViewDisplayMode', _mapViewDisplayMode);
    MapViewControl1_CallbackTrigger_IfVisible(_srmIndex);
    //KGTabbedWindowsControl_CallbackTrigger('KnowdeSelected', _srmIndex);
  }
  else
  {
    // concept clicked
    SetSessionProperty('PageSession_KGSelectedConceptID', idvalue);
    SetSessionProperty('MapViewDisplayMode', _mapViewDisplayMode);
    MapViewControl1_CallbackTrigger_IfVisible(_srmIndex);
    //KGTabbedWindowsControl_CallbackTrigger('ConceptSelected', _srmIndex);
    
    if(m_bEditable == true)
    {
    m_bEditable = false;
      //SwitchEditableFlag();
    }
  }
  
  if(_clientSideOnConceptSeleted != null && _clientSideOnConceptSeleted.length > 0)
    eval(_clientSideOnConceptSeleted);
  
}// end function

// Highlight Tree Node
function ConceptTreeControl_HighlightTreeNode(_treeViewID, _treeNodeID)
{
  var aTreeView = null;
  var aTreeNode = null;
  var treeId = _treeViewID;
  var nodeId = _treeNodeID;
  
  if(treeId != null && treeId !='' && treeId != '-1' && eval('window.'+ treeId+'!=null'))
    aTreeNode = eval(treeId + '.FindNodeById(\'' + nodeId + '\')');

  if(aTreeNode != null)
  { 
    aTreeView = aTreeNode.ParentTreeView;
    
    if(aTreeNode.ID != null && aTreeNode.ID != '')
      conceptTreeControl_preTreeNodeID = aTreeNode.ID;
    
    if(aTreeView != null && aTreeView.TreeViewID != '')
      conceptTreeControl_preTreeViewID = aTreeView.TreeViewID;
  }

  if (aTreeView)
    aTreeView.beginUpdate();
    
  while(aTreeNode != null)
  {
    aTreeNode.set_cssClass('SelectedConcept');
    aTreeNode.SaveState();
    aTreeNode = aTreeNode.ParentNode;
  }
  
  if (aTreeView)
    aTreeView.endUpdate();
} // end function

function endUpdateNoRender(_treeView)
{
  _treeView._updating=false;
}

// Lowlight Tree Node
function ConceptTreeControl_LowlightTreeNode(_treeViewID, _treeNodeID)
{   
    var aTreeNode = null;
    var aTreeView = null;
    var treeId = _treeViewID;
    var nodeId = _treeNodeID;
    
    if(treeId != null && treeId !='' && treeId != '-1' && eval('window.'+ treeId+'!=null'))
    {
      aTreeNode = eval(treeId + '.FindNodeById(\'' + nodeId + '\')');
      
      if(aTreeNode != null)
      {
        aTreeView = aTreeNode.ParentTreeView;
      }
      
      if (aTreeView)
        aTreeView.beginUpdate();
      
      while(aTreeNode != null)
      {
        aTreeNode.set_cssClass('Concept');  // Change the class so it actually gets unhighlighted
        aTreeNode.SaveState();
        aTreeNode = aTreeNode.ParentNode;  //work up through its parents, lowlighting them as well
      }
      
      if (aTreeView)
        endUpdateNoRender(aTreeView);
    }
 }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Scrolling functions

function DetachScrolling_Wrapped(_treeView)
{
  alert('First node ' + m_firstTopNode + '\r\nLast node ' + m_lastTopNode);
  var div = GetParentDiv(_treeView);
  div.onscroll = null;
  div.onresize = null;
}

// this needs calling after the tree is rendered - it will always show the root node, so it moves the tree down
function hideRootNode(_treeViewId)
{
  if (m_rootNodeIsHidden) // it was hidden before, and should be hidden again now
  {
    var treeView = eval(_treeViewId);
    if (treeView.Frame != null)
    {
      var rootNodeTable = treeView.Frame.childNodes[0];
      if (rootNodeTable != null)
        rootNodeTable.style.display="none";
    }
  }
}

// global variables
var m_globalConceptTreeTimerScroll = null;
var m_firstTopNode = 0; // used to determine which nodes to get from the server, whether to hide or show the root node and whether we need more nodes
var m_lastTopNode; // used to determine which nodes to get from the server, and to calculate m_firstTopNode
var m_totalTopNodes = 0; // top nodes in the *whole* tree, rather than just the visible part. Get from server.
var m_lastPosition=0; // last scrolled position
var m_rootNodeIsHidden = false;
var m_treeViewIsLoaded = false;
var m_scrolling = false; // already doing scrolling work, don't do two at once
var m_refire = false; // if m_scrolling, use m_refire to tell it to fire a new scroll when it's done

function ResetTreeScrollingVariablesWrapped(_treeView, _sessionNameForScrollPosition)
{ // reset the global variables and session variables if we're drawing a new tree (refocus, back button, click suggestion)
  m_globalConceptTreeTimerScroll = null;
  m_firstTopNode = 0;
  m_totalTopNodes = 0;
  m_lastPosition=0;
  m_rootNodeIsHidden = false;
  m_treeViewIsLoaded = false;
  m_scrolling = false;
  m_refire = false;
  setTimeout('ResetScrollbar(' + _treeView.TreeViewID + ')',1);

  SetSessionProperty(_sessionNameForScrollPosition, 0);
  SetSessionProperty('SearchResultTree_firstLoad', 'true');
}

// put the scrollbar to the top, without triggering the onscroll function
function ResetScrollbar(_treeView)
{
  var scrollingDiv = document.getElementById(scrollingDivID);
  if (scrollingDiv != null)
  {
    scrollingDiv.onscroll = null; // remove it temporarily so a callback isn't triggered when we move the scrollbar back to the top
    scrollingDiv.scrollTop = 0; 
    scrollingDiv.onscroll = SearchResult_TreeOnScrollTimer;
  }
}

function MoveScrollbar(_treeView, _position, _counter)
{
  if (scrollingDivID == null || scrollingDivID == '')
    return;
  var scrollingDiv = document.getElementById(scrollingDivID);
  if(scrollingDiv == null)
    return;
  scrollingDiv.scrollTop = _position;
  if (scrollingDiv.scrollTop != _position)
  {
    // it didn't move the div because it hasn't loaded yet, so try again
    // use _counter to make sure it doesn't get stuck in an infinite loop
    if (_counter != null)
      _counter++;
    else
      _counter = 1;
    if (_counter <= 10)
      window.setTimeout("MoveScrollbar(" + _treeView.TreeViewID + ", " + _position + ", " + _counter + ")",200);
  }
}

function TreeOnScrollTimerWrapped(_treeView, _loadingDivId)
{
  if(ConceptSelectedTab == 'Results')
  {
    if (_treeView.Frame == null)
      return;
      
    if (m_treeViewIsLoaded) // stops lots of calls on page load before the tree is fully loaded
      AddLoadingMessage(_treeView, _loadingDivId);
      
    if (m_scrolling)
      m_refire = true;
    else
    {  
      //onscroll fires too many times http://support.microsoft.com/kb/238004  
      clearTimeout(m_globalConceptTreeTimerScroll);
      m_globalConceptTreeTimerScroll = window.setTimeout('SearchResult_TreeOnScroll()', 200);
    }
  }else
  {
    clearTimeout(m_globalConceptTreeTimerScroll);
  }
}

function GetParentDiv(_treeView)
{ // this is the div that has the onscroll event attached to it, set in ConceptTabbedView.cs CreateChildControls
  var frame = _treeView.Frame;
  if (frame == null)
    return null;
  var div = frame.parentNode;
  if (div == null)
    return null;
  while (div.tagName != "DIV")
    div = div.parentNode;
  return div;
}

function AddLoadingMessage(_treeView, _loadingDivId)
{
  //debugger;
  //loadingDiv already exists (added in KGConceptTreeControl.cs), just need to position it and make it visible
  var loadingDiv = document.getElementById(_loadingDivId);
  if (loadingDiv == null)
    return;
  var div = GetParentDiv(_treeView);
  if (div == null || scrollingDivID == null || scrollingDivID == '')
    return;
  var scrollingDiv = document.getElementById(scrollingDivID);
  if(scrollingDiv == null)
    return;
    
  var titleLabel = document.getElementById('Library_LoginView_KGNavigationControl1_ctl03_Library_LoginView_KGNavigationControl1_ctl03_p1_ConceptTitleLabel');
  // get offset top
  var titleLabelTop = 0;
  var obj = titleLabel;
  if(obj.offsetParent)
  {
    do
    {
      if(obj.id == scrollingDiv.id)
        break;
      titleLabelTop += obj.offsetTop;
    }while(obj = obj.offsetParent);
  }
  titleLabelTop += 26;
  if(titleLabelTop < loadingDivOffset)
    titleLabelTop = loadingDivOffset; 

  var position = scrollingDiv.scrollTop;
  var screenHeight = scrollingDiv.clientHeight;
  
  var treeViewOuterTable = _treeView.Frame.parentNode.parentNode.parentNode;
  var spacerAbove = hkFirstChild(treeViewOuterTable.firstChild); // children are: spacerAbove, tree view, spacer below, status box
  var spacerBelow = hkFirstChild(treeViewOuterTable.childNodes[2]); 
  
  var treeStart = GetPixelHeight(spacerAbove);
  var treeEnd = treeStart + _treeView.Frame.offsetHeight + titleLabelTop;
  var totalHeight = treeEnd + GetPixelHeight(spacerBelow);
  
  if (position + screenHeight > treeEnd && totalHeight > treeEnd + 1) // there's empty space below the tree
  {
    loadingDiv.style.left = scrollingDiv.clientLeft;
    if (position > treeEnd)
      loadingDiv.style.top = scrollingDiv.clientTop + position; // Show at top of screen
    else
      loadingDiv.style.top = scrollingDiv.clientTop + treeEnd + _treeView.LineImageHeight; // Show at end of tree
       
    loadingDiv.style.display="block";
  }
  else if (position < treeStart -1) // there's empty space above the tree (initially spacerAbove.clientHeight = 1px) 
  {
    loadingDiv.style.left = scrollingDiv.clientLeft;
    loadingDiv.style.top = scrollingDiv.clientTop + position  + titleLabelTop; //Show at top of screen
    loadingDiv.style.display="block";
  }
  else
    loadingDiv.style.display="none";
}

function ResetForReturn(_loadingDivId)
{
  m_scrolling = false;
  var loadingDiv = document.getElementById(_loadingDivId);
  if (loadingDiv)
    loadingDiv.style.display="none";
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// OnScroll function to trigger callback
function TreeOnScrollWrapped(_treeView, _sessionNameForScrollPosition, _cbreference, _loadingDivId)
{
  //debugger;
  clearTimeout(m_globalConceptTreeTimerScroll);
  if(ConceptSelectedTab == 'Results')
  {
    ///debugger;
    m_scrolling = true;
    
    var nodes = _treeView.Nodes();
    if (nodes.length > 1) // multiple trees from search button - not paging this
    {
      ResetForReturn(_loadingDivId)
      return;
    }
    var rootNode = nodes[0];
    if (rootNode == null)
    {
      ResetForReturn(_loadingDivId)
      return;
    }
    if (!rootNode.Expanded)
    {
      ResetForReturn(_loadingDivId)
      return;
    }
    
    nodes = rootNode.Nodes();

    if (m_lastTopNode == 0 && m_firstTopNode == 0)
      m_lastTopNode = nodes.length;
        
    var lineHeight = _treeView.LineImageHeight; // height of one row in the tree
    var div = GetParentDiv(_treeView);
    if (div == null || scrollingDivID == null || scrollingDivID == '')
    {
      ResetForReturn(_loadingDivId)
      return;
    }
    var scrollingDiv = document.getElementById(scrollingDivID);
    if(scrollingDiv == null)
      return;
    var position = scrollingDiv.scrollTop;
    var screenHeight = scrollingDiv.clientHeight;
    
    // spacerAbove and spacerBelow keep the total height constant so the scroll bar looks right
    var treeViewOuterTable = _treeView.Frame.parentNode.parentNode.parentNode;
    var spacerAbove = hkFirstChild(treeViewOuterTable.firstChild); // children are: spacerAbove, tree view, spacer below, status box
    var spacerBelow = hkFirstChild(treeViewOuterTable.childNodes[2]); 

    // current tree start, end and total height; measured in pixels
    var initTreeStart = GetPixelHeight(spacerAbove);
    var initTreeEnd = _treeView.Frame.offsetHeight + GetPixelHeight(spacerAbove);
    var totalHeight = initTreeEnd + GetPixelHeight(spacerBelow);
    
    // required tree start and end after the scroll; measured in pixels
    var requiredTreeEnd = Math.min(totalHeight, position + 2*screenHeight);
    var requiredTreeStart = Math.max(0,position - screenHeight);
    var numExcessNodes;
    
    if (position >= m_lastPosition) // scrollbar moved down or resize screen or node(s) collapsed
    {
      if (requiredTreeEnd > initTreeEnd + 1 && (m_totalTopNodes == 0 || m_lastTopNode < m_totalTopNodes - 1)) //Do we need to load more nodes?
      {
        var numNodes = Math.floor((requiredTreeEnd - initTreeEnd)/lineHeight) + 1; // total nodes required (root + children)
          
        if (requiredTreeStart > initTreeEnd) // big change, don't need to add all the nodes
          numExcessNodes = Math.floor((requiredTreeStart - initTreeEnd)/lineHeight);
        else
          numExcessNodes = 0;
          
        var lastExistingNode = nodes[nodes.length-1];
        var nodeId = lastExistingNode.ID;
        var nodeType = nodeId.substring(0,nodeId.indexOf('_'));
        var text = lastExistingNode.Text;
        
        var sessionVariable = text + '@' + nodeType + '@' + numNodes + '@' + numExcessNodes;
        SetSessionProperty('SearchResultTree_Scrolling', sessionVariable);
        
        //Go back to the server
        var args = 'Action=scroll';
        args += '|scrollDirection=down';
        args += '|position=' + position;
        args += '|screenHeight=' + screenHeight;
        args += '|numExcessNodes=' + numExcessNodes;
        
        eval(_cbreference);
      } // end if load more nodes on scroll down
      else 
      {
        ResetForReturn(_loadingDivId)
      }
    }
    else if (position < m_lastPosition)//scrollbar moved up
    {
      if (m_firstTopNode > 0 && requiredTreeStart < initTreeStart) //Do we need to load more nodes?
      {
        //Add nodes above and fix spacer
        var numNodes = Math.floor((initTreeStart - requiredTreeStart)/lineHeight) + 1;
            
        if (requiredTreeEnd < initTreeStart) // big change, don't need to add all the nodes
          numExcessNodes = Math.floor((initTreeStart - requiredTreeEnd)/lineHeight);
        else
          numExcessNodes = 0;
        
        var lastExistingNode = nodes[0];
        var nodeId = lastExistingNode.ID;
        var nodeType = nodeId.substring(0,nodeId.indexOf('_'));
        var text = lastExistingNode.Text;
        
        var sessionVariable = text + '@' + nodeType + '@' + -numNodes + '@' + numExcessNodes;
        SetSessionProperty('SearchResultTree_Scrolling', sessionVariable);
          
        //Go back to the server
        var args = 'Action=scroll';
        args += '|scrollDirection=up';
        args += '|position=' + position;
        args += '|screenHeight=' + screenHeight;
        args += '|numExcessNodes=' + numExcessNodes;
        
        eval(_cbreference);
      } //if load more nodes on scroll up
      else
      {
        ResetForReturn(_loadingDivId)
      }
    } 
   
    // CM used to save the scroll position over a redirect/refresh
    SetSessionProperty(_sessionNameForScrollPosition, position);
    m_lastPosition = position;
  }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// After callback has finished
function ConceptTreeControl_CallbackDone(_args, _context)
{
  if (CheckSessionTimeout())
    return;
  
  if(_args.indexOf('Status=Error') > -1)
  {
    m_scrolling = false;
    return;
  }

  var argsSplit = _args.split('[@|@]');
  var info = argsSplit[0].split('@');
  var direction = info[0]; // the scroll direction, either 'up' or 'down'
  var treeViewId = info[1];
  var position = parseInt(info[2]); // the scroll position from the onscroll method - could have changed if there's been another scroll
  var screenHeight = parseInt(info[3]); // the screen height from the onscroll method
  var numExcessNodes = parseInt(info[4]); // for a big scroll, number of nodes between the previous tree end and the new tree start
  var lastNode = parseInt(info[5]); // the last node added to the tree - determined at the server
  var nodesPassedOver = parseInt(info[6]); // like numExcessNodes, but adjusted of there are children near the join
  var loadingDivId = info[7]; // the div that says 'Loading...'
  m_totalTopNodes = parseInt(info[8]); // number of top nodes in the tree (root node + top how, what, why children)
  
  var treeView = eval(treeViewId); 
  var rootNode = treeView.Nodes()[0];
  
  var newPosition;
  if (m_refire)
  {
    var scrollingDiv = document.getElementById(scrollingDivID);
    newPosition = scrollingDiv.scrollTop; // get this here - scrollbar sometimes moves when we edit the dom below. Need for next scroll
  }

  // lastNode is the last top node (root & first children) that was added at the server
  // if we scrolled up, the nodes were added upside down this is actually the first top node in the tree
  if (direction == "down")
    m_lastTopNode = lastNode;
  else
  {
    m_firstTopNode = lastNode;
    if (m_firstTopNode == 1)
      m_firstTopNode = 0;
  }
  
  var lineHeight = treeView.LineImageHeight
  var serverHeightChange = nodesPassedOver * lineHeight; // these nodes weren't added, just passed over

  var treeViewOuterTable = treeView.Frame.parentNode.parentNode.parentNode;
  var spacerAbove = hkFirstChild(treeViewOuterTable.firstChild); // children are: spacerAbove, tree view, spacer below, status box
  var spacerBelow = hkFirstChild(treeViewOuterTable.childNodes[2]); 
  
  var initTreeStart = GetPixelHeight(spacerAbove);
  var initTreeEnd = initTreeStart + treeView.Frame.offsetHeight;

  var requiredTreeEnd = position + 2*screenHeight;
  var requiredTreeStart = Math.max(0,position - screenHeight);

  var treeXmlString = argsSplit[1];
  //parse XmlString to XmlDocument
  //http://www.w3schools.com/dom/tryit.asp?filename=note_parsertest2
  // code for IE
  if (window.ActiveXObject)
  {
    var doc=new ActiveXObject("Microsoft.XMLDOM");
    doc.async="false";
    doc.loadXML(treeXmlString);
  }
  // code for Mozilla, Firefox, Opera, etc.
  else
  {
    var parser=new DOMParser();
    var doc=parser.parseFromString(treeXmlString,"text/xml");
  }
  var treeXml=doc.documentElement;

  if (direction == "down")
  {
    var bigChange = false;
    //If it was a big change, clear the tree
    if (numExcessNodes != 0 || initTreeEnd <= requiredTreeStart + 20)
    {
      spacerAbove.style.height = (GetPixelHeight(spacerAbove) + treeView.Frame.offsetHeight) + "px";
      ClearTree(rootNode);
      bigChange = true;
    }

    //Add nodes below and fix spacer
    var heightChange = lineHeight * AddNodesBelow(rootNode, treeXml.getElementsByTagName("Node")[1]); //start from 1 so don't add the root node
    if (m_lastTopNode == m_totalTopNodes - 1) // at the end of the tree
      spacerBelow.style.height = "1px"; // should be the same as below unless the tree changed between scrolls
    else
      spacerBelow.style.height = Math.max(1,GetPixelHeight(spacerBelow)-heightChange) + "px";

    if (!bigChange) // small change, need to remove nodes above
    {
      //Remove nodes above and fix spacer
      if (requiredTreeStart > initTreeStart)
      {
        var numNodes = Math.floor((requiredTreeStart - initTreeStart)/lineHeight);
        heightChange = lineHeight * RemoveNodesAbove(treeView, numNodes);
        spacerAbove.style.height = (GetPixelHeight(spacerAbove) + heightChange) + "px";
      }
      
      m_firstTopNode = m_lastTopNode - rootNode.Nodes().length + 1;
      
      //if the top node is 0, i.e. the root node, it will never be counted in the m_firstTopNode calculation above
      //if the top node really should be 1, it doesn't matter if you make it 0 and show the root node
      if (m_firstTopNode == 1) 
        m_firstTopNode = 0;
        
      //  render the tree
      //CMTEMP
      if (navigator.appName == "Microsoft Internet Explorer")
        PartialRenderSearchResult(treeView, 'down');
      else
        treeView.Render();
      if (m_firstTopNode != 0) // need to hide the root node. It's always in the tree so the other nodes can be children
      {
        var rootNodeTable = treeView.Frame.childNodes[0];
        rootNodeTable.style.display="none";
        if (!m_rootNodeIsHidden)
        {
          spacerAbove.style.height = (GetPixelHeight(spacerAbove) + lineHeight) + "px";
          m_rootNodeIsHidden = true;
        }
      }
    }
    else // big change, nodes above already removed - existing in ClearTree, others never added
    {
      m_firstTopNode = m_lastTopNode - rootNode.Nodes().length + 1;
      if (m_firstTopNode == 1)
        m_firstTopNode = 0;
      spacerAbove.style.height = (GetPixelHeight(spacerAbove) + serverHeightChange) + "px";
      spacerBelow.style.height = Math.max(1, GetPixelHeight(spacerBelow) - serverHeightChange) + "px";
      
      // render the tree 
      treeView.Render();
      if (m_firstTopNode != 0) // need to hide the root node. It's always in the tree so the other nodes can be children
      {
        var rootNodeTable = treeView.Frame.childNodes[0];
        rootNodeTable.style.display="none";
        m_rootNodeIsHidden = true;
      }
    }

  }
  else // scrolled up
  {
    //If it was a big change, clear the tree
    var bigChange = false;
    if (numExcessNodes != 0 || initTreeStart >= requiredTreeEnd - 20)
    {
      spacerBelow.style.height = (GetPixelHeight(spacerBelow) + treeView.Frame.offsetHeight) + "px";
      ClearTree(rootNode);
      bigChange = true;
    }

    //Add nodes above and fix spacer
    var lastXmlNode = treeXml.getElementsByTagName("Node")[1]; // Xml is upside down, so last Xml node = first tree node
    while (lastXmlNode.nextSibling != null)
      lastXmlNode = lastXmlNode.nextSibling;
    var heightChange = lineHeight * AddNodesAbove(rootNode, lastXmlNode);
    spacerAbove.style.height = Math.max(0,GetPixelHeight(spacerAbove)-heightChange) + "px";
    
    if (!bigChange)// small change, need to remove nodes above
    {
      //Remove nodes below and fix spacer
      if (requiredTreeEnd < initTreeEnd)
      {
        var numNodes = Math.floor((initTreeEnd - requiredTreeEnd)/lineHeight);
        heightChange = lineHeight * RemoveNodesBelow(treeView, numNodes);
        spacerBelow.style.height = (GetPixelHeight(spacerBelow) + heightChange) + "px";
      }
      m_lastTopNode = m_firstTopNode + rootNode.Nodes().length - 1;
      
      // render the tree
      if (navigator.appName == "Microsoft Internet Explorer")
        PartialRenderSearchResult(treeView, 'up');
      else
        treeView.Render();

      if (m_firstTopNode != 0) // hide the root node
      {
        var rootNodeTable = treeView.Frame.childNodes[0];
        rootNodeTable.style.display="none";
      }
      else if (m_rootNodeIsHidden) // show the root node
      {
        spacerAbove.style.height = "1px";
        m_rootNodeIsHidden = false;
        var rootNodeTable = treeView.Frame.childNodes[0];
        rootNodeTable.style.display="block";
      }
    }
    else // big change, nodes above already removed - existing in ClearTree, others never added
    {
      m_lastTopNode = m_firstTopNode + rootNode.Nodes().length - 1;
      spacerAbove.style.height = Math.max(1, GetPixelHeight(spacerAbove) - serverHeightChange) + "px";
      spacerBelow.style.height = (GetPixelHeight(spacerBelow) + serverHeightChange) + "px";
      
      // render the tree
      treeView.Render();
      
      if (m_firstTopNode != 0) // hide the root node
      {
        var rootNodeTable = treeView.Frame.childNodes[0];
        rootNodeTable.style.display="none";
      }
      else if (m_rootNodeIsHidden) // show the root node
      {
        spacerAbove.style.height = "1px";
        m_rootNodeIsHidden = false;
      }
    }
  }
  
  //Remove the loading message
  var loadingDiv = document.getElementById(loadingDivId);
  loadingDiv.style.display="none";
  
  m_scrolling = false;
  if (m_refire) //Scrollbar has been moved again
  {
    var scrollingDiv = document.getElementById(scrollingDivID);
    scrollingDiv.scrollTop = newPosition; 
    window.setTimeout("SearchResult_TreeOnScrollTimer()", 0);
    m_refire = false;
  }
  else
  {
    // Make sure the scrollbar is in the right place (it can move when you remove things from the dom)
    // Jumps if a scroll is stacked up, so only do this if m_refire == false
    var scrollingDiv = document.getElementById(scrollingDivID);
    scrollingDiv.scrollTop = position; 
  }
  setPaneWidths();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function ClearTree(_rootNode)
{
  var nodesArray = _rootNode.Nodes(); // keep root node, remove all its children
  for (var nodeIndex = 0; nodeIndex < nodesArray.length; nodeIndex ++)
  {
    node = nodesArray[nodeIndex];
    node.Remove();
  }
}

function AddNodesBelow(_parent, _xmlNode)
{
//xmlNode is for first child to add
//parent is either parent treeView node, or treeView for top level root nodes
  var nodesAdded = 0;
  var treeNode;
  
  while (_xmlNode != null) //make a tree view node from the xml node
  {
    treeNode = CreateTreeNode(_xmlNode);
    _parent.AddNode(treeNode);
    nodesAdded++;
    
    if (_xmlNode.firstChild != null) // add the children
    {
      if (treeNode.Expanded)
        nodesAdded += AddNodesBelow(treeNode, _xmlNode.firstChild)
      else // still need to add children so can be expanded, don't need to count for the height change
        AddNodesBelow(treeNode, _xmlNode.firstChild) 
    }
    
    _xmlNode = _xmlNode.nextSibling; // next root node
  }
  return nodesAdded;
}

function CreateTreeNode(_xmlNode)
{ // turn a node from the xml into a tree view node
  var attributes = _xmlNode.attributes;
  var att;
  
  treeNode = new ComponentArt.Web.UI.TreeViewNode();
  for (var j=0; j<attributes.length; j++)
  {
    att = attributes[j];
    if (att.nodeValue == "True")
      treeNode.SetProperty(att.nodeName, true);
    else if (att.nodeValue == "False")
      treeNode.SetProperty(att.nodeName, false);
    else
      treeNode.SetProperty(att.nodeName, att.nodeValue);
  }
  return treeNode;
}

function RemoveNodesAbove(_treeView, _numNodes)
{
  //_numNodes is a total number including children
  //before you remove a top node, check all its children are ok to be removed
  //only need to remove top nodes
  var nRemovedNodes = 0;
  var node;
  var nChildren;
  var topNode = 0;
  
  var rootNode = _treeView.Nodes()[0];
  var rootNodeDiv = _treeView.Frame.childNodes[1];
  var nodesArray = rootNode.Nodes();
  
  var divDom; //From the Component Art Tree View inner html - remove them here then Partial Render method can be used
  var tableDom;
  
  while (nRemovedNodes < _numNodes)
  {
    node = nodesArray[topNode];
    if (node.Expanded)
    {
      nChildren = NumberOfChildNodes(node);
      if (nRemovedNodes + nChildren > _numNodes)
        break;  
      nRemovedNodes += nChildren;
    }
    else if (nRemovedNodes > _numNodes)
      break;  
    
    nRemovedNodes++;
    node.Remove();
    
    //update DOM for partial render
    tableDom = rootNodeDiv.childNodes[0]; 
    divDom = rootNodeDiv.childNodes[1];
    purge(tableDom);
    tableDom.parentNode.removeChild(tableDom);
    purge(divDom);
    divDom.parentNode.removeChild(divDom);
    
    topNode ++;
  }
  
  return nRemovedNodes;
}

function AddNodesAbove(_rootNode, _xmlNode)
{
//Can only add nodes to end of tree
//First save original nodes, remove then add again later
//xml from server has top nodes upside down, child nodes right way up
//xmlNode is for last xml child (= first tree View node)
//parent is root node
  var nodesAdded = 0;
  var treeNode;
  var originalNodes = _rootNode.Nodes();
  
  //remove original nodes
  for (var nodeIndex = 0; nodeIndex < originalNodes.length; nodeIndex ++)
  {
    node = originalNodes[nodeIndex];
    node.Remove();
  }
  
  while (_xmlNode != null) //make a tree view node from the xml node
  {
    treeNode = CreateTreeNode(_xmlNode);
    _rootNode.AddNode(treeNode);
    nodesAdded++;
    
    if (_xmlNode.firstChild != null) // add the children
    {
      if (treeNode.Expanded)
        nodesAdded += AddNodesBelow(treeNode, _xmlNode.firstChild)
      else // still need to add children so can be expanded, don't need to count for the height change
        AddNodesBelow(treeNode, _xmlNode.firstChild)
    }
    
    _xmlNode = _xmlNode.previousSibling; // next root node (xml root nodes are upside down for scroll up)
  }
  
  //re-add original nodes
  for (var nodeIndex = 0; nodeIndex < originalNodes.length; nodeIndex++)
  {
    node = originalNodes[nodeIndex];
    _rootNode.AddNode(node);
  }
  
  return nodesAdded;
}

function RemoveNodesBelow(_treeView, _numNodes)
{
  //_numNodes is a total number including children
  //before you remove a root node, check all its children are ok to be removed
  //only need to remove root nodes
  var nRemovedNodes = 0;
  var node;
  var nChildren;
  
  var rootNode = _treeView.Nodes()[0];
  var rootNodeDiv = _treeView.Frame.childNodes[1];
  var nodesArray = rootNode.Nodes();
  var nodeIndex = nodesArray.length - 1;
  
  var nodesDomArray;
  var divDom; //From the Component Art Tree View inner html - remove them here then Partial Render method can be used
  var tableDom;
  
  while (nRemovedNodes < _numNodes)
  {
    node = nodesArray[nodeIndex];
    
    if (node.Expanded)
    {
      nChildren = NumberOfChildNodes(node);
      if (nRemovedNodes + nChildren > _numNodes)
        break;  
      nRemovedNodes += nChildren;
    }
    else if (nRemovedNodes > _numNodes)
      break;  
    
    nRemovedNodes++;
    node.Remove();
    
    //update DOM for partial render
    nodesDomArray = rootNodeDiv.childNodes;
    tableDom = nodesDomArray[(nodesDomArray.length-2)];
    divDom = nodesDomArray[(nodesDomArray.length-1)];

    purge(tableDom);
    tableDom.parentNode.removeChild(tableDom);
    purge(divDom);
    divDom.parentNode.removeChild(divDom);
    
    nodeIndex --;
  }
  return nRemovedNodes;
}

function NumberOfChildNodes(_parent)
{
//loop through all the children
  var nChildNodes = 0;
  if (_parent.Expanded)
  {
    var children = _parent.Nodes();
    nChildNodes = children.length;
    for (var c=0; c<children.length; c++)
      nChildNodes += NumberOfChildNodes(children[c]);
  }
  return nChildNodes;
}   

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function PartialRenderSearchResult(_treeView, _direction)
//window.ComponentArt_TreeView.prototype.PartialRender=function(qzja)
{
  if (_treeView == null)
    return;
  _treeView.element=_treeView.Frame=document.getElementById(_treeView.DivName);
  if (_treeView.Frame == null)
    return;
  var qzon=_treeView.GetProperty('CssClass');
  if(qzon)
    _treeView.Frame.className=qzon;
  var qza=[];

  ////////////////////-------------------------------------------------------------------------------------  
  var rootNode = _treeView.Nodes()[0];
  var qzsm=rootNode.Nodes();
  var rootNodeFrame = document.getElementById(_treeView.TreeViewID + '_item_0_div');

  var nElements = rootNodeFrame.childNodes.length;
  var nRenderedTopChildNodes = nElements/2;
  
  if (nElements == 0)
    return;
    
  if (_direction == "down")
  {
    var lastTable = rootNodeFrame.childNodes[nElements-2];
    var lastDiv = rootNodeFrame.childNodes[nElements-1];
    purge(lastTable);
    lastTable.parentNode.removeChild(lastTable);
    
    for(var qzba=nRenderedTopChildNodes-1;qzba<qzsm.length;qzba++)
    {
      if(qzsm[qzba] && qzsm[qzba].Visible)
      {
        qza[qza.length]=qzsm[qzba].GetHtml();
      };
    };

    SetOuterHtml(lastDiv,qza.join(''));
  }
  else
  {
    var firstTable = rootNodeFrame.childNodes[0];
    var firstDiv = rootNodeFrame.childNodes[1];
    firstTable.removeNode(true);
  
    for(var qzba=0; qzba<qzsm.length-nRenderedTopChildNodes+1;qzba++)
    {
      if(qzsm[qzba] && qzsm[qzba].Visible)
      {
        qza[qza.length]=qzsm[qzba].GetHtml();
      };
    };

    SetOuterHtml(firstDiv,qza.join(''));
  }
  ////////////////////-------------------------------------------------------------------------------------
  
  if(_treeView.KeyboardEnabled)
    ComponentArt_InitKeyboard(_treeView);
    
  if(!_treeView.AllowTextSelection&&cart_browser_ie)
    _treeView.Frame.onselectstart=ComponentArt_CancelEvent;
    
  if(_treeView.HoverPopupEnabled)
    setTimeout(_treeView.TreeViewID+'.GenerateHoverPopups()',200);
};

function HandleRefocusClick(_refocusDiv, _text)
{
  if(_text.substring(0,1) == ' ')
    _text = _text.substring(1); // trim out space, fix for bug 5295
  SetSessionProperty('HideSearchResultItemInfo', 'true');
  var nodeID = _refocusDiv.id.split('_');
  var displayMode = nodeID[0];
  var nodeType = nodeID[1];
  // only deal with refocus on concept, not for what at the moment
  //if(nodeType.indexOf('What') < 0)
  //{
    globalConceptTreeTimer = null;
    var itemID = nodeID[2];
    var itemName = _text;
    
    if(itemID != null && itemID != '0' && itemID != "-1")
    {
      SetSessionProperty("ConceptTreeControl_RefousTreeView_NewSelectedRootID", itemID);
    }
    
    if (displayMode == 'SearchResult')
      SearchResult_ResetTreeScrollingVariables();
     
    KGNavigationControl_RefocusTreeView(itemID);
  //}
  m_contextString = _text;
}// end function

// ConceptTabbedView JScript File
var global_ConceptTabbedControl_CurrentlySelectedTab = 'none';

function KGOptionControl_OptionChange(tab, _modeAlertCheck, _administrator, _bCategoryAdministrator)
{
  //debugger;
  try
  {
    if(document.getElementById('KGOptionControlID1') != null)
    {
      var optiondiv = document.getElementById('KGOptionControl');
      var loginview = "Library_LoginView_";

      try
      {
          loginview = "Library_LoginView_";
          var check = document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewKgIcon.png";
      }
      catch(Exception)
      {
        loginview = "";
      }
      switch(tab.ID)
      {
      case "Personal":     

//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewKgIcon.png";  
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").width = 30;       
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = function(){ShowKGNewKnowledgeGeneControl()};       
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='pointer'};
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "Create new Knowledge Gene in \"My Knowledge\"";
            
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon.png";
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = function(){KGPrivateSpaceCreatedControl_CreatePrivateSpace()};
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='pointer'};
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "Create a Community/Sub-Community Space";
            
            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon_Grey.png";
            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = "";
            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='default'};
            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "";
         
          break;
      case "Library":

//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon_Grey.png";
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = "";
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='default'};
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "";
//            
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon_Grey.png";
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = "";
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='default'};
//            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "";
            
            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon_Grey.png";
            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = "";
            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='default'};
            document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "";
       
          break;   
      case "Results":  
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon_Grey.png";
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = "";
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='default'};
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "";
       
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon_Grey.png";
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = "";
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='default'};
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "";
          
          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon_Grey.png";
          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = "";
          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='default'};
          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "";
        
          break;   
      default:
        // This is for Community Space Tabs that have been dynamically created
        // They all start with CS_
        if(tab.ID.substr(0,3) == 'CS_')
        { 
          if(_administrator == 1 && tab.Text != "Categories")
          {
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon_Grey.png";
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = "";
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='default'};
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber1").title = "";
          
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon.png";
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = function(){KGPrivateSpaceCreatedControl_CreatePrivateSpace()};
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='pointer'};
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "Create a Community/Sub-Community Space";
//          
          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/Cog2.png";        
          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = function(){KGPrivateSpaceAdminControl_OpenPrivateSpace()};       
          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='pointer'};
          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "Configure your Community Space";
          }
          else
          {
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon_Grey.png";
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = "";
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='default'};
//          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "";
          
            // If they are a category Administrator they can add new categories 
//            if(_bCategoryAdministrator = true)
//            {
//              document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon.png";
//              document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = function(){KGPrivateSpaceCreatedControl_CreatePrivateSpace()};
//              document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='pointer'};
//              document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "Create a Community/Sub-Community Space";          
//            }
//            else
//            {
//              document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon_Grey.png";
//              document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = "";
//              document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='default'};
//              document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "";
//            }
          
          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").src = "Images/NewCategoryIcon_Grey.png";        
          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onclick = "";       
          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").onmouseover = function(){this.style.cursor='default'};
          document.getElementById(loginview + "ConceptTabbedView1_KGOptionControl_ImageNumber0").title = "";
          }      
        }
          break;    
      }
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function ConceptTabbedView_SelectInitialTab(_tabStrip, _srmIndex)
{
  //debugger;
  try
  {
    SetRepopulationHiddenFields();
    
    var tab = _tabStrip.GetSelectedTab();
    if (tab.ID == "PrivateSpace")
    {
       ConceptTabbedView1_SelectPersonalTab();
       tab = _tabStrip.GetSelectedTab();
    }
    
    // vertical tab strip selected tab will be hidden
    ConceptTabbedView_TabSelected(null, null, tab, _srmIndex);
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function ConceptTabbedView1_UpdateTabTextAndTitle_Wrapper(_tabStripClientID, _tabID, _titleLabelClientID, _tabContextSeparator, _subfixName)
{
  //debugger;
  try
  {
    var tabStrip = _tabStripClientID;
    if(tabStrip != null)
    {
      var tab = tabStrip.FindTabById(_tabID);
      if(tab != null)
      {
        // update tab text
        ConceptTabbedView_UpdateTabText(tab, _tabContextSeparator, _subfixName);
        
        // update title lable
        var titleLabel = document.getElementById(_titleLabelClientID);
        if(titleLabel != null)
        {
          titleLabel.innerHTML = tab.Text;
        }
      }
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function ConceptTabbedView_UpdateTabText(_tab, _tabContextSeparator, _subfixName)
{
  //debugger;
  try
  {
    // set the correct tab name
    var tabName = _tab.Text;
    var separatorIndex = tabName.indexOf(_tabContextSeparator);
    
    // If the subfix name is no length we wish to remove the last item as going up a level
    // if(_subfixName.length == 0)
    // This has broken the original function. this method shouldn't be changed, it should be the code that calling into this function
    // to pass in the correct Full subFixName or empty if don't need subfix
    if(separatorIndex > 0)
    {
      tabName = tabName.substring(0, separatorIndex);
    }
      
    if(_subfixName.length > 0)
    {
      // capitalize first letter
      _subfixName = _subfixName.substring(0,1).toUpperCase() + _subfixName.substring(1);
      tabName = tabName + _tabContextSeparator + _subfixName;
    }
    
    if(_tab.Text != tabName) 
    {
      _tab.Text = tabName;
      _tab.SaveState();
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}


function ConceptTabbedView1_SwitchTabs_Wrapper(_tabStripClientID, _tabID, _titleLabelClientID, _tabContextSeparator, _subfixName, _groupNameHiddenField, _groupIDHiddenField)
{
  //debugger;
  try
  {
    // show the previously selected tab
    var tabStrip = _tabStripClientID;
    if(tabStrip != null)
    {
      var tab = tabStrip.FindTabById(_tabID);
      if(tab != null)
      {
        // updat tab text
        if(_subfixName != null && _subfixName.length > 0)
        {
          ConceptTabbedView_UpdateTabText(tab, _tabContextSeparator, _subfixName);
        }
        
        // switch tabs
        if(global_ConceptTabbedControl_CurrentlySelectedTab != null && global_ConceptTabbedControl_CurrentlySelectedTab != tab.ID)
        {
          var previousTab = tabStrip.FindTabById(global_ConceptTabbedControl_CurrentlySelectedTab);
          if(previousTab != null)
          {
            previousTab.Visible = 1; 
            previousTab.SaveState();
          }
        }
        // select current tab
        global_ConceptTabbedControl_CurrentlySelectedTab = tab.ID;
        SetSessionProperty('ConceptTabbedView_SelectedTab', tab.ID);
        
        // Set hidden fields
        var groupName = document.getElementById(_groupNameHiddenField);
        if(groupName != null)
        {
          groupName.value = "Temp Text";
        }
        
        var groupID = document.getElementById(_groupIDHiddenField);
        if(groupID != null)
        {
          groupID.value = tab.ID;
        }
        
        ConceptTabbedView_ChangeBackButtonMode(ShowBackButton(tab));
        
        // hide the current tab and set the title
        tab.Visible = 0; 
        tab.SaveState();
        
        var titleLabel = document.getElementById(_titleLabelClientID);
        if(titleLabel != null)
        {
          titleLabel.innerHTML = tab.Text;
        }
      }
    }

    var currentLocation = window.location.href;
		var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
    if(window.location.href == hostURL + "PrivateSpaceAdmin.aspx" && tab.ID.substr(0,3) != 'CS_')
    {
      window.location = "home.aspx";
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

// Client Side On Tab Select
function ConceptTabbedView_TabSelected_Wrapped(tab, _tabStripClientID, _titleLabelClientID, _modeAlertCheck, _cbreference, _personalLibDropDownListClientID, _groupID, _hiddenfieldID, _administrator, _srmIndex, _bCategoryAdministrator)
{
  //debugger;
  try
  {
    if(tab != null)
    {
      SetSessionProperty('KGCurrentTabID', tab.ID);
      
      try
      {
        if (m_srmGetTimes!= null && m_srmGetTimes == "True" && _srmIndex != null)
          m_srmAction[_srmIndex] += ',' + tab.ID;
      }
      catch(e){}
      
      ConceptTabbedView1_SwitchTabs(tab.ID, null);
      
      var oddl = document.getElementById(_personalLibDropDownListClientID);

      switch(tab.ID)
      {
      case "Personal": 
          KGOptionControl_OptionChange(tab, _modeAlertCheck, _administrator, _bCategoryAdministrator);
          SetSessionProperty('KGCurrentGroupID', _groupID);
          SetSessionProperty('Topics_SelectedTopicGroupId', null);
          SetSessionProperty('Topics_SelectedTopicName', null);
          break
      case "Results":
          KGOptionControl_OptionChange(tab, _modeAlertCheck, _administrator, _bCategoryAdministrator);
          SetSessionProperty('KGCurrentGroupID', _groupID);
          SetSessionProperty('Topics_SelectedTopicGroupId', null);
          SetSessionProperty('Topics_SelectedTopicName', null);
          break;
      case "Library":
          KGOptionControl_OptionChange(tab, _modeAlertCheck, _administrator, _bCategoryAdministrator);
          SetSessionProperty('Topics_SelectedTopicGroupId', null);
          SetSessionProperty('Topics_SelectedTopicName', null);
          break
      default:
        // This is for Community Space Tabs that have been dynamically created
        // They all start with CS_ also includes the category tab
        if(tab.ID.substr(0,3) == 'CS_')
        {
          KGOptionControl_OptionChange(tab, _modeAlertCheck, _administrator, _bCategoryAdministrator);
          
          // To set the correct Group ID we use the ID from the Tab ID
          var groupID = tab.ID.substr(3,tab.ID.length - 1)
          
          SetSessionProperty('KGCurrentGroupID', groupID);
        }
        else
        {
          SetSessionProperty('KGCurrentGroupID', -1);
        }
      }

      if(oddl != null)
      {
        if(tab.ID == 'Personal')
        {
          oddl.className = 'PersonalLibDropDownList';
        }
        else
        {
          oddl.className = 'PersonalLibDropDownListHidden';
        } // end if tab.ID
      } // end if oddl
//debugger;
      var repopulateStatus = document.getElementById(_hiddenfieldID);
      if (repopulateStatus != null && repopulateStatus.value.indexOf(tab.ID + '|') > -1)
      {
        // This check is to ensure that it repopulates all instances of the Community Spaces Tab
        // This also incudes the Category Tab as well.
        if(tab.ID.substr(0,3) != 'CS_')
          repopulateStatus.value = repopulateStatus.value.replace(tab.ID + '|', '');
        
        var args = 'Action=RepopulateTab|TabID=' + tab.ID + '|SrmIndex=' + _srmIndex;
        eval(_cbreference);
      } // end if repopulate status true
      
      if (window.MapViewDefaultFocus)
        MapViewDefaultFocus();
        
      var currentLocation = window.location.href;
      var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
      if (currentPage.indexOf('home') > -1 || currentPage.length == 0)
        HomeContentControl_CallbackTrigger();
    } 
    return true; //end tab null if
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
} //end function

// Personal library drop list selection changed
function ConceptTabbedView_PersonalLibOptionsChanged_Wrapped(_cbreference, _personalLibDropDownListClientID, _optionDivClientID, _personalLibraryContentConcepts)
{
  //debugger;
  try
  {
    var personalLibDDL = document.getElementById(_personalLibDropDownListClientID);
    if(personalLibDDL != null)
    {
      var selectedOption = personalLibDDL.options[personalLibDDL.selectedIndex].value;
      SetSessionProperty('ConceptTabbedView_PersonalLibContent',selectedOption);
      var odiv = document.getElementById(_optionDivClientID);
      if(odiv != null)
      {
        if(selectedOption == _personalLibraryContentConcepts)
        {
          odiv.className = 'SubscriptionOptionCell';
        }
        else
        {
          odiv.className = 'SubscriptionOptionCellHidden';
        } // end if tab.ID
      } // end if odiv    
      var args = 'Action=RepopulateTab|TabID=Personal';
      eval(_cbreference);
    } // end if not null
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
} //end function

// RePopulateCallbackDone - Also used when Subscription changed as well
function ConceptTabbedView_RepopulateTabCallbackDone_Wrapped(args, context,_tabStripClientID)
{
  //debugger;
  try
  {
    // Check for a session time out before completing the callback
    if (CheckSessionTimeout())
      return;
    if(args.indexOf('Status=Error') > -1)
    {
      var statusInfo = args.split('[@|@]'); 
      var status = statusInfo[0].split('=');
      if(status[1]=='Error')
      {
        var holderID = statusInfo[1].split('=');
        var exception = statusInfo[2].split('=');
        var callbackerror = holderID[1] + '=' + exception[1];
        ConceptTabbedView_ProcessCallBackError(callbackerror, '');
      }
    }
    else
    {
      var scriptToCall = args.split('[@|@]');
      var scriptFunction = scriptToCall[0].split('=');
      if(scriptFunction[1].length > 0)
      {
        var newArgs = args.substring(args.indexOf('[@|@]') + 5);
        eval(scriptFunction[1] + '(newArgs, context)');
      }
      else
      {
        ConceptTabbedView_ProcessCallBackError('Script function not found.', '');
      }
    }
    
    var tabStrip = _tabStripClientID;
    var tab = tabStrip.GetSelectedTab()
    
    var lastRootNodeHiddenFieldClientID;
    var lastRootNodeHiddenField;
    if (tab.ID == "Results")
    {
      lastRootNodeHiddenFieldClientID = SearchResult_GetLastRootNodeHiddenFieldID();
      lastRootNodeHiddenField = document.getElementById(lastRootNodeHiddenFieldClientID);
    }
    else if (tab.ID.substr(0,3) == 'CS_')
    {
      if (window.Topic_GetLastRootNodeHiddenFieldID)
      {
        lastRootNodeHiddenFieldClientID = Topic_GetLastRootNodeHiddenFieldID();
        lastRootNodeHiddenField = document.getElementById(lastRootNodeHiddenFieldClientID);
      }
    }
    else if (tab.ID == "Personal")
    {
      lastRootNodeHiddenFieldClientID = PersonalLibrary_GetLastRootNodeHiddenFieldID();
      lastRootNodeHiddenField = document.getElementById(lastRootNodeHiddenFieldClientID);
    }

    if (lastRootNodeHiddenField != null)
    {
      if(args.indexOf('lastRootNodeID:') > -1)
      {
        var subLastRootNodeID = args.split('lastRootNodeID:');
        lastRootNodeHiddenField.value = subLastRootNodeID[1];
      }
      else
      {
        lastRootNodeHiddenField.value = null;
      }
      
      ConceptTabbedView_ChangeBackButtonMode(ShowBackButton(tab));
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

// UpdateRepopulationHiddenFields
function SetRepopulationHiddenFields_Wrapped(_hiddenfieldID, _statusInfo) 
{
  //debugger;
  try
  {
    var repopulateStatus = document.getElementById(_hiddenfieldID);
    if (repopulateStatus != null) 
    {
      var statusInfo = '';
      // set status
      statusInfo = statusInfo + _statusInfo;
      repopulateStatus.value = statusInfo;
    } // end if repopulate status is not null
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
} //end function

// ProcessCallBackError
// this will return message in case of error
function ConceptTabbedView_ProcessCallBackError(args, context)
{
  //debugger;
  try
  {  
    // Here we are dealing with authentication timeout before callback, 
    // the message from the server is 'elogin' signify an error with 
    // authentication. The response will be trimmed to form the args 
    // 'login' here..... 
    if(args == 'login')
    {
      window.location='home.aspx';
    }
    else
    {
      if(args.indexOf('=') > -1)
      {
        var s = args.split('='); 
        var holder = document.getElementById(s[0]);
        if(holder != null)
        {
          holder.innerHTML = 'An error has occurred. ' + s[1];
        }
        else
        {
          alert('Exception occurred. '+ s[1]);
        }
      }
      else
      {
        alert('Exception occurred. '+ args);
      }
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

// ConceptTabbedViewDocument_CallbackTrigger
function ConceptTabbedViewDocument_CallbackTrigger_Wrapped(action, _multiPageClientID, _tabStripClientID, _cbreference, _srmIndex) 
{
  //debugger;
  try
  {
    // render document
    if(action=='DocumentSelected')
    {
      var args = 'Action=RepopulateTab|TabID=Document|SrmIndex=' + _srmIndex;
      eval(_cbreference);
      // show document tab
      var tabStrip = _tabStripClientID;
      if(tabStrip != null)
      {
        var docTab = tabStrip.FindTabById('Document');
        if(docTab != null)
        {
          docTab.Visible = 1; docTab.SaveState();
          
          // select tab
          tabStrip.SelectTabById(global_ConceptTabbedControl_CurrentlySelectedTab);
        }// end doctab is not null
      } // end tabstrip is not null
    } // end action

    // document tab close
    if(action=='DocumentClosed')
    {
      selectedPageID = _multiPageClientID;
      var args = 'Action=RepopulateTab|TabID=Document';
      eval(_cbreference);
      // hide document tab 
      var tabStrip = _tabStripClientID;
      if(tabStrip != null)
      {
        var docTab = tabStrip.FindTabById('Document');
        if(docTab != null)
        {
          docTab.Visible = 0; docTab.SaveState();
          
          // select library tab instead if the current selected tab is the Document tab
          if(docTab.IsSelected())
          {
            tabStrip.SelectTabById('Library');
            SetSessionProperty('ConceptTabbedView_SelectedTab', 'Library');
          }
          else
          {
            // remain in the current selected tab
            var currentTab = tabStrip.SelectedTabPostBackID;
            tabStrip.SelectTabByPostBackId(currentTab);
          } // end if else docTab selected
        } // end docTab is not null
      } // end tabStrip is not null
    } // end action DocumentClosed
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
} //end function

function ConceptTabbedView1_SelectResultTab_Wrapper(_tabStripClientID, _titleLabelClientID, _tabContextSeparator, _itemName)
{
  //debugger;
  try
  {
    SetSessionProperty('KGShowResultsTab', 'true');
    //SetSessionProperty('ConceptTabbedView_SelectedTab', 'Results');
      
    var tabStrip = _tabStripClientID;
    var resultsTab = tabStrip.FindTabById('Results');
    //resultsTab.Visible = 1;
    //resultsTab.SaveState();
    tabStrip.SelectTabById('Results');
    //ConceptTabbedView_TabSelected(null, null, resultsTab);
    
    // store in session
    SetSessionProperty('SearchResult_SearchRootPhraseName', _itemName); 
    //global_ConceptTabbedControl_CurrentlySelectedTab = 'Results';

    ConceptTabbedView1_SwitchTabs(resultsTab.ID, _itemName);
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function ConceptTabbedView1_SelectPersonalTab_Wrapper(_tabStripClientID, _titleLabelClientID)
{
  //debugger;
  try
  {
    SetSessionProperty('KGShowPersonalTab', 'true');      
    var tabStrip = _tabStripClientID;
    var personalTab = tabStrip.FindTabById('Personal');
    tabStrip.SelectTabById('Personal');    
    ConceptTabbedView1_SwitchTabs(personalTab.ID, null);
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

// DisplaySearchResult Callback scripts
function ConceptTabbedView1_CallbackTrigger_Wrapped(_itemID, _itemType, _itemName, _rootPhraseName, _titleLabelClientID, _tabContextSeparator, _MapViewDisplayModeKGMapView, _cbreference, _srmIndex, _tabStripClientID, _tabbedViewClientID)
{
  //debugger;
  try
  {
    //Show loading icon (bug 2856)
    var holder = document.getElementById(_tabbedViewClientID.id + "_ResultsPage");
    if(holder != null)
    {
      holder.innerHTML = '<table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
    }

    SetSessionProperty('PageSession_LibrarySelectedItemID', _itemID);
    SetSessionProperty('PageSession_LibrarySelectedItemTypeID', _itemType);
    SetSessionProperty('PageSession_LibrarySelectedITemName', _itemName);
    
    var tabStrip = _tabStripClientID;
    var resultsTab = tabStrip.FindTabById('Results');
    tabStrip.SelectTabById('Results');
    
    var currentLocation = window.location.href;
    var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
    
    // Update Mapview and TabbedWindow controls
    if (window.MapViewControl1_CallbackTrigger_IfVisible)
    {
      SetSessionProperty('MapViewDisplayMode', _MapViewDisplayModeKGMapView);
      MapViewControl1_CallbackTrigger_IfVisible(_srmIndex);
    }
    
    //if (window.KGTabbedWindowsControl_CallbackTrigger)
    //  KGTabbedWindowsControl_CallbackTrigger('ConceptSelected', _srmIndex);
    
    var args = 'Action=DisplaySearchResult|ItemID='+_itemID+'|'+'ItemType='+_itemType+'|'+'ItemName='+_itemName+'|SrmIndex='+_srmIndex;
    eval(_cbreference);
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function ConceptTabbedView1_CallbackDone_Wrapped(args, context, _tabStripClientID)
{
  //debugger;
  try
  {
    // Check for a session time out before completing the callback
    if (CheckSessionTimeout())
      return;
    
    var s = args.split('='); 
    var ids = s[0].split('@');
    
    var holder = document.getElementById(ids[0]);
    if(holder != null)
    {
      holder.innerHTML = args.substring(args.indexOf('=')+1);
      // need to redeclare the storage and the main function before calling it
      // therefore get the text of it
      // storage first
      var pos1 = args.indexOf('![CDATA[');
      if ( pos1 > - 1)
      {
        var string2 = args.substring(pos1, args.length);
        var pos2 = string2.indexOf('[[');
        var pos3 = string2.indexOf('//]]>');
        if ( pos2 > -1 && pos3 > -1 )
        {
          var storageString = string2.substring(pos2, pos3);
          var evalStorageString = 'window.ComponentArt_Storage_' + ids[1] + '_ResultTree = ' + storageString;
          // eval the string
          eval(evalStorageString);
          // now the init string
          var pos4 = string2.lastIndexOf('![CDATA[');
          if ( pos4 > -1 )
          {
            var string3 = string2.substring(pos4, string2.length);
            var pos5 = string3.indexOf('{');
            var pos6 = string3.lastIndexOf('}');
            if ( pos5 > -1 && pos6 > -1 )
            {
              var initString = string3.substring(pos5, pos6 + 1);
              var evalInitString = 'window.ComponentArt_Init_' + ids[1] + '_ResultTree = function()' + initString;
              // eval the string
              eval(evalInitString);
              // now execute it now that we've redefined it
              eval('ComponentArt_Init_' + ids[1] + '_ResultTree()');
            } // end if pos5 and pos6
          } // end if pos4
        } // end if pos2 and pos3
      } // end if pos1
      // Selecting the Result Page after callback returns
      var tabStrip = _tabStripClientID;
      tabStrip.SelectTabById('Results');
      
      // Highlisht Selected TreeNode
      if(ids[2] != null && ids[3] != null)
      {
        var nodeId = ids[2];
        var treeId = ids[3];
        var aTreeNode = null;
        var aTreeView = null;
        
        if(treeId != null && treeId !='' && treeId != '-1' && eval('window.'+ treeId+'!=null'))
          aTreeNode = eval(treeId + '.FindNodeById(\'' + nodeId + '\')');
          
        if(aTreeNode != null) 
        {
          aTreeView = aTreeNode.ParentTreeView;
          
          if(aTreeView!= null && aTreeView.TreeViewID != null && aTreeView.TreeViewID != '')
            conceptTreeControl_preTreeViewID = aTreeView.TreeViewID;
          
          if(aTreeNode.ID != null && aTreeNode.ID != '')
            conceptTreeControl_preTreeNodeID = aTreeNode.ID;
          
          aTreeView.SelectedNode = aTreeNode;
        } 
        
        // lowlight previous selected path
        //if(conceptTreeControl_preTreeViewID != null && conceptTreeControl_preTreeNodeID != null)
          //ConceptTreeControl_LowlightTreeNode(conceptTreeControl_preTreeViewID, conceptTreeControl_preTreeNodeID);
        
        // Highlight Selected Path
        //if(aTreeView != null)
          //ConceptTreeControl_HighlightTreeNode(treeId, nodeId); 
      } 
    }
    else
    {
      ConceptTabbedView_ProcessCallBackError('Content Cell not found.', '');
    }
    
    var searchResultsTreeLastRootNodeHiddenFieldClientID = SearchResult_GetLastRootNodeHiddenFieldID();
    var searchResultLastRootNodeHiddenField = document.getElementById(searchResultsTreeLastRootNodeHiddenFieldClientID);
    searchResultLastRootNodeHiddenField.value = null;
    
    var tabStrip = _tabStripClientID;
    var tab = tabStrip.GetSelectedTab();
    ConceptTabbedView_ChangeBackButtonMode(ShowBackButton(tab));
    m_treeViewIsLoaded = true;
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
  try
  {
    var srmIndex = ids[4];
    SrmControl_RecordTimes(srmIndex);
  }
  catch(e){}
};

// Check box javascripts
function ConceptTabbedView_SubscriptionModeChanged_Wrapped(_cb, _cbreference)
{
  //debugger;
  try
  {
		var optiondiv = document.getElementById('KGOptionControlID1');
    var loginview = "Library_LoginView_";
    try
    {
      loginview = "Library_LoginView_";
      var check = document.getElementById(loginview + "KGOptionControl_ImageNumber0").src = "Images/newGeneOption.png";
    }
    catch(Exception)
    {
      loginview = "";
    }
    
    if(_cb == false)
    {
      SetSessionProperty('ConceptTabbedView_AllowSubscripton', true);
      var args = 'Action=SubscriptionModeChanged|Value=' + true;
      eval(_cbreference);
      document.getElementById(loginview + "KGOptionControl_ImageNumber4").src = "Images/LeftSubsOn.png";        
      document.getElementById(loginview + "KGOptionControl_CellNumber4").onclick = function(){ConceptTabbedView_SubscriptionModeChanged(true)};     
      document.getElementById(loginview + "KGOptionControl_CellNumber4").onmouseover = function(){this.style.cursor='pointer'};
    }
    else
    {
      SetSessionProperty('ConceptTabbedView_AllowSubscripton', false);
      var args = 'Action=SubscriptionModeChanged|Value=' + false;
      eval(_cbreference);
      document.getElementById(loginview + "KGOptionControl_ImageNumber4").src = "Images/LeftSubsOff.png";        
      document.getElementById(loginview + "KGOptionControl_CellNumber4").onclick = function(){ConceptTabbedView_SubscriptionModeChanged(false)};     
      document.getElementById(loginview + "KGOptionControl_CellNumber4").onmouseover = function(){this.style.cursor='pointer'};
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
} //end function

function ConceptTabbedView_AlertSettingModeChanged_Wrapped(_cb, _cbreference, _srmIndex) 
{
  //debugger;
  try
  {
    if (m_srmGetTimes!= null && m_srmGetTimes == "True" && _srmIndex != null)
      m_srmAction[_srmIndex] += ',' + !_cb;
  }
  catch(e){}

  try
  {
    var optiondiv = document.getElementById('KGOptionControlID1');
    var loginview = "Library_LoginView_";
    
    try
    {
      loginview = "Library_LoginView_";
      var check = document.getElementById(loginview + "KGOptionControl_ImageNumber0").src = "Images/newGeneOption.png";
    }
    catch(Exception)
    {
      loginview = "";
    }

    if(_cb == false)
    {
      SetSessionProperty('ConceptTabbedView_AllowChangeAlertSetting', true);
      var args = 'Action=AlertSettingModeChanged|Value=' + true + '|SrmIndex=' + _srmIndex;
      eval(_cbreference);
      document.getElementById(loginview + "KGOptionControl_ImageNumber3").src = "Images/LeftAlertsOfn.png";        
      document.getElementById(loginview + "KGOptionControl_CellNumber3").onclick = function(){ConceptTabbedView_AlertSettingModeChanged(true)};     
      document.getElementById(loginview + "KGOptionControl_CellNumber3").onmouseover = function(){this.style.cursor='pointer'};
    }
    else
    {
      SetSessionProperty('ConceptTabbedView_AllowChangeAlertSetting', false);
      var args = 'Action=AlertSettingModeChanged|Value=' + false + '|SrmIndex=' + _srmIndex;
      eval(_cbreference);
      document.getElementById(loginview + "KGOptionControl_ImageNumber3").src = "Images/LeftAlertsOff.png";        
      document.getElementById(loginview + "KGOptionControl_CellNumber3").onclick = function(){ConceptTabbedView_AlertSettingModeChanged(false)};     
      document.getElementById(loginview + "KGOptionControl_CellNumber3").onmouseover = function(){this.style.cursor='pointer'};
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
} //end function

function ConceptTabbedView1_RefocusTreeView_wrapped(_itemID,
                                                    _itemName,
                                                    _tabStripClientID,
                                                    _titleLabelClientID,
                                                    _tabContextSeparator,
                                                    _MapViewDisplayModeKGMapView,
                                                    _cbreference,
                                                    _isBackButtonPress,
                                                    _srmIndex)
{
  //debugger;
  try
  {
    if (window.CancelEdit)
      CancelEdit(true);
    
    var tabStrip = eval(_tabStripClientID);
    var currentTabID = (tabStrip.GetSelectedTab()).ID;
    if (currentTabID != null)
    {
      if(currentTabID == 'Library')
        SetSessionProperty('GlobalLibrary_NewRootConceptID', _itemID);
      else if(currentTabID == 'Personal')
        SetSessionProperty('PersonalLibrary_NewRootConceptID', _itemID);
      else if(currentTabID == 'Results')
        SetSessionProperty('SearchResult_NewRootConceptID', _itemID);
      else if(currentTabID.substr(0,3) == 'CS_')
        SetSessionProperty('Topic_NewRootConceptID', _itemID);             
      
      var currentLocation = window.location.href;
      var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
      var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
      
      // refocus tree
      if (_isBackButtonPress == true)
        var args = 'Action=Refocus|CurrentTabID='+currentTabID+'|BackButtonPress=true';
      else
        var args = 'Action=Refocus|NewRootConceptID='+_itemID+'|CurrentTabID='+currentTabID+'|SrmIndex='+_srmIndex;
      eval(_cbreference);
      
      try
      {
        if (m_srmGetTimes!= null && m_srmGetTimes == "True" && _srmIndex != null)
        {
          m_srmAction[_srmIndex] += ',' + currentPage + ',' + currentTabID;
          m_srmCallbacks[_srmIndex] = 2;
        }
      }
      catch(e){}
      
      if(!(_isBackButtonPress == true && (_itemID == 0 || _itemID == -1)))
      {
        if (window.MapViewControl1_CallbackTrigger_IfVisible)
        {
          SetSessionProperty('MapViewDisplayMode', _MapViewDisplayModeKGMapView);
          MapViewControl1_CallbackTrigger_IfVisible(_srmIndex);
        }
       // if (window.KGTabbedWindowsControl_CallbackTrigger)
        //  KGTabbedWindowsControl_CallbackTrigger('ConceptSelected', _srmIndex);
      }
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function ConceptTabbedView_ControlReload(args, context)
{
  //debugger;
  try
  {
    if(args.indexOf('SelectedTabId') > 0)
    {
      var params = args.split('|');
      var tabStrip = eval(params[0].substring(params[0].indexOf('=') + 1, params[0].length));
      var selectedTabID = params[1].substring(params[1].indexOf('=') + 1, params[1].length);
      
      if((selectedTabID != null) && (tabStrip != null))
      {
        var selectedTab = tabStrip.FindTabById(selectedTabID);
        if(selectedTab != null)
        {
          tabStrip.SelectTabById(selectedTabID);
          ConceptTabbedView_TabSelected(null, null, selectedTab);
        }
      }
    }
    else
    {
      var s = args.split('=');
	    var ids = s[1].split(' ');
	    var holder = document.getElementById(ids[0].replace(/"/g,''));
    	
	    if(holder != null)
	    {
		    holder.parentNode.innerHTML = args;
		    var jscripts = args.split('<script');
		    var targets = new Array();
		    var x;
    		
		    for(x in jscripts)
		    {
			    if(jscripts[x].indexOf('//<![CDATA[') > 0)
			    {
				    targets.push(jscripts[x].substring(jscripts[x].indexOf('//<![CDATA['), jscripts[x].indexOf('//]]>') + 5));
			    }
		    }
    		
		    for(x in targets)
		    {
			    var posWindow = targets[x].indexOf('window');
			    var posFunction = targets[x].indexOf('function');
			    var evalString;
    			
			    if((posWindow < posFunction) || (posFunction == -1))
			    {
				    evalString = targets[x].substring(targets[x].indexOf('window'), targets[x].indexOf('//]]>'));
			    }
			    else if((posWindow > posFunction) && (posFunction != -1))
		      {
            evalStrng = targets[x].substring(targets[x].indexOf('function'), targets[x].indexOf('//]]>'));
		      }
    			
			    eval(evalString);
		    }
	    }
	    else
	    {
	      ConceptTabbedView_ProcessCallBackError('Content Cell not found.', '');
	    }
	  }
	}
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

// show (true) or hide (false) the back button, depending on _boolShow (can get _boolShow from ShowBackButton below)
function ConceptTabbedView_ChangeBackButtonMode_Wrapped(_boolShow, _backButtonCellClientID)
{
  //debugger;
  try
  {
    var backButtonCell = document.getElementById(_backButtonCellClientID);
    if (backButtonCell != null)
    {
      if (_boolShow)
        backButtonCell.className = "TabBackButton";
      else
        backButtonCell.className = "TabBackButtonHidden";
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function ConceptTabbedView_onBackButtonClickHandler_Wrapped(_tabStrip)
{
  //debugger;
  try
  {
    var tab = _tabStrip.GetSelectedTab();
    if (tab.ID.substr(0,3) == 'CS_')
    {
      var lastRootNodeHiddenFieldID = Topic_GetLastRootNodeHiddenFieldID();
      var lastRootNodeHiddenField = document.getElementById(lastRootNodeHiddenFieldID);
      if (lastRootNodeHiddenField!=null && lastRootNodeHiddenField.value != null && lastRootNodeHiddenField.value != 'null' && lastRootNodeHiddenField.value.length > 0)
        ConceptTabbedView1_RefocusTreeView(lastRootNodeHiddenField.value, null, null, true);
      else
        KGTopicsControl_upToTopLevel(tab.ID, _tabStrip);
    }
    else if (tab.ID == 'Results')
    {
      var lastRootNodeHiddenFieldID = SearchResult_GetLastRootNodeHiddenFieldID();
      var lastRootNodeHiddenField = document.getElementById(lastRootNodeHiddenFieldID);
      
      SearchResult_ResetTreeScrollingVariables();
      
      // refocus tree view _backbuttonpress = true
      if (lastRootNodeHiddenField.value != null && lastRootNodeHiddenField.value != 'null' && lastRootNodeHiddenField.value.length > 0)
      {
        if(global_SearchResult_ClickedItemID == lastRootNodeHiddenField.value)
          SetSessionProperty('HideSearchResultItemInfo', 'false'); // reach the original display tree
        ConceptTabbedView1_RefocusTreeView(lastRootNodeHiddenField.value, null, null, true);
      }
    }
    else if (tab.ID == 'Personal')
    {
      var lastRootNodeHiddenFieldID = PersonalLibrary_GetLastRootNodeHiddenFieldID();
      var lastRootNodeHiddenField = document.getElementById(lastRootNodeHiddenFieldID);
      
      // refocus tree view _backbuttonpress = true
      if (lastRootNodeHiddenField.value != null && lastRootNodeHiddenField.value != 'null' && lastRootNodeHiddenField.value.length > 0)
        ConceptTabbedView1_RefocusTreeView(lastRootNodeHiddenField.value, null, null, true);
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

// return true if the back button should be shown, false otherwise
function ShowBackButton(_tab)
{
  //debugger;
  try
  {
    if (_tab != null)
    {
      if (_tab.ID.substr(0,3) == 'CS_')
      {
        if (KGTopicsControl_isTopicSelected())
          return true;
      }
      else if (_tab.ID == 'Results')
      {
        var lastRootNodeHiddenFieldClientID = SearchResult_GetLastRootNodeHiddenFieldID();
        var lastRootNodeHiddenField = document.getElementById(lastRootNodeHiddenFieldClientID);
        
        if(lastRootNodeHiddenField.value == null || 
          lastRootNodeHiddenField.value == "null" ||
          lastRootNodeHiddenField.value == "")
          return false;
        else
          return true;
      }
      else if (_tab.ID == 'Personal')
      {
        var lastRootNodeHiddenFieldClientID = PersonalLibrary_GetLastRootNodeHiddenFieldID();
        var lastRootNodeHiddenField = document.getElementById(lastRootNodeHiddenFieldClientID);
        
        if (lastRootNodeHiddenField.value == null || 
            lastRootNodeHiddenField.value == "null" ||
            lastRootNodeHiddenField.value == "")
          return false;
        else
          return true;
      }
    }
    return false;
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

// JScript File
function KGSignInControl_CallbackTrigger_Wrapped(actionToken, cbreference)
{
  var args = "action=" + actionToken;
  
  if(cbreference != null)
  {
    eval(cbreference); 
  }
}

function KGSignInControl_CallbackDone(args, context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  alert('A copy of the activation email has been sent to you. Thank you.');
  ToggleLoginControl(0);
  
  WM_killCookie('LoginStatus');
}

function KGSignInControl_CallbackError(args, context)
{

}

function KGSignInControl_Position(e)
{
  //make sure it isn't off the page
  var x = e.x || e.pageX;
  var y = e.y || e.pageY;
  
  xPos = x<450?0:x-450;
 
  yPos = y + 10;
  var maxY = document.body.clientHeight - 180;
  if (maxY > 0 && yPos > maxY)
      yPos = maxY;
      
  UpdateKGSignInControlPos('absolute',xPos,yPos);
}
function KGListViewControl_CallbackError(_args, _context)
{
  var alertMessage = "The ListView encountered an error. \n\n" + _args;
  alert(alertMessage);
}

function KGListViewControl_CallbackDone(_args, _context)
{
  // check for exceptions
  if (_args.indexOf("Exception") == 0 || _args.length == 0)
  {
    KGListViewControl_CallbackError(_args, _context);
    return;
    // looking for indexOf == 0 instead of > -1 incase it's genuine html that happens to contain 'Exception' in there
    // e.g. a user called "... Exceptional ..." 
  }

  // get the parameters
  var argsSplit = _args.split('[@|@]');
  var json = argsSplit[0];
  var javascripts = argsSplit[1];
  var htmlContent = argsSplit[2];
  
  var retMsg = eval( '(' + json + ')' );
  var holderId = retMsg.HolderId;
  
  var holder = document.getElementById(holderId);
  if (!holder)
  {
    KGListViewControl_CallbackError('The holder doesn\'t exist ' + holderId);
    return;
  }
  
  // fill the control
  SetOuterHtml(holder, htmlContent);
  
   // eval any javascripts
  if (javascripts)
    eval(javascripts);
  
  // fire the callbackCompleteMethod, if required
  var callbackCompleteMethod = retMsg.CallbackCompleteMethod;
  if (callbackCompleteMethod)
    eval(callbackCompleteMethod);
}

function KGListViewControl_Pager_Wrapped(_type, _pagContId, _callbackTrigger)
{
  // clicked on any pager button
  // _type for which button
  
  // get the parameters
  var pagCont = document.getElementById(_pagContId); //container
  var curPage = parseInt(pagCont.getAttribute("CurPage")); //current page index - starts at one
  var lastPage = parseInt(pagCont.getAttribute("LastPage")); //last page index - starts at one
  
  // find out which page to get
  // or return early if it was an invalid button, e.g. First when you're already on the first page
  switch (_type)
  {
    case "First":
      if (curPage == 1)
        return;
      else
        curPage = 1;
      break;
    case "Prev":
      if (curPage == 1)
        return;
      else
        curPage--;  
      break;
    case "Next":
      if (curPage == lastPage)
        return;
      else
        curPage++;
      break;
    case "Last":
      if (curPage == lastPage)
        return;
      else
        curPage = lastPage;
      break;      
  }
  
  // callback to get the new page of data
  var args = "Base=True|Action=Page|PageIdx=" + curPage;
  eval(_callbackTrigger + "('" + args + "')");
  
  // note we don't adjust the CurPage attribute here
  // it will get set in callback done
  // if the user tries to page again before the callback finishes
  // it'll just repeat 
  // the current page index matches what the user can see
  // just incase something goes wrong in the callback
}

function KGListViewControl_GetPageInfo_Wrapped(_type, _pagContId)
{
  // if you only want the current page, call it with _type = "CurPage"
  // if you want all the info, don't use _type, leave it null
  // if you only want something else, could extend the _type = "CurPage" - I haven't done it because it didn't seem useful
  
  var pagCont = document.getElementById(_pagContId); //container
  
  if (!pagCont)
  {
    // e.g. if no KGs in MyKGs it has a message instead of the grid and pager
    if (_type == "CurPage")
      return 1;
    else
      return new PageInfo(1, 1, 0, 1);
  }
  
  // read useful paging variables from the paging container
  var curPage = parseInt(pagCont.getAttribute("CurPage")); //current page index - starts at one
  if (_type == "CurPage")
    return curPage;
    
  var lastPage = parseInt(pagCont.getAttribute("LastPage")); //last page index - starts at one
  var totalRecords = parseInt(pagCont.getAttribute("TotalRecords")); //total number of records
  var pageSize = parseInt(pagCont.getAttribute("PageSize")); //page size
  
  return new PageInfo(curPage, lastPage, totalRecords, pageSize);
}

function PageInfo(curPage, lastPage, totalRecords, pageSize)
{
  this.CurPage = curPage;
  this.LastPage = lastPage;
  this.TotalRecords = totalRecords;
  this.PageSize = pageSize;
  
  this.IsShowingSingleItem = function()
  {
    // i.e. the only item on the last page
    // good to know incase you're removing the item, then the page will need to change
    // probably also want to check CurPage == 1 to see if it's the very last item (this method will return true)
    var result = false;
    
    // is it the last page? Is easiest to test so test it first
    if (this.CurPage == this.LastPage)
    {
      // calculate number of items on the last page
      var numOnLastPage = this.TotalRecords - this.PageSize * (this.LastPage - 1);
      if (numOnLastPage == 1)
        result = true;
    }
    
    return result;
  } 
}
// PrivateSpaceCreatedControl.js

function KGPrivateSpaceCreatedControl_CreatePrivateSpace()
{
  //debugger;
  try
  {
    try
    {
      if (m_srmGetTimes!= null && m_srmGetTimes == "True")
      {
        var now = new Date();
        SetSessionProperty('Srm_T0', now.getTime());
        SetSessionProperty('Srm_Action', 'CreatePrivateSpace');
        SetSessionProperty('Srm_Callbacks', 1);
      }
    }
    catch(e){}
   
    window.location = "CommunitySpace.aspx";
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function KGPrivateSpaceAdminControl_OpenPrivateSpace(_groupID)
{
  //debugger;
  try
  {
    var keys = 'KGCurrentGroupID|Topics_SelectedTopicGroupId';
	  var values = _groupID + '|' + _groupID;
    SetSessionProperty(keys, values, true);

    //SetSessionProperty('KGCurrentGroupID', _groupID);
    //SetSessionProperty('Topics_SelectedTopicGroupId', _groupID);
    try
    {
      if (m_srmGetTimes!= null && m_srmGetTimes == "True")
      {
        var now = new Date();
        SetSessionProperty('Srm_T0', now.getTime());
        SetSessionProperty('Srm_Action', 'ConfigurePrivateSpace');
        SetSessionProperty('Srm_Callbacks', 1);
      }
    }
    catch(e){}
  
    //window.location = "PrivateSpaceAdmin.aspx"; 
    window.location = "ConfigureCommunitySpace.aspx";
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function CreateCommunitySpace()
{
  //debugger;
  try
  {  
    window.location = "CommunitySpace.aspx"; 
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}
// TabbedWindowsControl JScript File

var global_TabbedWindowsControl_CurrentlySelectedTab = null;

// variables used to determine if page has already been loaded
var globalKGListPageLoaded = false;
var globalIndexedDocsPageLoaded = false;
var globalTextViewPageLoaded = false;
var globalDocumentPageLoaded = false;
var globalCommunityPageLoaded = false;
var globalCategoryHomePageLoaded = false;
var RelatedConcept = "";
var currentlySelectedKG = "";
var savedConcept;
var currentDocListKnowdeID;
var currentDocListMode = "None";

// 
// this will rerender audit history table after call back
function KGTabbedWindowsControl_CallbackDone_Wrapped(args, context, _tabStripClientID)
{

}

// The Callback trigger will populate the selected tab if it has not yet been loaded.
// If it has been loaded, it will do nothing.
function KGTabbedWindowsControl_CallbackTrigger_Wrapped(action,
                                                        _cbreference, 
                                                        _tabStripClientID,
                                                        _thisClientID,
                                                        _parsingDocControlSessionNameForDocument,
                                                        _clientSideOnDocumentTabClosed,
                                                        _kgMemberControlSessionNameForCommunity,
                                                        _clientSideOnCommunityTabClosed,
                                                        _SelectedTabOnPageLoad,
                                                        _srmIndex,
                                                        _doButtonToolbarCallback)
{

}

// This function evals the cbreference for the selected tab (_tabID)
function KGTabbedWindowsControl_RepopulateTab(_tabID,
                                              _thisClientID,
                                              action,
                                              _cbreference,
                                              _srmIndex)
{

}

function CallbackAfterTimeout(_args, _cbreference)
{
  var args = _args;
  eval(_cbreference);
}

function KGTabbedWindowsControl_TabSelected_Wrapped(_eventArgs,
                                                    _thisClientID,
                                                    _srmIndex)
{

}

// prevent double gene click until one has loaded
var globalGeneClick = 'true';

// _groupID: the GroupID for the KG
function KGTabbedWindowsControl_MyHK_KGSelected(_KnowdeKey, _ownerKey, _kgid, _openText, _groupID)
{
	if(globalGeneClick == 'true')
	{
		globalGeneClick = 'false';
		// these two session variables are used in the TabbedWindowsControl callback then removed in ProcessAJAXCallback
		// so if the callback is not triggered they shouldn't be set
		if(_openText != true &&	global_TabbedWindowsControl_CurrentlySelectedTab != 'Indexed Documents')
		{
			// The map view callback is triggered this side of the TabbedWindowsControl callback 
			// so cancel the callback trigger in the TabbedWindowsControl_callback done
			SetSessionProperty('IndexedDoc_MyHK_KGID', _kgid);
		}
		
		KGTabbedWindowsControl_KGSelected(_KnowdeKey, _ownerKey, _kgid, _openText, true, _groupID);
		globalGeneClick = 'true';
	}  
}

// KGTabbedWindowsControl_KGSelected handler
// _KnowdeKey: the string KnowdeKey
// _groupID: the GroupID for the KG
function KGTabbedWindowsControl_KGSelected(_KnowdeKey, _ownerKey, _kgid, _openText, _MyHK, _groupID)
{
  if (window.CloseApplicationControl && m_applicationControlOpen && !m_appForceOpen)
  {
    CloseApplicationControl();
  }
	// if the current map has been clicked and a different KG map will be loaded, 
	// then the old map need to become background map
	var sdiv1 = document.getElementById('scrolling-section');
	var sdiv2 = document.getElementById('scrolling-section-disable');
	// if not first time loading the map
	if(sdiv1 != null && sdiv2 != null && Active_KGID != '')
	{
		if(LastKnowdeClickedKGID == Active_KGID)
		{
			Background_KGID = Active_KGID;
			Background_SelectedKnowde = Active_GlobalLastSelectedKnowde;
			SetSessionProperty('Background_SelectedKG', Background_KGID + '|' + returnKnowdeID(Background_SelectedKnowde));
			SetSessionProperty('BackUpKGContext', Active_KGID);
			if(Active_KGID != ('' + _kgid + ''))
			{
				Background_howChainArray = howChainArray;
				Background_whyChainArray = whyChainArray;
				Background_ShadowKnowdeList = Active_ShadowKnowdeList;
				Background_CenterShadowKnowdeList = Background_ShadowKnowdeList;
				Background_SelectedKnowdePosX = parseInt(Background_SelectedKnowde.parentNode.style.left);
				Background_SelectedKnowdePosY = parseInt(Background_SelectedKnowde.parentNode.style.top) + Background_SelectedKnowde.offsetTop;
				Background_KnowdeWidth = knowdeWidth;
        
				//if(Background_ShadowKnowdeList.indexOf(','+returnKnowdeID(Background_SelectedKnowde)+'|') > -1)
				//{
					// there is shadow showed in it, adjust the offset top
					//Background_SelectedKnowdePosY -= KnowdeShadow_OffsetTopPX;
				//}
				// set background map
				Background_DivInnerHTML = sdiv1.innerHTML;
				var contents = Background_DivInnerHTML;//.replace("KnowdeShadow' style='visibility:visible;","KnowdeShadow' style='visibility:hidden;");
				//contents = contents.replace("KnowdeShadow style='visibility:visible;","KnowdeShadow style='visibility:hidden;");
				sdiv2.innerHTML = contents;
			}
		}
    
		if(Background_KGID == ('' + _kgid + ''))
		{
			// same mapview, don't show the background one, 
			ClearBackgroundMapView();
		}
		else
		{
				// don't show background map at the moment  
				HighlightConcept = false; //HighlightConcept = true;
		}
	} 
	// in the SessionPropertiesAshxHandler, if the knowdeKey is same with Background_SelectedKnowdeID, then won't override the context
	if (_KnowdeKey != null)
	{
		if(sdiv1 != null && sdiv2 != null && Active_KGID != '')
			SetSessionProperty('KGList_SelectedKGID', _KnowdeKey);
		else
			SetSessionProperty('SelectedKGID', _KnowdeKey);
	}

  var keys = 'RemoveSelectedConcept|MapViewDisplayMode'
  var values = '0|KGMapView';
  if (_groupID != null)
  {
    keys += '|Topics_SelectedTopicGroupId';
    values += '|' + _groupID;
  }
  SetSessionProperty(keys, values, true);
  
	// let the map view reload when it is viewed
	globalMapViewControlLoaded = false;
  
	if(_openText == true)
	{
	//debugger;
		ClearTextViewValues();
		// Load the text view page
		globalTextViewPageLoaded = false;
		if (_MyHK)
			ShowSelectedKnowdeHalo(globalLastSelectedKnowde, globalLastMapDirection);
		//KGTabbedWindowsControl_SelectTabById('TextView');

	}
	else
	{ // kg click
    
		// turn off edit mode
		if(m_bEditable == true)
		{
			SwitchEditableFlag();
		}
      
		// don't show background map at the moment  
		ShowBackgroundMapView = 0; //ShowBackgroundMapView = 1;
		SetSessionProperty('KGMapViewCollapsed',false);
         
		var mapViewCollapsed = PaneBStatus();
		if (mapViewCollapsed == null || mapViewCollapsed == false) // map view is visible, reload it
		{
			MapViewControl1_CallbackTrigger();
		}
		else // map view is not visible - open the splitter
		{
			//globalMapViewControlLoaded = false;
			DoExpandMapViewPane("fully");
		}
		if(globalSplitterSetting == "split")
			ShowSplitterArrowDown();
	}// else show text view click, don't reload the map
  
	currentlySelectedKG = _kgid;
	globalLastTickerAction = "";
}

function KGTabbedWindowsControl_SelectTabById_Wrapped(_tabId, _thisClientID, _tabStripClientID, _doButtonToolbarCallback)
{
  /*if(_thisClientID != "undefined")
  {
    var tabStrip = eval(_tabStripClientID);
    if(tabStrip != null)
    {
      var selectedTab = tabStrip.selectTabById(_tabId);
      SetSessionProperty(_thisClientID + '_SelectedTab', _tabId);
      global_TabbedWindowsControl_CurrentlySelectedTab = _tabId;
      KGTabbedWindowsControl_CallbackTrigger('TabSelected, ' + _tabId, null, _doButtonToolbarCallback);
    }
  }*/
}

function ShowTextView(_knowdeKey, _ownerKey, _kgId, _openText, _HK)
{
   //debugger;
  // if ! editing
  if(m_bEditable == true)
    if(_HK == true)
      KGTabbedWindowsControl_MyHK_KGSelected(_knowdeKey, _ownerKey, _kgId, _openText);
    else
      KGTabbedWindowsControl_KGSelected(_knowdeKey, _ownerKey, _kgId, _openText); 
  else
  {
		if(globalSplitterSetting == "split")
			ShowSplitterArrowDown();
    globalHelpTopicKey = 'needTextView';
    
    if(document.getElementById("DockedHelpWindow") != null)
      DisplayTextViewInTab('TextView', '', 'false', _kgId);
    else
      DisplayTextViewInTab('TextView', '', 'true', _kgId);
    
    var MapHelpBox = document.getElementById("KGHelpControlID1");
    MapHelpBox.title = "Associated Text";
    
    //KGHelpControl_CallbackTrigger(globalHelpTopicKey, globalHelpTopicParams);
  }
}

function ShowWebDocument(_url)
{
  // close the preview document window 
  var helpBox = document.getElementById("KGHelpControlID1");
  if(helpBox != null && helpBox.className == "OverlayPosition")
    CloseHelpControl();

  //SwitchTextTabControlMode(false);
	//UpdateTour(5);
  ClearHelpFrame();
  m_HelpFrame = document.getElementById("HelpFrame");
  globalShowingWebDoc = true;
  m_HelpFrame.src = _url;
  // hide textview view mode option div
  //HideOrShowTextViewOptionDiv(false);
  // make sure docked control is closed
  CloseDockedKGHelpControl();
  OpenHelpControl(true);
  
  var MapHelpBox = document.getElementById("KGHelpControlID1");
  if (MapHelpBox.title != "Web Document")
  {//Only resize if not already viewing a web document
    MapHelpBox.style.top = screen.height/4;//"30%"; //screen.height/3;
    MapHelpBox.style.height = screen.height/2;
    try
    {
			if(document.body.clientWidth < 1025)
			{
				MapHelpBox.style.left = "5%";
				MapHelpBox.style.width = "80%";
			}
			else
			{
				MapHelpBox.style.left = "5%";
				MapHelpBox.style.width = "1024px";
			}
    }catch(e){MapHelpBox.style.left = "5%"; MapHelpBox.style.width = "40%";}
  }
  MapHelpBox.title = "Web Document";
}

function ResetScrollBar()
{
  //this resets the indexed docs scroll bar position back to the top when using the paging
  document.getElementById("Splitter1_pane_1").firstChild.scrollTop = 0;
}

// KnowledgeGeneListControl JScript File

var globalknowledgeGenesGridClientID;


function KGKnowledgeGeneListControl_ProcessCallBackError_Wrapped(args, context, _thisClientID)
{
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    document.getElementById(_thisClientID).innerHTML = 'An error has occurred.';
  }
}

var m_selectedProfileID;
// Event handler for Author icon/name click event
function KGKnowledgeGeneListControl_Author_OnClientSideSelect(_selectedAuthorID, e, _isBackButtonClick)
{
  // Start the callback onto KGTabbedWindows to show CommunityTab
  SetSessionProperty('SelectedAuthorID', _selectedAuthorID);
  m_selectedProfileID = _selectedAuthorID;
  //KGTabbedWindowsControl_CallbackTrigger('AuthorSelected');
  if (!_isBackButtonClick)// if this action is not from a back button click, trigger the KGButtonToolbar callback
    KGButtonToolbar_AuthorSelected(_selectedAuthorID);
  CancelBubble(e);
  
  /*if(WM_readCookie('UserID') == _selectedAuthorID)
    document.getElementById('CategoriesTreeCheckbox').parentNode.style.display = 'block';//KGNavigationControl_ShowHideSemanticTreeCheckBox(1); 
  else
    document.getElementById('CategoriesTreeCheckbox').parentNode.style.display = 'none';//KGNavigationControl_ShowHideSemanticTreeCheckBox(0);*/
}

function KGKnowledgeGeneListControl_Grid_OnInit(_knowledgeGenesGridClientID)
{
 globalknowledgeGenesGridClientID = _knowledgeGenesGridClientID;
}

// KGListGrid OnClientSideSelect event handler
function KGKnowledgeGeneListControl_Grid_OnClientSideSelect(_item)
{
  SetSessionProperty('SelectedKGID', _item.GetMember('KnowdeKey').Text);
  var keys = 'RemoveSelectedConcept|MapViewDisplayMode';
	var values = '0|true';
  SetSessionProperty(keys, values, true);

  //SetSessionProperty('RemoveSelectedConcept', 0);
  //SetSessionProperty('MapViewDisplayMode', 'KGMapView'); // this is set in the ASHX to MapViewDisplayMode.KGMapView.ToString()
      
  // Trigger MapView callback now if map view is visible
  MapViewControl1_CallbackTrigger_IfVisible();
        				
  // reset the page loaded variables
  // We will want to reload these pages if the tabs get selected
  globalIndexedDocsPageLoaded = false;
  globalTextViewPageLoaded = false;

  return true;
}

//Event Handle check box OnCheckeChanged 
function KGKnowledgeGeneListControl_OnCheckChanged(item, columnIndex, checkbox)
{ 
//debugger;
   if(item != null && columnIndex != null && checkbox != null)
   {
     var conceptId = -1;
     var kgId = -1;
     var conceptKey = item.GetMember("ConceptKey");
     var kgIdKey = item.GetMember("KnowledgeGeneKey");
     
     if(conceptKey != null)
       conceptId = conceptKey.Value;
     if(kgIdKey != null)  
       kgId = kgIdKey.Value;
     
     // Call back to subscribe kg and concept;
     //HandleTreeNodeCheckedChangedByKGList(checkbox,conceptId,kgId);
     SubscribeKGByKGListControl(checkbox, kgId);
     
   }  
     
   return true;
}// end function

function ChangeSubscriptionOfKGByKGListControl_Wrapped(aSubscribedButton,  kgId, _cbreference, _subscribe, _conceptId, _knowdeId)
{
  //debugger;
  if(aSubscribedButton != null)
  {
    var args = 'action=subscription|Concept=' + _conceptId + '|Checked=' + _subscribe + '|NodeID=' + _knowdeId + '|KGID=' + kgId + '|KGSubscrpition=1|SubscriptionButton=' + aSubscribedButton;
    
    eval(_cbreference);
    
    //aSubscribedButton.src = aSubscribedButton.src;
  }

  return true;
}// end function


function ConceptTreeControl_ChangeSubscriptionImage(_subscribeButton, _subscribe)
{
//debugger;

  if(_subscribe == "True")
  {
    _subscribeButton.src = "Images/Buttons/Add.png";
    _subscribe = false;
  }
  else
  {
    _subscribeButton.src = "Images/Buttons/Remove.png";
    _subscribe = true;
  }
  
  return _subscribeButton;
}


function KnowledgeGeneListControl_CallbackDone_Wrapped(args, context, contentDiv)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  var srmIndex;
  try
  {
    srmIndex = SrmControl_SetInitial('KnowledgeGeneListControl_CallbackDone_Wrapped');
  }
  catch(e){}
  
 // start the debugging session 
  //debugger;
  
  // extract all the cdatas lines from callback result
  var cdatas = args.split('<![CDATA[');
  
  // extract the predefined control client IDs
  var s = args.split('=');
  var ids = s[0].split('@');
  
  // search for the control container
  //var holder = document.getElementById(contentDiv);
  
  // Test if the container is found
  // Yes: replace the innerHTML with the callback result
  //  No: call CallbackError with Content div not found error message
  if(contentDiv != null)
  {
    // holder.innerHTML = args.substring(args.indexOf('=') + 1);
    contentDiv.innerHTML = args;
    
    // loop through the cdatas and process each of them
    // ignoring the first one coz it is just HTML
    var z = 0;
    for(z = 1; z < cdatas.length; z++)
    {
      // javascript starting position
      var posStart = cdatas[z].indexOf('window');
      
      // javascript ending position 
      var posEnd = cdatas[z].lastIndexOf('}') + 1;
      
      if(posStart > -1 && posEnd > -1)
      {
        // attemp to extract the javascript
        var jscript = cdatas[z].substring(posStart, posEnd);
       
        // Now we have the potential jscript we need to execute it to 
        // reinitiallise the grid
        if(jscript.length != 0)
        {        
          // redefine the init script on Page
          eval(jscript);
          var posNameStart = jscript.indexOf('window');
          var posNameEnd = jscript.indexOf('=');
          
          var functionName = jscript.substring(posNameStart, posNameEnd);
          // execute the script
          eval(functionName+'()');
        }// end if(jscript.....
      }// end if(posStart ......         
    }// end for
  }//end if(holder ....
  else
  {
    KGUserObjectSummaryControl_CallBackError('ContentDiv not found in KGUserObjectSummaryControl.', '');
  }
  SrmControl_RecordTimes(srmIndex);
}
// KGPublishOptionControl JScript File
var g_eventX;
var g_eventY;
var g_originalKgId;
var g_locationId;
var g_publishHolderId = 'Contents_LoginView_KGMemberControl_UserObjectSummary_KGPublishOptionControl_KGPublishOptionControl';
// For firefox
var g_splitter1DivScrollTop = -1;
var g_splitter1DivScrollLeft = -1;

// to store component art menu group divs
var g_KGPublishCatMenuGroupDivs = new Array();

function KGPublishOptionControl_CallbackTrigger_Wrapped(_action, 
                                                        _originalKgId, 
                                                        _publishedKgId, 
                                                        _locationId,
                                                        _knowdeShortcut,
                                                        _textVersion,
                                                        _lockData,
                                                        _newName,
                                                        e,
                                                        _sessionNameForPublishKG,
                                                        _callbackScript,
                                                        _isOnCommunityTab)
{
  // debugger;
  var args;


  // Construct the callback arguments
  if(_action.length > 0)
    args = 'action=' + _action;
  
  if(_originalKgId > 0)
    args += '|originalKgId=' + _originalKgId;

  if(_publishedKgId != null && _publishedKgId.length > 0)
    args += '|publishedKgId=' + _publishedKgId;

  if(_locationId != null && (_locationId > 0 || _locationId == -1))
    args += '|locationId=' + _locationId;
    
  if(_knowdeShortcut != null && _knowdeShortcut > 0)
    args += '|knowdeShortcut=' + _knowdeShortcut;
    
  if(_textVersion != null && _textVersion > 0)
    args += '|textVersion=' + _textVersion;
    
  if(_lockData != null && _lockData > 0)
    args += '|lockData=' + true;
    
  if(_newName != null && _newName != '')
    args += '|newName=' + _newName;
    
  // Test if we are dealing with Remove or Publish action
  // YES: use the coords saved from gen-menu (1st callback), 
  //      coz we don't want to move the menu to the new event location
  //  NO: we are dealing with gen-menu action, so used the event location
  //      also we need to save the coords for subsequent actions (2nd callback)
  if(_action.indexOf('gen_menu') == 0)
  {
    if(e != null)
    {
      g_originalKgId = _originalKgId;
      g_locationId = _locationId;
      if(_isOnCommunityTab.toLowerCase() == "true")
      {
        g_eventX = e.clientX;
        g_eventY = e.clientY;
      }
      else
      {
        g_eventX = e.x || e.pageX;
        g_eventY = e.y || e.pageY;
      }
    }
  }
  
  args += '|eventX=' + g_eventX;
  args += '|eventY=' + g_eventY;
  
  
  if(args.length > 0)
  {      
    SetSessionProperty(_sessionNameForPublishKG, _originalKgId);
    CancelBubble(e);
    eval(_callbackScript);
  }
  
}

function KGPublishOptionControl_ReSetPublishingChoicesControl()
{
  // make sure the existing menus are hidden
  for (var mid in g_KGPublishCatMenuGroupDivs)
  {
    var menuGroupTable = document.getElementById(g_KGPublishCatMenuGroupDivs[mid]);
    if(menuGroupTable != null && menuGroupTable.parentNode != null)
    {
      var parentDiv = menuGroupTable.parentNode;
      parentDiv.parentNode.removeChild(parentDiv);
    }
  }
  g_KGPublishCatMenuGroupDivs = new Array();
  HideKGPublishingChoicesControl();
}
				  
function KGPublishOptionControl_CallbackDone_Wrapped(_args, _context, _isOnCommunityTab)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  window.setTimeout('KGPublishOptionControl_ReSetPublishingChoicesControl()', 500);
  
  // for firefox
  // set the current scroll position
  var tabScroller = GetTabScroller();
  if(tabScroller)
  {
    g_splitter1DivScrollTop = tabScroller.scrollTop;
    g_splitter1DivScrollLeft = tabScroller.scrollLeft;
  }


  var tokens = _args.split('|');
  if(tokens.length == 6)
  {
    var holder = document.getElementById(tokens[0]);
    g_publishHolderId = tokens[0];
    var action = tokens[1];
    var eventX = tokens[2];
    var eventY = tokens[3];
    var kgvalid = tokens[4];
    var content = tokens[5];
    
    if(holder != null)
    {
      holder.innerHTML = content;
      // eval javascripts
      var cdatas = _args.split('<![CDATA[');
      var z = 0;
      for(z = 1; z < cdatas.length; z++)
      {
	      var posStart = cdatas[z].indexOf('window');      
	      var posEnd = cdatas[z].lastIndexOf('}') + 1;
	      if(posStart > -1 && posEnd > -1)
	      {
	  	    if (posEnd < posStart)
	  	    {
	          posEnd = cdatas[z].lastIndexOf(']') + 1;
	          var jscript = cdatas[z].substring(posStart, posEnd);
		        if(jscript.length != 0)
		        {
		          eval(jscript);
		        }
	        }
	        else
	        {
		        var jscript = cdatas[z].substring(posStart, posEnd);
		        if(jscript.length != 0)
		        {
			        eval(jscript);
			        var posNameStart = jscript.indexOf('window');
			        var posNameEnd = jscript.indexOf('=');
			        if(posNameStart > -1 && posNameEnd > -1)
			        {
			          var functionName = jscript.substring(posNameStart, posNameEnd);
			          eval(functionName+'()');
			        }
		        }
		      }
	      }
      }
      // for firefox
      var tabScroller = GetTabScroller();
      if(tabScroller)
      {
        if(tabScroller.scrollTop != g_splitter1DivScrollTop)
          tabScroller.scrollTop = g_splitter1DivScrollTop;
        
        if(tabScroller.scrollLeft != g_splitter1DivScrollLeft)
          tabScroller.scrollLeft = g_splitter1DivScrollLeft;
      }


      // Use callback to update the KGUserObjectSummaryControl after remove and publish
      if(action == 'remove' || action == 'publish' || action == 'republish' ||action == 'republishall' || action == 'unpublishall')
      {
        window.setTimeout("RepopulateProfilePageKGLists()",100);
        
        if(action != 'gen_menu')
        {
          // kg might have been removed
          if(kgvalid.toLowerCase() == 'false')
            window.setTimeout("ClearActiveKG()",200);
        }
      }
      //else
      //{
        // Need this to make sure the control is displayed on the screen
        KGPublishOptionControl_ShowMenu(tokens[0]);  
      //}
              
      // Need to test for which page we are on to decided what co-ordinates to use:
      // MapTabbedView.aspx has an extra spliter pane which will mess up the normal event.x and event.y
      // so we have to use event.clientX and clientY to correctly position the popup relative to the 
      // extra spliter pane.
      // Options.aspx does not have the extra spliter pane so it can use the normal event.x and event.y
      // however, if we apply clientX and clientY the positioning is wrong for that page.
      // Hence, we need to detect where we are and apply the correct co-ordinates [PL05Mar2008]
      if(_isOnCommunityTab.toLowerCase() == "true")
      {
        if(action == 'publish'|| action =='remove' || action == 'republish' ||action == 'republishall' || action == 'unpublishall')
          window.setTimeout("KGPublishOptionControl_ShowAndReposition('absolute', " + parseInt(g_eventX) + 2 + "," + (parseInt(g_eventY) - 5) + ",'" + tokens[0] + "')", 1000);
        else
          UpdateKGPublishOptionControlPos('absolute', parseInt(eventX) + 2, parseInt(eventY) - 5);
      }
      else 
      { 
        if(action == 'publish'|| action =='remove' || action == 'republish' ||action == 'republishall' || action == 'unpublishall')
          window.setTimeout("KGPublishOptionControl_ShowAndReposition('absolute', " + parseInt(g_eventX) + "," + (parseInt(g_eventY) + 5) + ",'" + tokens[0] + "')", 1000);
        else
          UpdateKGPublishOptionControlPos('absolute', parseInt(eventX), parseInt(eventY) + 5);
      }

    }
    else
      KGPublishOptionControl_CallbackError('Content Div element is missing.');
  }
}

function KGPublishOptionControl_ShowAndReposition(_positionType, _eventX, _eventY, _holderID)
{
  //debugger;
  KGPublishOptionControl_HideMenu(_holderID);
  //KGPublishOptionControl_CallbackTrigger('gen_menu', g_originalKgId, -1, g_locationId, null);
  //UpdateKGPublishOptionControlPos(_positionType, _eventX, _eventY);
}

function KGPublishOptionControl_ShowMessage_Wrapped(_resultDivId, _message)
{
  var resultDiv = document.getElementById(_resultDivId);
  if(resultDiv != null)
  {
    resultDiv.innerHTML = "<img src='Images/LoadingBar.gif' widht='12px' height='12px'>&nbsp;&nbsp;" + _message;
  }
}

  			
function KGPublishOptionControl_CallbackError(_args, _context)
{
  alert(_args);
}

function KGPublishOptionControl_PublishClick(_object, _action, 
                                                        _originalKgId, 
                                                        _publishedKgId, 
                                                        _locationId,
                                                        e)
{
  // show loading icon
  if(_object != null && _object.tagName.toLowerCase() == 'span')
  {
    _object.className = 'InProgressImage';
    _object.title = 'Please wait while we publishing...'
    _object.innerHTML = "<img src='Images/LoadingBar.gif' widht='12px' height='12px'>";
  }
  
  KGPublishOptionControl_ShowMessage('publishing...');

  // trigger callback
  KGPublishOptionControl_CallbackTrigger(_action, _originalKgId, _publishedKgId, _locationId, 0, 0, 0, null, e);
}

function KGPublishOptionControl_PublishClickWithOptions(_object, _action, 
                                                        _originalKgId, 
                                                        _publishedKgId, 
                                                        _locationId,
                                                        _knowdeShortcut,
                                                        _textVersion,
                                                        _lockData,
                                                        _newName,
                                                        e)
{
  // show loading icon
  if(_object != null && _object.tagName.toLowerCase() == 'div')
  {
    //_object.className = 'InProgressImage';
    _object.title = 'Please wait while we publishing...'
    _object.innerHTML = "<img src='Images/LoadingBar.gif' widht='12px' height='12px'>&nbsp;Publishing...&nbsp;&nbsp;";
  }
  
  // trigger callback
  KGPublishOptionControl_CallbackTrigger(_action, _originalKgId, _publishedKgId, _locationId, _knowdeShortcut, _textVersion, _lockData, _newName, e);
}

function KGPublishOptionControl_UnPublishClick(_object, _action, 
                                                        _originalKgId, 
                                                        _publishedKgId, 
                                                        _locationId,
                                                        e)
{
    if (_action == 'remove' || _action == 'unpublishall')
    {
        EnsureDeletePubKGMessage(_action, _originalKgId, _publishedKgId, _locationId, e);
        PositionUosMessageBox("SiteOverlays_LoginView1_KGPublishOptionControl1_KGPublishOptionTable", false, e);
    }
    else
    {
      var msg = 'unpublishing...';
      if(_action == 'republish')
        msg = 'republishing...';
      KGPublishOptionControl_ShowMessage(msg);

      // trigger callback
      KGPublishOptionControl_CallbackTrigger(_action, _originalKgId, _publishedKgId, _locationId, 0, 0, 0, null, e);
    }   
}

function KGPublishOptionControl_UnPublishClick_Confirm(_action, 
                                                        _originalKgId, 
                                                        _publishedKgId, 
                                                        _locationId,
                                                        e)
{
  m_UosMessageBox.innerHTML= '<div style=\"position:absolute;width:400px;height:120px;border:gray solid 1pt;background:white\"><table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" />Unpublishing....</td></tr></table></div>';

  // trigger callback
  KGPublishOptionControl_CallbackTrigger(_action, _originalKgId, _publishedKgId, _locationId, 0, 0, 0, null, e);
}



///////////////////////
// Ensures that the delete message box is on the page
function EnsureDeletePubKGMessage(_action, _originalKgId, _publishedKgId, _locationId, e)
{

  m_UosMessageBox = document.getElementById("DeleteKGMessageBox");

  if(m_UosMessageBox == null)
  {
    m_UosMessageBox = document.createElement("div");
    m_UosMessageBox.setAttribute("id", "DeleteKGMessageBox");
    m_UosMessageBox.style.display = "none";
    m_UosMessageBox.style.width = "400px"
    m_UosMessageBox.style.height = "160px";
    m_UosMessageBox.style.position = "absolute";
    m_UosMessageBox.style.zIndex = 1000;
    //m_UosMessageBox.style.zIndex = TopZIndex(); // this function does not work in FF, so have hard coded a z-index for a quick fix
    
    if (_action == 'unpublishall')
      m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Are you sure you want to unpublish this Knowledge Gene<sup>&#174;</sup> from ALL groups?</td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>It will be removed from ALL groups it has previously been published to and any links added by other users (e.g. in the 'Community' tab) will also be removed.</td></tr><tr><td align='right'><button type='button' onclick='KGPublishOptionControl_UnPublishClick_Confirm(\"" + _action + "\"," + _originalKgId + ",\"" + _publishedKgId + "\"," + _locationId + ")'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";
    else
      m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Are you sure you want to unpublish this Knowledge Gene<sup>&#174;</sup>?</td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>It will be removed from the group and any links added by other users (e.g. in the 'Community' tab) will also be removed.</td></tr><tr><td align='right'><button type='button' onclick='KGPublishOptionControl_UnPublishClick_Confirm(\"" + _action + "\"," + _originalKgId + ",\"" + _publishedKgId + "\"," + _locationId + ")'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";
    
    //var parentControlDiv = document.getElementById(_parentControlDivId);
    //InsertAdjacentElement(document.body,"afterBegin", m_UosMessageBox);
    document.body.appendChild(m_UosMessageBox);
  }
  else
  {
    if (_action == 'unpublishall')
        m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Are you sure you want to unpublish this Knowledge Gene<sup>&#174;</sup> from ALL groups?</td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>It will be removed from ALL groups it has previously been published to and any links added by other users (e.g. in the 'Community' tab) will also be removed.</td></tr><tr><td align='right'><button type='button' onclick='KGPublishOptionControl_UnPublishClick_Confirm(\"" + _action + "\"," + _originalKgId + ",\"" + _publishedKgId + "\"," + _locationId + ")'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";
    else
        m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Are you sure you want to unpublish this Knowledge Gene<sup>&#174;</sup>?</td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>It will be removed from the group and any links added by other users (e.g. in the 'Community' tab) will also be removed.</td></tr><tr><td align='right'><button type='button' onclick='KGPublishOptionControl_UnPublishClick_Confirm(\"" + _action + "\"," + _originalKgId + ",\"" + _publishedKgId + "\"," + _locationId + ")'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";

    m_UosMessageBox.style.zIndex = TopZIndex(); //Show on top of other items
  }
}

function KGPublishOptionControl_RePublishAllClick(_object, _action, 
                                                        _originalKgId,
                                                        e)
{
  // show loading icon
  if(_object != null && _object.tagName.toLowerCase() == 'span')
  {
    _object.className = 'InProgressImage';
    _object.title = 'Please wait while we re-publishing...'
    _object.innerHTML = "<img src='Images/LoadingBar.gif' widht='12px' height='12px'>";
  }
  
  KGPublishOptionControl_ShowMessage('republishing...');
  
  // trigger callback
  KGPublishOptionControl_CallbackTrigger(_action, _originalKgId, null, null, 0, null, e);
}

function KGPublishOptionControl_UnPublishAllClick(_object, _action, 
                                                        _originalKgId,
                                                        e)
{
  if (_action == 'remove' || _action == 'unpublishall')
  {
        EnsureDeletePubKGMessage(_action, _originalKgId, null, null, e);
        PositionUosMessageBox("SiteOverlays_LoginView1_KGPublishOptionControl1_KGPublishOptionTable", false, e);
  }
  else
  {
  
    KGPublishOptionControl_ShowMessage('unpublishing...');
    
    // trigger callback
    KGPublishOptionControl_CallbackTrigger(_action, _originalKgId, null, null, 0, null, e);
  }
}

function KGPublishOptionControl_MenuItemMouseOver(_sender, _eventArgs)
{
	HideBubble();
  var menuItem = _eventArgs.get_item();
  var menuGroupID = KGPublishOptionControl_GetMenuItemElementID(menuItem);
  // store into the array
  g_KGPublishCatMenuGroupDivs.push(menuGroupID);
  if (menuItem.getItems().length > 0)//if the item has children to show
  {
    KGPublishOptionControl_ShowMenuGroup(menuGroupID, null, menuItem.ParentIndex);
  }
}


function KGPublishOptionControl_MenuItemMouseOut(_sender, _eventArgs)
{
}

// finds the DOM element id for a component art menuItem object
function KGPublishOptionControl_GetMenuItemElementID(_menuItem)
{
  var indexArray = new Array();
  indexArray.push(_menuItem.get_index());
  
  while(_menuItem.ParentItem != null)
  {
    _menuItem = _menuItem.ParentItem;
    indexArray.push(_menuItem.get_index());
  }
  
  var groupId = _menuItem.ParentMenu.MenuId;
	var menuGroup = document.getElementById(groupId);
  var menuitems = menuGroup.getElementsByTagName("td");
  
  var menuItemElement = menuitems[indexArray[indexArray.length-1]];// get the menuItemElement at the index position given by the last array item
  groupId = "G" + menuItemElement.id;// get the id for the menuGroup that belongs to this menuItem
  indexArray.pop();// remove the last array item    

  while (indexArray.length > 0)
  {
  	var menuGroup = document.getElementById(groupId);// get the menuGroup
    var menuitems = menuGroup.getElementsByTagName("nobr");// only one of these tags per menuitem (there are additional tds if a menu item has children)

    var menuItemElement = menuitems[indexArray[indexArray.length-1]];// get the menuItemElement at the index position given by the last array item
    
    // the dom nesting is different for items with children an those without.
    // first check the parentNode for the item id, then check higher up.
    menuItemId = menuItemElement.parentNode.id || menuItemElement.parentNode.parentNode.parentNode.parentNode.id
    groupId = "G" + menuItemId;// get the id for the menuGroup that belongs to this menuItem
    indexArray.pop();// remove the last array item    
  }

  return groupId;
}

function KGPublishOptionControl_ShowMenuGroup(_menuGroupID, _iteration, _parentIndex)
{
  if (_iteration == null)
    _iteration = 0;
  else
    _iteration++;
  
  // get the menu group container
  var menuGroup = document.getElementById(_menuGroupID);
  if (menuGroup == null && _iteration <= 10)
  {
    // wait until it gets shown
    setTimeout("KGPublishOptionControl_ShowMenuGroup('" + _menuGroupID + "', " + _iteration + ", " + _parentIndex + ")", 100);
  }
  else if (_iteration > 10)
  {
    // this prevents the timeout from looping indefinitely if something goes wrong
    return;
  }
  else
  {
    // ensure the container is the correct size
    if(navigator.appName == "Opera") 
    {
      // this will causing templates sometimes become more than one lines (left icon, text in the middle and right icon)
      // but this is required for Opera, so have to assign a fix width which is wide enough for the moment.
      menuGroup.parentNode.style.height = menuGroup.clientHeight + 2 + 'px';
      //alert(menuGroup.clientWidth);
      menuGroup.parentNode.style.width = (menuGroup.clientWidth + 40) + 'px';
    }
    var divScrollTop = Splitter1.scrollTop;
    var divScrollLeft = Splitter1.scrollLeft;
    var parentDiv = menuGroup.parentNode;
    
    if (_parentIndex == -1) // if it's top level sub group 
    {
      if(parentDiv != null && parentDiv.tagName && parentDiv.tagName.toLowerCase() == 'div' 
           && parentDiv.style.top && parentDiv.style.top != '' && parentDiv.style.left && parentDiv.style.left != '')
      {
        // if the menu group just get created, or already exists but position been reset
        if(!menuGroup.getAttribute("moved"))
        {
          var currentScrollTop = parseInt(parentDiv.style.top.replace('px',''));
          var currentScrollLeft = parseInt(parentDiv.style.left.replace('px',''));
          
          if(divScrollTop > 0 || navigator.appName == 'Netscape')
          {
            // reposition the div
            currentScrollTop = currentScrollTop - divScrollTop;
            if (navigator.appName == 'Netscape')
              currentScrollTop += 100;
            if(currentScrollTop < 0)
              currentScrollTop = 0;
            parentDiv.style.top = currentScrollTop + 'px';
          }
          
          if(divScrollLeft > 0)
          {
            // reposition the div
            currentScrollLeft = currentScrollLeft - divScrollLeft;
            if(currentScrollLeft < 0)
              currentScrollLeft = 0;
            parentDiv.style.left = currentScrollLeft + 'px';
          }
          menuGroup.setAttribute("moved", true);
        }
        else // check whether need to update position if the container div has been scroll
        {
          var oldScrollTop = parentDiv.getAttribute("containerScrollTop");
          var oldScrollLeft = parentDiv.getAttribute("containerScrollLeft");
          
          var currentScrollTop = parseInt(parentDiv.style.top.replace('px',''));
          var currentScrollLeft = parseInt(parentDiv.style.left.replace('px',''));
          
          // if the outer splitter pane scrollable div scroll position has been changed
          if(oldScrollTop != null && oldScrollLeft != null)
          {
            if(oldScrollTop != divScrollTop)
            {
              // verticle scroll position changed
              var vdiff = divScrollTop - oldScrollTop;
              currentScrollTop = currentScrollTop - vdiff;
              if (navigator.appName == 'Netscape')
                currentScrollTop += 100;
              if(currentScrollTop < 0)
                currentScrollTop = 0;
              parentDiv.style.top = currentScrollTop + 'px';
            }
            if(oldScrollLeft!= divScrollLeft)
            {
              // verticle scroll position changed
              var hdiff = divScrollLeft - oldScrollLeft;
              currentScrollLeft = currentScrollLeft - hdiff;
              if(currentScrollLeft < 0)
                currentScrollLeft = 0;
              parentDiv.style.left = currentScrollLeft + 'px';
            }
          }
        }
        
        // store the current scrollable position
        parentDiv.setAttribute("containerScrollTop", divScrollTop)
        parentDiv.setAttribute("containerScrollLeft", divScrollLeft)
        
        
      } // end if parentDiv != null
    }
  }
}



// Resource File containing the hints for the map view help text. 
MapHintShow = "Show Hyperknowldge Assistance";
MapHintNavigate = "Use the arrow keys to move about the map in the four Knowledge Genes<sup>&#174;</sup> directions.<br><img src='Images/MapViewIcons/Compass.png'/>";
MapHintAddVerb = "Add a verb phrase to the Knowde in order to describe the action to perform.<br><img src='Images/MapViewIcons/EditVerbNoun.png'/>";
MapHintAddNoun = "Add a noun phrase to the Knowde in order to describe the item to act upon.<br><img src='Images/MapViewIcons/EditVerbNoun.png'/>";
MapHintAddWhat = "Add a WHAT item.<br><img src='Images/MapViewIcons/EditVerbNoun.png'/>";
MapHintAddWhatIs = "Add a WHAT-IS item.<br><img src='Images/MapViewIcons/EditVerbNoun.png'/>";
MapHintInsert = "Press the 'insert' key to create a new Knowde between two existing Knowde boxes.<br><img src='Images/MapViewIcons/HInsert.png'/>";
MapHintVerticalInsert = "Press the 'insert' key to create a new Knowde between two existing Knowde boxes.<br><img src='Images/MapViewIcons/VInsert.png'/>";
MapHintNoWhys = "There are no further Why items.<br><img src='Images/MapViewIcons/NoWhys.png'/>";
MapHintNoHows = "There are no further How items.<br><img src='Images/MapViewIcons/NoHows.png'/>";
MapHintNoWhat = "There are no further What items.<br><img src='Images/MapViewIcons/NoWhats.png'/>";
MapHintNoWhatIs = "There are no further What-is items.<br><img src='Images/MapViewIcons/NoWhatIs.png'/>";
MapHintNoDrop = "A Knowde cannot be made a HOW or a WHY of itself.<br><img src='Images/Alert.png'/>";
MapHintNoDropRepeat = "A Knowde cannot be dropped here as it would cause repetition.<br><img src='Images/Alert.png'/>";
MapHintDrop = "Drop here to paste Knowde.";
MapHintDrag = "To drop a dragged item onto a Knowde or connector, move the cursor over it.<br><br>  To show the HOWS of a HOW, or to add a new HOW to it, hover over it";

// KGOverlayControl

var KGOverlayControl_marginLeft = 10; // the margin from right border
var KGOverlayControl_marginTop = 10; // the margin from bottom border

//function KGOverlayControl_UpdateOverlayDivPosStyle_Wrapped(m_KGOverlayControlDivId, style)
//{
//  if (style != null && style !='')
//  {
//   var holder = document.getElementById( m_KGOverlayControlDivId );
//   if(holder != null)
//   {
//     holder.style.property=style;
//   }
//  }
//}

//function KGOverlayControl_UpdateOverlayDivPos_Wrapped(_controlId, _posType, _posLeft, _posTop)
//{
//  var div=document.getElementById( _controlId );
//  if (div != null)
//  {
// 
//    var style='';
//    if(_posType != null && _posType !='')
//      div.style.position=_posType;
//    if(_posLeft != null && _posLeft !='')
//       div.style.left=_posLeft;
//    if(_posTop != null && _posTop !='')
//       div.style.top=_posTop;
//  }
//}

//function KGOverlayControl_UpdateOverlayTitle_Wrapped( m_Title_DivId, title)
//{
//   var div=document.getElementById( m_Title_DivId );
//   if (div != null && title != null)
//     SetInnerText(div,title);
//}

/// Wrapper of DisplayControlScript
function KGOverlayControl_DisplayControlScript_Wrapped(_controlId, _cssclass, _helpTopicKeyword, _helpTopicParams) 
{  
//debugger;
   var div = null; 
   
   if(_controlId != null && _controlId != '')
      div =document.getElementById(_controlId);
      
   if(div != null && _cssclass != null)
   {
			div.className = _cssclass;
			
			if(_controlId == "KGHelpControlID1")
			{
			  var currentKG = document.getElementById(currentlySelectedKG)
			  
			  if (currentKG != null)	
			    switch(currentKG.innerHTML)
			    {
			      case "Now showing the Knowledge Gene<sup>&#174;</sup> and document":
			        if(document.getElementById("DockedHelpWindow") != null)
			          currentKG.innerHTML = "Now showing the Knowledge Gene<sup>&#174;</sup> and document";	
			        else
			          currentKG.innerHTML = "Now showing the Knowledge Gene<sup>&#174;</sup>, click here to view the document";		  
			        break;
			      case "Now showing the Knowledge Gene<sup>&#174;</sup>, click here to view the document":  
	                currentKG.innerHTML = "Now showing the Knowledge Gene<sup>&#174;</sup> and document";
	   	            break;
			    }
			}
			
			// drop list z-index bugs for IE6
			if(_controlId.match("KGHelpControl") == "KGHelpControl")
			{				
				// find x & y coords of all drop lists - hide list if there is an overlay.
				if(navigator.appVersion.match("MSIE 7.0") != "MSIE 7.0")
				{
					// retrieve and hide all droplists.
					var droplist = document.getElementsByTagName("SELECT");
					for(var num=0;num<droplist.length;num++)
					{
						//only hide the visible boxes
						if(droplist[num].className == "list_dropList")
						{
							if(_cssclass == "OverlayPositionHidden")
							{
								droplist[num].style.display = "inline";
							}
						}
					}
				}
			}
			// Store the Help Topic Keywords and params if passed in 
			if(_helpTopicKeyword!=null)
			{ 
			}
	     
			// If the element is resizable, we need to remember the position
			if (div.className.indexOf("drsElement") > -1)
				SetSessionProperty(div.id + 'Position',div.style.cssText);  
			
			//debugger;	
			if(globalHideDockButton == true || m_bEditable == true) //globalSplitterSetting == "single" || 
			{
				// hide dock in window option
				if(document.getElementById("SiteOverlays_KGHelpControl1_DockInPageButton") != null)
				  document.getElementById("SiteOverlays_KGHelpControl1_DockInPageButton").style.display = "none";
				//globalHideDockButton = false;
			}
			else
			{
				// show dock in window option
				if(document.getElementById("SiteOverlays_KGHelpControl1_DockInPageButton") != null)
				  document.getElementById("SiteOverlays_KGHelpControl1_DockInPageButton").style.display = "";
			}  
   }
}


/// Wrapper of UpdateControlTitleScript
function KGOverlayControl_UpdateControlTitleScript_Wrapped(_controlId, _title)
{  
   var div = null; 
   
   if(_controlId != null && _controlId != '')
      div =document.getElementById(_controlId);
      
   if (div != null && _title != null)
     SetInnerText(div,_title);
}

/// Wrapper of CloseButtonOnClickScript
function KGOverlayCotrol_CloseButtonOnClickScript_Wrapped(_controlId, _hidenCssclass)
{
   var div = null; 
   
   if(_controlId != null && _controlId != '')
      div = document.getElementById(_controlId);
 
   if (div != null && _hidenCssclass != null)
     div.className= _hidenCssclass;
}


/// Wrapper of UpdateControlPositionScript to return script string for changing position of Control
function KGOverlayControl_UpdateOverlayDivPos_Wrapped( _controlId, _posType, _posLeft, _posTop)
{
	// hide the droplists for earlier IE versions
	if(navigator.appVersion.match("MSIE 7.0") != "MSIE 7.0" && navigator.appName == "Microsoft Internet Explorer")
	{
		if(_controlId.match("SignIn") == "SignIn" || _controlId.match("Suggestion") == "Suggestion")
		{
			HideDropLists();
		}
	}
	
	if(_controlId.match("Suggestion") == "Suggestion")
	{
		HideBubble(false);
	}

  var div = null;
  if(_controlId != null )
    div = document.getElementById( _controlId );
  
  if (div != null)
  {
    var posLeftNum = 0;
    var posTopNum = 0;
    var position = -1;
    
    try
    {
      // extract number part in postLeft, and set to posLeftNum
      if(_posLeft != null && _posLeft !='')
      {
        _posLeft +=""; // convert to string
        _posLeft = _posLeft.toLowerCase();
        position = _posLeft.indexOf('px');
        if(position >= 0)
          posLeftNum = parseInt(_posLeft.substring(0, position));
        else 
          posLeftNum = parseInt(_posLeft);
      }
      
      if(_posTop != null && _posTop !='')
      {
        _posTop +="";
        _posTop = _posTop.toLowerCase();
        position = _posTop.indexOf('px');
        if(position >= 0)
          posTopNum = parseInt(_posTop.substring(0, position));
        else 
          posTopNum = parseInt(_posTop);
      }
    }
    catch(e)
    {
      posLeftNum = 0;
      posTopNum = 0;
    }
    
    try 
    {
      /* [PL01May2008]
         Section removed to fix bug 3452, this block causes the bug in that it limits
         the y coordinates without considering the page can be taller than the screen 
              
      if(posLeftNum > 0 && posTopNum > 0)
      {
        // Get the proper Left and Top position by checking current window's border
        _posLeft = KGOverlayControl_GetLeft(div, _posType, posLeftNum)+"px";
        _posTop = KGOverlayControl_GetTop(div, _posType, posTopNum)+"px";
      }
      */
      
      if(_posType != null && _posType !='')
        div.style.position=_posType;
      if(_posLeft != null && _posLeft !='')
        div.style.left=_posLeft;
      if(_posTop != null && _posTop !='')
        div.style.top=_posTop;
     }
     catch(e)
     {
       // do nothing;
     }

  }
}

/// Get width of current window
function KGOverlayControl_GetWindowWidth() {
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement && document.documentElement.clientWidth ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && document.body.clientWidth ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  return myWidth;
}

/// Get height of current window
function KGOverlayControl_GetWindowHeight() {
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement && document.documentElement.clientHeight ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && document.body.clientHeight ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
  return myHeight;
}

/// Get width of the div that embeds the whole control
function KGOverlayControl_GetControlDivWidth(_div)
{
  var divWidth = 0;
  if(_div != null && _div.clientWidth != null)
    divWidth = _div.clientWidth;
  
  return divWidth; 
}

/// Get height of the div that embeds the whole control
function KGOverlayControl_GetControlDivHeight(_div)
{
  var divHeight = 0;
  if(_div != null && _div.clientHeight != null)
    divHeight = _div.clientHeight;
  
  return divHeight;
}

/// Get Explorer's Type
function KGOverlayControl_GetExplorerType()
{
  var isIE = document.all ? 1 : 0
  var isNS = document.layers ? 1 : 0
  
  if(isIE == 1)  
    return "ie";
  else if(isNS == 1)
    return "ns";
  else 
    return "other";
}

/// Get x(left) postion of event
function KGOverlayControl_GetEventX()
{
  window.captureEvents(Event.CLICK);

  var explorerType = KGOverlayControl_GetExplorerType();
  var eventX = 0;
  if(explorerType == 'ie' && event != null && event.x != null)
    eventX = event.x;
  else if(explorerType == 'ns' && e != null && e.pageX != null)
    eventX = e.pageX;
 
  return eventX;
}

/// Get y(top) postion of event
function KGOverlayControl_GetEventY()
{
  window.captureEvents(Event.CLICK);

  var explorerType = KGOverlayControl_GetExplorerType();
  var eventY = 0;
  if(explorerType == 'ie' && event != null && event.y != null)
    eventY = event.y;
  else if(explorerType == 'ns' && e != null && e.pageY != null)
    eventY = e.pageY;
      
  return eventY;
}

// Get the left position by checking current window's border 
// If part of current control is out of border, get the proper left position 
function KGOverlayControl_GetLeft(_div, _posType, _posLeft)
{
  var _windowWidth = KGOverlayControl_GetWindowWidth();
  var _controlWidth = KGOverlayControl_GetControlDivWidth(_div);
  
  if(_div != null && _windowWidth > 0 && _controlWidth > 0 && _posLeft > 0)
  {
    var fromBorderRight = _windowWidth - _controlWidth - KGOverlayControl_marginLeft;
    if(fromBorderRight < 0)
      fromBorderRight = 0;
    
    if(_posType != null && _posType.toLowerCase() == 'absolute')
    {
      if(_posLeft > fromBorderRight)
        _posLeft = fromBorderRight;
      
    }
    else if (_posType != null && _posType.toLowerCase() == 'relative')
    {
      var eventX = KGOverlayControl_GetEventX();
      if(eventX != null && eventX > 0)
      {
        if(_posLeft > fromBorderRight - eventX )
          _posLeft = fromBorderRight - eventX;
      }
    }
    
    if(_posLeft < 0)
       _posLeft = 0;
       
  }
  return _posLeft;
}

// Get the top position by checking current window's border
// If part of current control is out of border, get the proper top position 
function KGOverlayControl_GetTop(_div, _posType, _posTop)
{
  var _windowHeight = KGOverlayControl_GetWindowHeight();
  var _controlHeight = KGOverlayControl_GetControlDivHeight(_div);

  if(_div != null && _windowHeight > 0 && _controlHeight > 0 && _posTop > 0)
  {
    var fromBorderBottom = _windowHeight - _controlHeight - KGOverlayControl_marginTop;
     
    if(fromBorderBottom < 0)
      fromBorderBottom = 0;

    if(_posType != null && _posType.toLowerCase() == 'absolute')
    {
      if(_posTop > fromBorderBottom)
        _posTop = fromBorderBottom;
      
    }
    else if (_posType != null && _posType.toLowerCase() == 'relative')
    {
      var eventY = KGOverlayControl_GetEventY();
      if(eventY != null && eventY > 0)
      {
        if(_posTop > fromBorderBottom - eventY )
          _posTop = fromBorderBottom - eventY;
      }
    }

    if(_posTop < 0)
       _posTop = 0;
       
  }
  return _posTop;
}

function KGOverlayControl_IsControlVisible_Wrapped(_controlId, _showClass, _hideClass)
{
  var control = document.getElementById(_controlId);
  if (control)
  {
    if (control.className == _showClass)
      return true;
    else if (control.className == _hideClass)
      return false;
  }
}

// JScript File
var ConceptSelectedTab;
var ConceptVisibility = 0;
var GlobalExpandedNavItemID = '';
var Global_SemanticTreeHolderID;
var ShowPublicCategory = 1;
var HasLeftHandSideCategories = 0;
var m_navCtlInitLoadCounter = 0;

function KGNavigationControl_InitialLoad_Wrapped(_categoryNavBar, _conceptNavBar, _srmIndex)
{
  //if(navigator.appName == "Microsoft Internet Explorer")
	{
		try
		{
			// set default clientID
			Global_SemanticTreeHolderID = _conceptNavBar.ClientControlId + '_' + _conceptNavBar.ClientControlId + '_p1';
			if (Global_SemanticTreeHolderID == 'undefined_undefined_p1' || !_conceptNavBar.get_items)
		  {
		    if (m_navCtlInitLoadCounter < 10)
		    {
		      setTimeout(KGNavigationControl_InitialLoad,250)
		      m_navCtlInitLoadCounter++;
		    }
		    return;
		  }
		  m_navCtlInitLoadCounter = 0;
		  
			KGNavigationControl_SetRepopulationHiddenFields();
	        
			var cItems = _categoryNavBar.get_items();
	    
			if(cItems.get_length() == 0)
			{
					ShowPublicCategory = 0;
			}else
			{
				HasLeftHandSideCategories = 1; 
			}
	          
			for (var ni = 0; ni < cItems.get_length(); ni++)
			{
				var cItem = cItems.getItem(ni);
				if(cItem.Expanded)
				{
					// populate
					KGNavigationControl_NavBarSelected(null, null, cItem, _srmIndex);
				}
			}
	    
			var pItem = _conceptNavBar.get_items().getItem(0);
			if(pItem != null && ConceptVisibility == 1 && pItem.Expanded)
			{
					// populate
					KGNavigationControl_NavBarSelected(null, null, pItem, _srmIndex);
			}
	    
			// override the ComponentArt NavBar js function to fix the expand error
			window._q134= KGNavBar_q134;
		}
		catch (e) 
		{
			alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
			debugger;
		}
	}
}

function KGNavigationControl_KeyConceptBtnOnClick_Wrapped(_categoryNavBar, _conceptNavBar, _srmIndex, _keyConceptBtn)
{
   var keyConceptImage = _keyConceptBtn;
   
   // Switch Images between ShowAllConcepts and JustKeyConcepts
   if(keyConceptImage != null)
   {
     if(keyConceptImage.className != null && keyConceptImage.className.indexOf('_AllConcepts',0) > -1)
     {
       keyConceptImage.className= "ButtonToolbar_KeyConcepts";//.src = 'Images/JustKeyConcepts.png';
       SetSessionProperty('KGNavigationControl_ShowKeyConcepts', '0');
     }
     else 
     {
       keyConceptImage.className= "ButtonToolbar_AllConcepts";//.src = 'Images/ShowAllConcepts.png';
       SetSessionProperty('KGNavigationControl_ShowKeyConcepts', '1');
     }
   }
            
   // repopulate NavigationControl and Semantic Tree
		KGNavigationControl_InitialLoad_Wrapped(_categoryNavBar, _conceptNavBar, _srmIndex);
   //KGNavigationControl_TreeNavBarRePopulate();
}

// Show or hide semantic tree check box cell
function KGNavigationControl_ShowHideSemanticTreeCheckBox_Wrapped(_status, _treeCheckBoxClientID)
{
   var cb = document.getElementById(_treeCheckBoxClientID);
   if(cb != null)
   {
      if(_status == 1)
        cb.className = 'NavBarCheckBoxCell';
      else
        cb.className = 'NavBarCheckBoxCellHidden';
   }
}


// Client Side On NavBar Close
function KGNavigationControl_NavBarClosed(sender, eventArgs, _navItem, _srmIndex)
{
  //debugger;
  if(eventArgs != null)
  {
     try {_srmIndex = SrmControl_SetInitial('KGNavigationControl_NavBarClosed');}
     catch(e){}   
     _navItem = eventArgs.get_item();
  }     
  if(_navItem != null)
  {
      SetSessionProperty('KGNavigationControl_CloseNavBar', _navItem.ID);
  }
}

// Client Side On NavBar Select
function KGNavigationControl_NavBarSelected_Wrapped(navItem, _titleLabelID, _modeAlertCheck, _cbreference, _groupID, _hiddenfieldID, _srmIndex)
{
  //debugger;
  try
  {
    if(navItem != null)
    {
      //SetSessionProperty('KGNavigationControl_ExpandNavBar', navItem.ID);
      
      try
      {
        if (m_srmGetTimes!= null && m_srmGetTimes == "True" && _srmIndex != null)
          m_srmAction[_srmIndex] += ',' + navItem.ID;
      }
      catch(e){}
      
      //debugger;
      var repopulateStatus = document.getElementById(_hiddenfieldID);
      if (repopulateStatus != null && repopulateStatus.value.indexOf(navItem.ID + '|') > -1)
      {
        repopulateStatus.value = repopulateStatus.value.replace(navItem.ID + '|', '');
        
        if(navItem.ID == 'SemanticTree' && global_ConceptTabbedControl_CurrentlySelectedTab.indexOf('CS_') != -1)
        {
            //Show loading icon (bug 2856)
            var holder = document.getElementById(Global_SemanticTreeHolderID + '_TopicsPage');
            if(holder != null)
            {
              holder.innerHTML = '<table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
            }
        }
        var args = 'Action=RepopulateNavBar|NavItemID=' + navItem.ID + '|SrmIndex=' + _srmIndex;
        eval(_cbreference);
        
        
        //if(navItem.ID.indexOf('CS_') > -1 && GlobalExpandedNavItemID == navItem.ID)
        //{
          
          //navItem.ParentNavBar.render();
        //}

      } // end if repopulate status true
      GlobalExpandedNavItemID = '';
            
      if (window.MapViewDefaultFocus)
        MapViewDefaultFocus();

      if (window.HomeContentControl_CallbackTrigger)
        HomeContentControl_CallbackTrigger();
    } 
    return true; //end navItem null if
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
} //end function

// SetRepopulationHiddenFields
function KGNavigationControl_SetRepopulationHiddenFields_Wrapped(_hiddenfieldID, _statusInfo) 
{
  //debugger;
  try
  {
    var repopulateStatus = document.getElementById(_hiddenfieldID);
    if (repopulateStatus != null) 
    {
      var statusInfo = '';
      // set status
      statusInfo = statusInfo + _statusInfo;
      repopulateStatus.value = statusInfo;
    } // end if repopulate status is not null
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
} //end function

// UpdateRepopulationHiddenFields
function KGNavigationControl_UpdateRepopulationHiddenFields_Wrapped(_hiddenfieldID, _statusInfo) 
{
  //debugger;
  
  if(_statusInfo.length > 0 && _statusInfo.lastIndexOf('|') == (_statusInfo.length - 1))
    _statusInfo = _statusInfo.substring(0,_statusInfo.length-1);
  
  try
  {
    var repopulateStatus = document.getElementById(_hiddenfieldID);
    if (repopulateStatus != null && repopulateStatus.value.indexOf(_statusInfo + '|')== -1) 
    {
      var statusInfo = repopulateStatus.value + _statusInfo + '|';
      // set status
      repopulateStatus.value = statusInfo;
    } // end if repopulate status is not null
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
} //end function


// RePopulateCallbackDone - Also used when Subscription changed as well
function KGNavigationControl_RepopulateNavBarCallbackDone_Wrapped(args, context, _categoryNavBar, _conceptNavBar)
{
  //debugger;
  try
  {
    // Check for a session time out before completing the callback
    if (CheckSessionTimeout())
      return;
    
    if(args.indexOf('Status=Error') > -1)
    {
      var statusInfo = args.split('[@|@]'); 
      var status = statusInfo[0].split('=');
      if(status[1]=='Error')
      {
        var holderID = statusInfo[1].split('=');
        var exception = statusInfo[2].split('=');
        var callbackerror = holderID[1] + '=' + exception[1];
        KGNavigationControl_ProcessCallBackError(callbackerror, '');
      }
    }
    else
    {
      var scriptToCall = args.split('[@|@]');
      var selectedTab = scriptToCall[3];
            
      var scriptFunction = scriptToCall[0].split('=');
      if(scriptFunction[1].length > 0)
      {
        var newArgs = args.substring(args.indexOf('[@|@]') + 5);
        newArgs = newArgs.replace(selectedTab + '[@|@]', '');
        eval(scriptFunction[1] + '(newArgs, context)');
      }
      else
      {
        KGNavigationControl_ProcessCallBackError('Script function not found.', '');
      }
    }
        
    var lastRootNodeHiddenFieldClientID;
    var lastRootNodeHiddenField;
    if (selectedTab == 'Results')
    {
      if (window.SearchResult_GetLastRootNodeHiddenFieldID)
      {
        lastRootNodeHiddenFieldClientID = SearchResult_GetLastRootNodeHiddenFieldID();
        lastRootNodeHiddenField = document.getElementById(lastRootNodeHiddenFieldClientID);
      }
    }
    else if (selectedTab.indexOf('CS') > -1)
    {
      if (window.Topic_GetLastRootNodeHiddenFieldID)
      {
        lastRootNodeHiddenFieldClientID = Topic_GetLastRootNodeHiddenFieldID();
        lastRootNodeHiddenField = document.getElementById(lastRootNodeHiddenFieldClientID);
      }
    }
    else if (selectedTab == 'Personal')
    {
      if (window.PersonalLibrary_GetLastRootNodeHiddenFieldID)
      {
        lastRootNodeHiddenFieldClientID = PersonalLibrary_GetLastRootNodeHiddenFieldID();
        lastRootNodeHiddenField = document.getElementById(lastRootNodeHiddenFieldClientID);
      }
    }

    if (lastRootNodeHiddenField != null)
    {
      if(args.indexOf('lastRootNodeID:') > -1)
      {
        var subLastRootNodeID = args.split('lastRootNodeID:');
        lastRootNodeHiddenField.value = subLastRootNodeID[1];
      }
      else
      {
        lastRootNodeHiddenField.value = null;
      }
      
    }
    
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function KGNavigationControl_RefocusTreeView_wrapped(_itemID,
                                                    _itemName,
                                                    _conceptNavBar,
                                                     _titleLabelClientID, 
                                                     _tabContextSeparator,
                                                    _MapViewDisplayModeKGMapView,
                                                    _cbreference,
                                                    _isBackButtonPress,
                                                    _srmIndex)
{
  //debugger;
  try
  {
    if (window.CancelEdit)
      CancelEdit(true);
    
    var navBar = eval(_conceptNavBar);
    var nItem = _conceptNavBar.get_items().getItem(0);
    if (nItem != null)
    {
      if(ConceptSelectedTab == 'Library')
        SetSessionProperty('GlobalLibrary_NewRootConceptID', _itemID);
      else if(ConceptSelectedTab == 'Personal')
        SetSessionProperty('PersonalLibrary_NewRootConceptID', _itemID);
      else if(ConceptSelectedTab == 'Results')
        SetSessionProperty('SearchResult_NewRootConceptID', _itemID);
      else if(ConceptSelectedTab.indexOf('Topic') > -1)
        SetSessionProperty('Topic_NewRootConceptID', _itemID);             
      
      var currentLocation = window.location.href;
      var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
      var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
      
      // refocus tree
      if (_isBackButtonPress == true)
        var args = 'Action=Refocus|NavItemID='+nItem.ID+'|BackButtonPress=true';
      else
        var args = 'Action=Refocus|NewRootConceptID='+_itemID+'|NavItemID='+nItem.ID+'|SrmIndex='+_srmIndex;
      eval(_cbreference);
      
      try
      {
        if (m_srmGetTimes!= null && m_srmGetTimes == "True" && _srmIndex != null)
        {
          m_srmAction[_srmIndex] += ',' + currentPage + ',' + currentTabID;
          m_srmCallbacks[_srmIndex] = 2;
        }
      }
      catch(e){}
      
      if(!(_isBackButtonPress == true && (_itemID == 0 || _itemID == -1)))
      {
        if (window.MapViewControl1_CallbackTrigger_IfVisible)
        {
          SetSessionProperty('MapViewDisplayMode', _MapViewDisplayModeKGMapView);
          MapViewControl1_CallbackTrigger_IfVisible(_srmIndex);
        }
       // if (window.KGTabbedWindowsControl_CallbackTrigger)
       //   KGTabbedWindowsControl_CallbackTrigger('ConceptSelected', _srmIndex);
      }
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

// DisplaySearchResult Callback scripts
function KGNavigationControl_CallbackTrigger_Wrapped(_itemID, _itemType, _itemName, _rootPhraseName,  _titleLabelClientID, _tabContextSeparator, _MapViewDisplayModeKGMapView, _cbreference, _srmIndex, _conceptNavBar)
{
  //debugger;
  try
  {
    //Show loading icon (bug 2856)
    var holder = document.getElementById(Global_SemanticTreeHolderID + '_ResultsPage');
    if(holder != null)
    {
      holder.innerHTML = '<table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
    }

    SetSessionProperty('PageSession_LibrarySelectedItemID', _itemID);
    SetSessionProperty('PageSession_LibrarySelectedItemTypeID', _itemType);
    SetSessionProperty('PageSession_LibrarySelectedITemName', _itemName);
        
    var currentLocation = window.location.href;
    var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
    
    // Update Mapview and TabbedWindow controls
    if(window.MapViewControl1_CallbackTrigger_IfVisible)
    {
      SetSessionProperty('MapViewDisplayMode', _MapViewDisplayModeKGMapView);
      MapViewControl1_CallbackTrigger_IfVisible(_srmIndex);
    }
    //if (window.KGTabbedWindowsControl_CallbackTrigger)
    //  KGTabbedWindowsControl_CallbackTrigger('ConceptSelected', _srmIndex);
    
    var pItem = _conceptNavBar.get_items().getItem(0);
    if(pItem != null && ConceptVisibility == 1 && pItem.Expanded)
    {
      var args = 'Action=DisplaySearchResult|ItemID='+_itemID+'|'+'ItemType='+_itemType+'|'+'ItemName='+_itemName+'|SrmIndex='+_srmIndex;
      eval(_cbreference);
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function KGNavigationControl_CallbackDone_Wrapped(args, context)
{
  //debugger;
  try
  {
    // Check for a session time out before completing the callback
    if (CheckSessionTimeout())
      return;
          
    var s = args.split('='); 
    var ids = s[0].split('@');
    
    var holder = document.getElementById(ids[0]);
    if(holder != null)
    {
      holder.innerHTML = args.substring(args.indexOf('=')+1);
      // need to redeclare the storage and the main function before calling it
      // therefore get the text of it
      // storage first
      var pos1 = args.indexOf('![CDATA[');
      if ( pos1 > - 1)
      {
        var string2 = args.substring(pos1, args.length);
        var pos2 = string2.indexOf('[[');
        var pos3 = string2.indexOf('//]]>');
        if ( pos2 > -1 && pos3 > -1 )
        {
          var storageString = string2.substring(pos2, pos3);
          var evalStorageString = 'window.ComponentArt_Storage_' + ids[1] + '_ResultTree = ' + storageString;
          // eval the string
          eval(evalStorageString);
          // now the init string
          var pos4 = string2.lastIndexOf('![CDATA[');
          if ( pos4 > -1 )
          {
            var string3 = string2.substring(pos4, string2.length);
            var pos5 = string3.indexOf('{');
            var pos6 = string3.lastIndexOf('}');
            if ( pos5 > -1 && pos6 > -1 )
            {
              var initString = string3.substring(pos5, pos6 + 1);
              var evalInitString = 'window.ComponentArt_Init_' + ids[1] + '_ResultTree = function()' + initString;
              // eval the string
              eval(evalInitString);
              // now execute it now that we've redefined it
              eval('ComponentArt_Init_' + ids[1] + '_ResultTree()');
            } // end if pos5 and pos6
          } // end if pos4
        } // end if pos2 and pos3
      } // end if pos1
      
      // Highlisht Selected TreeNode
      if(ids[2] != null && ids[3] != null)
      {
        var nodeId = ids[2];
        var treeId = ids[3];
        var aTreeNode = null;
        var aTreeView = null;
        
        if(treeId != null && treeId !='' && treeId != '-1' && eval('window.'+ treeId+'!=null'))
          aTreeNode = eval(treeId + '.FindNodeById(\'' + nodeId + '\')');
          
        if(aTreeNode != null) 
        {
          aTreeView = aTreeNode.ParentTreeView;
          
          if(aTreeView!= null && aTreeView.TreeViewID != null && aTreeView.TreeViewID != '')
            conceptTreeControl_preTreeViewID = aTreeView.TreeViewID;
          
          if(aTreeNode.ID != null && aTreeNode.ID != '')
            conceptTreeControl_preTreeNodeID = aTreeNode.ID;
          
          aTreeView.SelectedNode = aTreeNode;
        } 
        
      } 
    }
    else
    {
      KGNavigationControl_ProcessCallBackError('Content Cell not found.', '');
    }
    
    var searchResultsTreeLastRootNodeHiddenFieldClientID = SearchResult_GetLastRootNodeHiddenFieldID();
    var searchResultLastRootNodeHiddenField = document.getElementById(searchResultsTreeLastRootNodeHiddenFieldClientID);
    searchResultLastRootNodeHiddenField.value = null;
    
    //var tabStrip = _tabStripClientID;
    //var tab = tabStrip.GetSelectedTab();
    //ConceptTabbedView_ChangeBackButtonMode(ShowBackButton(tab));
    m_treeViewIsLoaded = true;
		setPaneWidths();
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
  try
  {
    var srmIndex = ids[4];
    SrmControl_RecordTimes(srmIndex);
  }
  catch(e){}
};

// ProcessCallBackError
// this will return message in case of error
function KGNavigationControl_ProcessCallBackError(args, context)
{
  //debugger;
  try
  {  
    // Here we are dealing with authentication timeout before callback, 
    // the message from the server is 'elogin' signify an error with 
    // authentication. The response will be trimmed to form the args 
    // 'login' here..... 
    if(args == 'login')
    {
      window.location='home.aspx';
    }
    else
    {
      if(args.indexOf('=') > -1)
      {
        var s = args.split('='); 
        var holder = document.getElementById(s[0]);
        if(holder != null)
        {
          holder.innerHTML = 'An error has occurred. ' + s[1];
        }
        else
        {
          alert('Exception occurred. '+ s[1]);
        }
      }
      else
      {
        alert('Exception occurred. '+ args);
      }
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

// Check box javascripts
function KGNavigationControl_SubscriptionModeChanged_Wrapped(_cb, _cbreference)
{
  //debugger;
  try
  {
		var optiondiv = document.getElementById('KGOptionControlID1');
    var loginview = "Library_LoginView_";
    try
    {
      loginview = "Library_LoginView_";
      var check = document.getElementById(loginview + "KGOptionControl_ImageNumber0").src = "Images/newGeneOption.png";
    }
    catch(Exception)
    {
      loginview = "";
    }
    
    if(_cb == false)
    {
      SetSessionProperty('ConceptTabbedView_AllowSubscripton', true);
      var args = 'Action=SubscriptionModeChanged|Value=' + true;
      eval(_cbreference);
      document.getElementById(loginview + "KGOptionControl_ImageNumber4").src = "Images/LeftSubsOn.png";        
      document.getElementById(loginview + "KGOptionControl_CellNumber4").onclick = function(){KGNavigationControl_SubscriptionModeChanged(true)};     
      document.getElementById(loginview + "KGOptionControl_CellNumber4").onmouseover = function(){this.style.cursor='pointer'};
    }
    else
    {
      SetSessionProperty('ConceptTabbedView_AllowSubscripton', false);
      var args = 'Action=SubscriptionModeChanged|Value=' + false;
      eval(_cbreference);
      document.getElementById(loginview + "KGOptionControl_ImageNumber4").src = "Images/LeftSubsOff.png";        
      document.getElementById(loginview + "KGOptionControl_CellNumber4").onclick = function(){KGNavigationControl_SubscriptionModeChanged(false)};     
      document.getElementById(loginview + "KGOptionControl_CellNumber4").onmouseover = function(){this.style.cursor='pointer'};
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
} //end function

function KGNavigationControl_AlertSettingModeChanged_Wrapped(_cb, _cbreference, _srmIndex) 
{
  //debugger;
  try
  {
    if (m_srmGetTimes!= null && m_srmGetTimes == "True" && _srmIndex != null)
      m_srmAction[_srmIndex] += ',' + !_cb;
  }
  catch(e){}

  try
  {
    var optiondiv = document.getElementById('KGOptionControlID1');
    var loginview = "Library_LoginView_";
    
    try
    {
      loginview = "Library_LoginView_";
      var check = document.getElementById(loginview + "KGOptionControl_ImageNumber0").src = "Images/newGeneOption.png";
    }
    catch(Exception)
    {
      loginview = "";
    }

    if(_cb == false)
    {
      SetSessionProperty('ConceptTabbedView_AllowChangeAlertSetting', true);
      var args = 'Action=AlertSettingModeChanged|Value=' + true + '|SrmIndex=' + _srmIndex;
      eval(_cbreference);
      document.getElementById(loginview + "KGOptionControl_ImageNumber3").src = "Images/LeftAlertsOfn.png";        
      document.getElementById(loginview + "KGOptionControl_CellNumber3").onclick = function(){KGNavigationControl_AlertSettingModeChanged(true)};     
      document.getElementById(loginview + "KGOptionControl_CellNumber3").onmouseover = function(){this.style.cursor='pointer'};
    }
    else
    {
      SetSessionProperty('ConceptTabbedView_AllowChangeAlertSetting', false);
      var args = 'Action=AlertSettingModeChanged|Value=' + false + '|SrmIndex=' + _srmIndex;
      eval(_cbreference);
      document.getElementById(loginview + "KGOptionControl_ImageNumber3").src = "Images/LeftAlertsOff.png";        
      document.getElementById(loginview + "KGOptionControl_CellNumber3").onclick = function(){KGNavigationControl_AlertSettingModeChanged(false)};     
      document.getElementById(loginview + "KGOptionControl_CellNumber3").onmouseover = function(){this.style.cursor='pointer'};
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
} //end function


// Check box javascripts
function KGNavigationControl_ShowHideSemanticTree_Wrapped(_cb, _holderClientID, _conceptNavBar, _navImageHeader, _item) 
{
  //debugger;
  return;
  try
  {
    var holder = document.getElementById(_holderClientID);
    
    var navImageHeader = document.getElementById(_navImageHeader);
    
    var menuItem = _item;

    if(holder != null)
    {
        if(_cb.checked)
        {
          SetSessionProperty('KGNavigationControl_SemanticTreeVisible', true);
          ConceptVisibility = 1;
          holder.className = 'NavBarsCell';
          navImageHeader.className = 'NavBarTitleHidePic';

          var pItem = _conceptNavBar.get_items().getItem(0);
          if(pItem != null && ConceptVisibility == 1)
          {

              try {srmIndex1 = SrmControl_SetInitial('ShowSemanticTree');}
              catch(e){}
              // populate
              KGNavigationControl_NavBarSelected(null, null, pItem, srmIndex1);
          }
          
        }
        else
        {
          SetSessionProperty('KGNavigationControl_SemanticTreeVisible', false);
          ConceptVisibility = 0;
          holder.className = 'NavBarsCellHidden';

          navImageHeader.className = 'NavBarTitleShowPic_';  
          if(menuItem != null)
          {
            //if(_cb.disabled == true)
            if(menuItem.Text == "All")
            {
              SetInnerText(navImageHeader,"");
            }
            else
            {
              SetInnerText(navImageHeader,menuItem.Text);
            }
          }  
        }
    }
  }
  catch (e)
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message);
    //debugger;
  }
} //end function

function KGNavigationControl_UpdateSemanticTreeTitle_Wrapper(_tabID, _titleLabelClientID, _tabContextSeparator, _subfixName)
{
  
  try
  {
        // update title lable
        _titleLabelClientID = Global_SemanticTreeHolderID + '_ConceptTitleLabel';
        //_keyConceptBtn = Global_SemanticTreeHolderID + '_' + _keyConceptBtn;
        var titleLabel = document.getElementById(_titleLabelClientID);
        // var keyConceptImg = document.getElementById(_keyConceptBtn);
        
        var tabName = 'Categories';
        if(_tabID.indexOf('CS') == -1)
        {
          switch(_tabID)
          {
            case 'Personal':
              tabName = 'My Knowledge';
              break;
            case 'Results':
              tabName = 'Search';
              break;
          }
        }
        
        if(titleLabel != null)
        {
          if(_subfixName != null && _subfixName.length > 0)
          {
            titleLabel.innerHTML = tabName + _tabContextSeparator + _subfixName;
          }else
          {
            titleLabel.innerHTML = tabName;
          }
        }
        
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function KGNavigationControl_SwitchTabs_Wrapper(_tabID, _titleLabelClientID, _tabContextSeparator, _subfixName, _groupNameHiddenField, _groupIDHiddenField)
{
  try
  {
  //debugger;
		ConceptSelectedTab = _tabID;
		var multipageID = Global_SemanticTreeHolderID + '_ConceptLibraryPages';
		var mp = eval(multipageID);
		var pageID = 'CategoriesPage';
		var pageIndex = 2;
		switch(_tabID)
		{
			case 'Results':
				pageID = 'SearchResultsPage';
				pageIndex = 1;
				break;
			case 'Personal':
				pageID = 'PersonalLibraryPage';
				pageIndex = 0;
				break;
			default:
				pageID = 'CategoriesPage';
				pageIndex = 2;
				break;
		}
    if(mp != null)
    {
      var mpageId = Global_SemanticTreeHolderID + '_' + pageID;
      var mselpageId = Global_SemanticTreeHolderID + '_' + mp.get_selectedPage().Id;
      mp.SetPageId(pageID);
      if(mpageId != mselpageId)
      {
        var mpageDiv = document.getElementById(mpageId);
        if(mpageDiv != null)
        {
          mpageDiv.style.display = 'block';
          var moldpageDiv = document.getElementById(mselpageId);
          if(moldpageDiv != null)
          {
            moldpageDiv.style.display = 'none';
          }
        }
      }
    }
    
    // Close the docked window if it is open.    
    var dockedWindow = document.getElementById('DockedHelpWindow');
    if(dockedWindow != null)
      CloseDockedKGHelpControl();
      
    // Close the pop up window
    if(window.HideKGHelpControl)
      HideKGHelpControl();
        
    // select current tab
    global_ConceptTabbedControl_CurrentlySelectedTab = _tabID;
    SetSessionProperty('ConceptTabbedView_SelectedTab', _tabID);
    if(_subfixName != null && _subfixName.length > 0)
    {
      SetSessionProperty('KGNavigationControl_SemanticTreeTitleSubFix', _subfixName.replace('&','%26'));
    }else
    {
        SetSessionProperty('KGNavigationControl_SemanticTreeTitleSubFix', '');
    }
    
    KGNavigationControl_UpdateRepopulationHiddenFields('SemanticTree|');
    
    // updat tab text
    KGNavigationControl_UpdateSemanticTreeTitle(_tabID, _subfixName);

    // Set hidden fields
    var groupName = document.getElementById(_groupNameHiddenField);
    if(groupName != null)
    {
      groupName.value = "Temp Text";
    }
        
    var groupID = document.getElementById(_groupIDHiddenField);
    if(groupID != null)
    {
      groupID.value = _tabID;
    }

    var currentLocation = window.location.href;
		var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
    if(window.location.href == hostURL + "PrivateSpaceAdmin.aspx" && _tabID.substr(0,3) != 'CS_')
    {
      window.location = "home.aspx";
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}


function KGNavBar_q134(_28,_29,_2a,_2b)
{
//debugger;
if(_q135)
{return;}

if(_q130==_29)
{return;}

var _2c=_28.get_events().getHandler("itemBeforeExpand");

if(_2c)
{

var _2d=new ComponentArt.Web.UI.NavBarItemCancelEventArgs(_2a);
_2c(_28,_2d);
if(_2d.get_cancel()){return;}}
if(_28.ClientSideOnItemExpand&&(!(eval(_28.ClientSideOnItemExpand))(_2a))){return;}
if(_2a.AutoPostBackOnExpand)
{__doPostBack(_28.ControlId,"EXPAND "+_2a.PostBackID);return;}
if(_29.childNodes.length==0)
{_29.innerHTML=_2a.GetSubGroupHtml();}
var _2e=true;
var _2f=0;

if(_28.FullExpand&&_28.ExpandSinglePath)
{

  if(!_28.FullExpandHeight)
  {
    var _30=document.getElementById(_28.NavBarID);
    if(cart_browser_ie&&_30.currentStyle)
    {
    var _31=0;_31+=_30.currentStyle.paddingTop?parseInt(_30.currentStyle.paddingTop):0;_31+=_30.currentStyle.paddingBottom?parseInt(_30.currentStyle.paddingBottom):0;_28.FullExpandHeight=_30.offsetHeight-_30.scrollHeight-_31;
    }
    else{
      var _31=0;
      var _32=document.defaultView.getComputedStyle?document.defaultView.getComputedStyle(_30,""):_30.style;_31+=_32.getPropertyValue("border-top-width")?parseInt(_32.getPropertyValue("border-top-width")):0;_31+=_32.getPropertyValue("border-bottom-width")?parseInt(_32.getPropertyValue("border-bottom-width")):0;_31+=_32.getPropertyValue("padding-top")?parseInt(_32.getPropertyValue("padding-top")):0;_31+=_32.getPropertyValue("padding-bottom")?parseInt(_32.getPropertyValue("padding-bottom")):0;
      var _33=_30.lastChild;
      if(_33.previousSibling)
      {
      while(_33&&!(_33.id&&_33.id.indexOf(_28.NavBarID+"_item_")==0))
      {_33=_33.previousSibling;}
      }
      if(_33)
      {var _34=_q86(_33)+_33.offsetHeight;
      var _35=_q86(_30)+_30.offsetHeight;
      _28.FullExpandHeight=_35-_34-_31;}
      }
      if(_28.FullExpandHeight<=0)
      {_28.FullExpandHeight=_30.parentNode.offsetHeight-_30.offsetHeight-_31;}
      if(_28.FullExpandHeight<=0){_28.FullExpandHeight=document.body.offsetHeight-_30.offsetHeight-_31;}
      if(_28.FullExpandHeight<=0){_28.FullExpandHeight=document.body.offsetHeight;}
    }
    _2f=_28.FullExpandHeight;
  }
  else
  {
    if(_2a.SubGroupHeight>0)
    {_2f=_2a.SubGroupHeight;}
    else{var _36=_29.cloneNode(false);
    _36.style.visibility="hidden";
    _36.style.display="block";
    _36.style.height="";
    document.body.appendChild(_36);
    _2f=_36.offsetHeight;_qE7(_36);
    _2e=false;}
  }

  if(_2e)
  {_29.style.height=_2f+"px";}
  else{_29.style.height="";}

  _2a.SetProperty("Expanded",true);
  _q135=_29.parentNode;
  _q135.ParentNavBar=_28;
  _q135.ParentItem=_2a;
  _q135.style.height="1px";
  _q135.style.display="block";
  _q135.style.overflow="hidden";
  var _37=null;

  if(_28.ExpandSinglePath)
  {

      var _38;var _39=_2a.GetParentItem();
      if(_39)
      {_38=_39.Items();}
      else{_38=_28.Items();}

      for(var i=0;i<_38.length;i++)
      {
        if(_38[i].GetProperty("Expanded")&&_38[i].ChildItemArray.length>0&&_38[i].StorageIndex!=_2a.StorageIndex)
        {_38[i].Collapse(_2b);}}

        _37=document.getElementById(_28.NavBarID+"_item_"+_2a.StorageIndex);
        if(_37.onmouseout){_37.onmouseout();}
      }

      var _3b=_28.ExpandDuration;
      if(_2b){_3b=0;}
      if((_28.ExpandTransition>0||_28.ExpandTransitionCustomFilter)&&_3b>0&&cart_browser_transitions)
      {

      if(!_29.ExpandTransitionFilterDefined)
      {
        var _3c=ComponentArt_EffectiveTransitionString(_28.ExpandTransition,_28.ExpandTransitionCustomFilter);
        _29.ExpandTransitionFilterIndex=_29.filters.length;
        _29.ExpandTransitionFilterDefined=true;
        _29.runtimeStyle.filter=_29.currentStyle.filter+" "+_3c;
      }

      _29.style.visibility="hidden";
      _29.filters[_29.ExpandTransitionFilterIndex].apply();
      _29.style.visibility="visible";
      _29.filters[_29.ExpandTransitionFilterIndex].play(_3b/1000);

  }
  _q136=(new Date()).getTime();
  ComponentArt_NavBar_ExpandDivStep(_2f,_3b,_28.ExpandSlide,_2e);
  ComponentArt_ConsiderExpandedStyle(_28,_2a.StorageIndex);
  _2a.RememberExpandState();

}

// KGIndexedDocListControl JScript File

function KGIndexedDocListControl_documentSelectionDropListIndexChanged(_documentSelectionDropList, _theGrid, _GridType)
{
  var options = _documentSelectionDropList.getElementsByTagName("option");
  var selectedItem = options[_documentSelectionDropList.selectedIndex];
  // confirm the item is in the list before applying the filter
  if (selectedItem.className == "docList_dropList_availableItem")
  {
    // set the session property (used to determine what to include in the grid population)
    SetSessionProperty("KGIndexedDocList_docTypeFilter", _documentSelectionDropList.value);
    SetSessionProperty("KGIndexedDocList_repopulateByDropList", true);
    if(savedConcept != 0)
			SetSessionProperty('KGIndexedDocList_repopulateByConceptId', savedConcept);
		else
			SetSessionProperty('KGIndexedDocList_repopulateByKnowdeId',returnKnowdeID(globalLastSelectedKnowde));
    
    // force the indexed doc tab to repopulate
    globalIndexedDocsPageLoaded = false;
    setTimeout("KGTabbedWindowsControl_SelectTabById('Indexed Documents');", 20);
  }
  else
	{
		var sortList = document.getElementById("sortListDiv");
		sortList.style.visibility = "hidden";
		SetSessionProperty("KGIndexedDocList_docTypeFilter", _documentSelectionDropList.value);
	}
}

function KGIndexedDocListControl_sortDropListIndexChanged(_sortDropList, _theGrid, GridType, _dropListSelector)
{
  var options = _sortDropList.getElementsByTagName("option");
  var selectedItem = options[_sortDropList.selectedIndex];
  // confirm the item is in the list before applying the filter
  if (selectedItem.className == "docList_dropList_availableItem")
  {
    // set the session property (used to determine what to include in the grid population)
    switch (_dropListSelector)
    {
      case "All":
        SetSessionProperty("KGIndexedDocList_sortAllFilter", _sortDropList.value);
        break;
      case "AllFeatured":
        SetSessionProperty("KGIndexedDocList_sortAllFeaturedFilter", _sortDropList.value);
        break;
      case "KG":
        SetSessionProperty("KGIndexedDocList_sortKGFilter", _sortDropList.value);
        break;
      case "Web":
        SetSessionProperty("KGIndexedDocList_sortWebFilter", _sortDropList.value);
        break;
      case "News":
        SetSessionProperty("KGIndexedDocList_sortWebFilter", _sortDropList.value);
        break;
      case "Blogs":
        SetSessionProperty("KGIndexedDocList_sortWebFilter", _sortDropList.value);
        break;
    }
    SetSessionProperty("KGIndexedDocList_repopulateByDropList", true);
    if(savedConcept != 0)
			SetSessionProperty('KGIndexedDocList_repopulateByConceptId', savedConcept);
		else
			SetSessionProperty('KGIndexedDocList_repopulateByKnowdeId',returnKnowdeID(globalLastSelectedKnowde));

    // force the indexed doc tab to repopulate
    globalIndexedDocsPageLoaded = false;
    setTimeout("KGTabbedWindowsControl_SelectTabById('Indexed Documents');", 20);
  }
}

function closeIndexedDocuments()
{
//debugger;
//check for a docked help window
var dockedHelp = document.getElementById("DockedHelpWindowContainer")

if(dockedHelp != null)
{
  dockedHelp.style.width = screen.width;
  document.getElementById("DockedHelpWindow").style.width = "100%";
  if(document.frames)
  {
    document.frames['DockedHelpWindow'].location.reload(true);
  }
  
  document.getElementById("KGTabbedWindowsControl1").style.height = dockedHelp.style.height;
  document.getElementById("KGTabbedWindowsControl1").style.overflowY = "hidden";
}
else
{
  SplitterControl('down');
}

globalHideIndexedDocs = true;

}
// JScript File
// For KGChangePasswordControl
function KGChangePasswordControl_ChangePasswordClick()
{
  var args = 'action=ChangeDisplayMode|mode=Update';
  KGChangePasswordControl_CallbackTrigger(args);
}

function KGChangePasswordControl_CancelUpdateClick()
{
  var args = 'action=ChangeDisplayMode|mode=Display';
  KGChangePasswordControl_CallbackTrigger(args);
}

function KGChangePasswordControl_UpdateClick(_btn)
{
  var hiddenFieldId = _btn.getAttribute("HiddenFieldId");
  var hiddenField = document.getElementById(hiddenFieldId);
  var inputControlIds = eval( '(' + hiddenField.value + ')' );
  
  var args = 'action=Update';
  args += '|currentPassword=' + ReadTextBoxValue(inputControlIds.currentPassword);
  args += '|newPassword=' + ReadTextBoxValue(inputControlIds.newPassword);
  args += '|confirmNewPassword=' + ReadTextBoxValue(inputControlIds.confirmNewPassword);


  KGChangePasswordControl_CallbackTrigger(args);
}

function KGChangePasswordControl_CallbackDone_Wrapped(args, context, controlDivId)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  var controlDiv = document.getElementById(controlDivId);
  
  if(controlDiv != null)
    controlDiv.innerHTML = args;
  else
    KGUserProfileControl_CallbackError('Can not find UserProfileForm element.', context, controldivId);    
}

function KGChangePasswordControl_CallbackError_Wrapped(args, context, controlDivId)
{
  // debugger;
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    var controlDiv = document.getElementById(_controlDivId);
    
    if(controlDiv != null)
    {
      controlDiv.innerHTML = args;
    }
    else
    {
      alert('Can not find contentDiv for ChangePassword control.');
    } 
  }
}

// JScript File
// for KGUserObjectSummaryControl
var selectedKGForDelete;
var selectedGroupIdForKGDelete;
var CurrentlyShowingUosMessageBox;
var m_UosMessageBox = null;
var m_UosNewVersionKGMessageBox = null;
var m_CurrentGridControl;

///////////////////////
// Ensures that the delete message box is on the page
function EnsureDeleteKGMessage(_parentControlDivId)
{
  m_UosMessageBox = document.getElementById("DeleteKGMessageBox");
  
  if(m_UosMessageBox == null)
  {
    m_UosMessageBox = document.createElement("div");
    m_UosMessageBox.setAttribute("id", "DeleteKGMessageBox");
    m_UosMessageBox.style.display = "none";
    m_UosMessageBox.style.width = "400px"
    m_UosMessageBox.style.height = "160px";
    m_UosMessageBox.style.position = "absolute";
    m_UosMessageBox.style.zIndex = TopZIndex();
    
    m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Do you want to delete this Knowledge Gene<sup>&#174;</sup>?</td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>Deleting this Knowledge Gene&reg; will remove it from the database. Any attachments and other information associated with this Knowledge Gene<sup>&#174;</sup> will also be removed. <br/>Any published versions will also be lost.</td></tr><tr><td align='right'><button type='button' onclick='KGUserObjectSummaryControl_DeleteKG()'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";
    
    //var parentControlDiv = document.getElementById(_parentControlDivId);
    //InsertAdjacentElement(document.body,"afterBegin", m_UosMessageBox);
    document.body.appendChild(m_UosMessageBox);
  }
  else
  {
    m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Do you want to delete this Knowledge Gene<sup>&#174;</sup>?</td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>Deleting this Knowledge Gene&reg; will remove it from the database. Any attachments and other information associated with this Knowledge Gene<sup>&#174;</sup> will also be removed. <br/>Any published versions will also be lost.</td></tr><tr><td align='right'><button type='button' onclick='KGUserObjectSummaryControl_DeleteKG()'>Yes</button><button id = defaultButton type='button' onclick='CloseUOSMessageBox()'>Cancel</button></td></tr></table></div>";

    m_UosMessageBox.style.zIndex = TopZIndex(); //Show on top of other items
  }
}

function TopZIndex()
//Find highest z index in current document and returns this value + 1 (so that
//the control using this value will appear on top of everything currently in  
//the page, but will appear behind everything called subsequently).  JPC.
//(inspired by http://domscripting.com/presentations/atmedia2006/slides/, slide 12)
{
  var maxZindex = 0;
  var elems = document.getElementsByTagName("div");
  
  for (var ti=0; ti<elems.length; ti++)
  {
    if (elems[ti].style.zindex > maxZindex)
    {
       maxZindex = parseInt(elems[ti].style.zindex);
    }
  }

  return maxZindex + 1;
}

/////////////////////
// Positions the supplied message box relative to the cursor
function PositionUosMessageBox(_parentControlDivId, _isKeyPressEvent, e)
{
  var parentControl = document.getElementById(_parentControlDivId); 
  
  if(_isKeyPressEvent)
  {
    // we don't know where the cursor is (may be off the page) so display in middle of parentControlDiv
    var coords = findPos(_parentControlDivId);
    m_UosMessageBox.style.top = coords[1] - 100; // (parentControl.offsetHeight/2);
    m_UosMessageBox.style.left = coords[0]; // (parentControl.offsetWidth/2) - (GetPixelWidth(m_UosMessageBox)/2);
  }
  else
  {
    //Displays messagebox relative to cursor  
    //Displays messagebox in middle of visible screen.  JPC.
    e = e || window.event;
    
    var btn = e.target || e.srcElement;
    var coords = findPos(btn);
    var x = e.clientX;
    var y = e.clientY;
    
    m_UosMessageBox.style.top = Math.min(document.body.clientHeight - GetPixelHeight(m_UosMessageBox),y + 30);     
    m_UosMessageBox.style.left = x - GetPixelWidth(m_UosMessageBox) / 2;
  }
  m_UosMessageBox.style.display = "block";
  m_UosMessageBox.style.zIndex = TopZIndex();
  m_UosMessageBox.style.visibility = "visible";
  focusOn("defaultButton");
  CurrentlyShowingUosMessageBox = true;
}

function focusOn(buttonId)
{
  var focusButton = document.getElementById(buttonId)
  if (focusButton != null)
  {
    // This line is necessary for the code to work with the WhatExists box.  
    // this may be due to my implementation of the box.  JPC
    focusButton.style.visiblity = "visible";  
    try
    {
        focusButton.focus();
    }
    catch(er)
    {
    }
  }
}

//////////////////
// Closes the message box
function CloseUOSMessageBox()
{
  if(m_UosMessageBox != null)
  {
    m_UosMessageBox.style.visibility = "hidden";
    m_UosMessageBox.style.display = "none";
    CurrentlyShowingUosMessageBox = false;
  }
}

function KGUserObjectSummaryControl_DislayDeleteKGMessage(_kgId, _groupId, _controlDivClientID, e)
{
  // debugger;
  
  KGUserObjectSummaryControl_CancelKGRename(CurrentlyRenamingKGID, _controlDivClientID);  
  selectedKGForDelete = _kgId;
  selectedGroupIdForKGDelete = _groupId;
  EnsureDeleteKGMessage(_controlDivClientID);
  PositionUosMessageBox(_controlDivClientID, false, e);
}

function KGUserObjectSummaryControl_DeleteKG()
{
  m_UosMessageBox.innerHTML= '<div style=\"position:absolute;width:400px;height:120px;border:gray solid 1pt;background:white\"><table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" />Deleting Knowledge Gene....</td></tr></table></div>';
  
  var args = 'action=deleteKG|kgId=' + selectedKGForDelete + '|groupId='+ selectedGroupIdForKGDelete;
  
  // if the KG being deleted is the only one on the last page, we'll need to decrease the current page (done at the server)
  //    only necessary if it's not the first page
  var pageInfo = PflPriv_ListView_GetPageInfo();
  if (pageInfo.CurPage > 1 && pageInfo.IsShowingSingleItem())
    args += '|pageBack=true';
  
  Pfl_KGUserObjectSummaryControl_CallbackTrigger(args);
}

function EnsureCopyKGMessage(_parentControlDivId)
{
  m_UosMessageBox = document.getElementById("CopyKGMessageBox");
  
  if(m_UosMessageBox == null)
  {
    m_UosMessageBox = document.createElement("div");
    m_UosMessageBox.setAttribute("id", "CopyKGMessageBox");
    m_UosMessageBox.style.display = "none";
    m_UosMessageBox.style.width = "400px"
    m_UosMessageBox.style.height = "120px";
    m_UosMessageBox.style.position = "absolute";
    m_UosMessageBox.style.zIndex = TopZIndex();
    
    m_UosMessageBox.innerHTML= '<div style=\"position:absolute;width:400px;height:120px;border:gray solid 1pt;background:white\"><table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" />Copying Knowledge Gene....</td></tr></table></div>';
    
    document.body.appendChild(m_UosMessageBox);
  }
  else
  {
    m_UosMessageBox.style.zIndex = TopZIndex(); //Show on top of other items
  }
}


function KGUserObjectSummaryControl_CopyKG(_kgId, _controlDivClientID, e)
{
  //debugger;
  KGUserObjectSummaryControl_CancelKGRename(CurrentlyRenamingKGID, _controlDivClientID);  
  EnsureCopyKGMessage(_controlDivClientID);
  PositionUosMessageBox(_controlDivClientID, false, e);

  var args = 'action=copyKG|kgId=' + _kgId;
  
  Pfl_KGUserObjectSummaryControl_CallbackTrigger(args);
}


function KGUserObjectSummaryControl_CallbackTrigger_Wrapped(_args, _cbReference)
{
  // pass back the current page numbers
  // alternative could be to save them in the session, but it could lead to a lot of bugs if they aren't cleared properly
  _args += '|curPagePriv=' + PflPriv_ListView_GetPageInfo("CurPage");
  _args += '|curPagePub=' + PflPub_ListView_GetPageInfo("CurPage");
  
  CallbackTrigger_Wrapped(_args, _cbReference);
}

// CallbackDone
function KGUserObjectSummaryControl_CallbackDone(_args, _context)
{
  // check for exceptions
  if (_args.indexOf("Exception") == 0 || _args.length == 0)
  {
    KGUserObjectSummaryControl_CallbackError(_args, _context);
    return;
    // looking for indexOf == 0 instead of > -1 incase it's genuine html that happens to contain 'Exception' in there
    // e.g. a user called "... Exceptional ..." 
  }
  
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  // get the parameters
  var argsSplit = _args.split('[@|@]');
  var holderId = argsSplit[0];
  var kgvalid = argsSplit[1];
  var htmlContent = argsSplit[2];
  
  // search for the control container
  var holder = document.getElementById(holderId);
  
  // Test if the container is found
  // Yes: replace the innerHTML with the callback result
  //  No: call CallbackError with Content div not found error message
  if(holder != null)
  {
    // holder.innerHTML = args.substring(args.indexOf('=') + 1);
    holder.innerHTML = htmlContent;
    
    CurrentlyRenamingKGID = null;
    
    
    // make sure the publish control is hidden, otherwise it will pop to top left after rerender
    if(g_publishHolderId != null && window.KGPublishOptionControl_HideMenu)
    {
      KGPublishOptionControl_HideMenu(g_publishHolderId);
    }
  
    CloseUOSMessageBox();
  }//end if(holder ....
  else
  {
    KGUserObjectSummaryControl_CallbackError('ContentDiv not found in KGUserObjectSummaryControl.', '');
  }
  
  // kg might have been removed
  if(kgvalid.toLowerCase() == 'false')
     window.setTimeout("ClearActiveKG()",200);
}

// CallbackError Handling
function KGUserObjectSummaryControl_CallbackError(args, context)
{
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    //debugger;
    alert(args);
  }
}

function PublicKGs_OnCallbackError()
{
  KGUserObjectSummaryControl_CallbackError('login', '');
}

// PublicKG grid will call this for handlling item clicks
// It will populate the m_CurrentGridControl global variable 
// for further processing
function KGUserObjectSummaryControl_OnClientSideSelect_NoRedirect(kgId, selectedKgAuthorId)
{
  PrepareSessionForMapView(kgId, selectedKgAuthorId);
  // Fix for disappearing pane problem (assigned to JPC, but fix suggested by CM - thanks!)
  var mapViewCollapsed = PaneBStatus();
  if (mapViewCollapsed == false) // map view is visible, reload it
    MapViewControl1_CallbackTrigger();
    
 // global_TabbedWindowsControl_CurrentlySelectedTab = "Indexed Documents";
  //KGTabbedWindowsControl_SelectTabById('Indexed Documents');
  //KGTabbedWindowsControl_CallbackTrigger('KGSelected', -1); 
  KGTabbedWindowsControl_KGSelected(null, selectedKgAuthorId, kgId, false, false);
  //global_TabbedWindowsControl_CurrentlySelectedTab = "Indexed Documents";
}

function KGUserObjectSummaryControl_OnClientSideSelect_WithRedirect(kgId, selectedKgAuthorId, _redirectUrl)
{
  PrepareSessionForMapView(kgId, selectedKgAuthorId); 
  // new default map will be load, clear old session
  SetSessionProperty('SelectedKnowdeSiblingInfo', '');	
  SetSessionProperty('SplitView', 'false');
  	  
  var currentLocation = window.location.href;
  var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
	window.location = hostURL + _redirectUrl;
}

// Setting the session variables for MapView to load the correct map
function PrepareSessionForMapView(kgId, selectedKgAuthorId)
{ 
  //debugger;
  // merge as one server call
  var keys = 'SelectedPersonalKGID|MapViewDisplayMode|KGTabbedWindowsControl1_SelectedTab|SelectedAuthorID|KGButtonToolbar_AuthorID|IndexedDocListMode|KGMapViewCollapsed|KGExpandMap|TriggerMapViewCallbackOnload';
	var values = kgId + '|KGMapView|Indexed Documents|' + selectedKgAuthorId + '|' + selectedKgAuthorId + '|IndexedDocuments|false|true|true';
  SetSessionProperty(keys, values, true);
	/*SetSessionProperty('SelectedPersonalKGID', kgId);
  SetSessionProperty('MapViewDisplayMode', "KGMapView");
  SetSessionProperty('KGTabbedWindowsControl1_SelectedTab', 'Indexed Documents');
  SetSessionProperty('SelectedAuthorID', selectedKgAuthorId);
  SetSessionProperty('KGButtonToolbar_AuthorID', selectedKgAuthorId);
  //global_TabbedWindowsControl_CurrentlySelectedTab = "Indexed Documents";
  SetSessionProperty('IndexedDocListMode', 'IndexedDocuments');
  SetSessionProperty('KGMapViewCollapsed',false);
  SetSessionProperty('KGExpandMap',true); //flip the splitter to show the map in button toolbar callback done (KGMapViewCollapsed is removed in aspx.cs)
  SetSessionProperty('TriggerMapViewCallbackOnload', "true");*/
}

function KGUserObjectSummaryControl_DetailsButtonClicked(kgId, _controlDivClientID)
{
  // cancels KGRename
  KGUserObjectSummaryControl_CancelKGRename(CurrentlyRenamingKGID, _controlDivClientID);
  
  KGDetailsControl_CallbackTrigger(kgId);
}

var CurrentlyRenamingKGID = null;

// Show the input field
function KGUserObjectSummaryControl_StartKGRename(_kgId, _controlDivClientID)
{
  KGUserObjectSummaryControl_CancelKGRename(CurrentlyRenamingKGID, _controlDivClientID);
  var KGName = document.getElementById("KGName" + _kgId);
  var TextBox = document.getElementById("KGNameTextBox" + _kgId);
  var editBtn = document.getElementById("KGNameEditButton" + _kgId);
  var confirmEditBtn = document.getElementById("KGNameConfirmEditButton" + _kgId);
  
  if (KGName != null && TextBox != null && editBtn != null && confirmEditBtn != null)
  {
    KGName.className = "KGUserObjectSummaryControl_Hidden";
    TextBox.className = "KGUserObjectSummaryControl_Shown KGUserObjectSummaryControl_KGNameTextBox";
    TextBox.value = GetInnerText(KGName);
    editBtn.className = "KGUserObjectSummaryControl_Hidden";
    confirmEditBtn.className = "KGUserObjectSummaryControl_Shown";
    TextBox.focus();
    TextBox.select();
  }
  CurrentlyRenamingKGID = _kgId;
}

// Cancel the Edit and hide the input field
function KGUserObjectSummaryControl_CancelKGRename(_kgId, _controlDivClientID)
{
  if (_kgId != null)
  {
    var KGName = document.getElementById("KGName" + _kgId);
    var TextBox = document.getElementById("KGNameTextBox" + _kgId);
    var editBtn = document.getElementById("KGNameEditButton" + _kgId);
    var confirmEditBtn = document.getElementById("KGNameConfirmEditButton" + _kgId);
    
    if (KGName != null && TextBox != null && editBtn != null && confirmEditBtn != null)
    {
      KGName.className = "KGUserObjectSummaryControl_Shown";
      TextBox.className = "KGUserObjectSummaryControl_Hidden";
      editBtn.className = "KGUserObjectSummaryControl_Shown";
      confirmEditBtn.className = "KGUserObjectSummaryControl_Hidden";
    }
    
    // set the focus to the control div
    var parentControlDiv = document.getElementById(_controlDivClientID);
    if (parentControlDiv != null)
      parentControlDiv.focus();
  }
  CurrentlyRenamingKGID = null;
  CloseUOSMessageBox();
}

// confirm the new KG name
function KGUserObjectSummaryControl_KGRenameRequestConfirmation(_kgId, _controlDivClientID, _isKeyPressEvent, e)
{
	KGUserObjectSummaryControl_CommitKGRename(_kgId);
}

// make the callback
function KGUserObjectSummaryControl_CommitKGRename(_kgId)
{
  var TextBox = document.getElementById("KGNameTextBox" + _kgId);
  if (TextBox != null)
  {
    var args = 'action=renameKG|kgId=' + _kgId + '|kgName='+ TextBox.value;
    Pfl_KGUserObjectSummaryControl_CallbackTrigger(args);
  }
}

// KGName input field onkeypress handler
function KGUserObjectSummaryControl_KGNameTextBoxKeyPress(_kgId, _controlDivClientID, e)
{
  CancelBubble(e);
  e = e || window.event;
  if(e && e.type == "keydown")
  {
    switch(e.keyCode)
    {
      case 13: // Enter Key
        e.returnValue = false;
        if (e.preventDefault) e.preventDefault();
        KGUserObjectSummaryControl_KGRenameRequestConfirmation(_kgId, _controlDivClientID, true, e);
        break;
      case 27: // Esc
        KGUserObjectSummaryControl_CancelKGRename(_kgId, _controlDivClientID);
        break;
    }
  }
}

// KGName input field onclick handler
function KGUserObjectSummaryControl_KGNameTextBoxClick(_kgId, e)
{
  // prevent the row onclick handler firing
  CancelBubble(e);
}

///////////////////////
// Ensures that the delete message box is on the page
function EnsureRenameKGMessage(_parentControlDivId, _kgName, _kgId)
{
  m_UosMessageBox = document.getElementById("RenameKGMessageBox");
  
  if(m_UosMessageBox == null)
  {
    m_UosMessageBox = document.createElement("div");
    m_UosMessageBox.setAttribute("id", "RenameKGMessageBox");
    m_UosMessageBox.style.display = "none";
    m_UosMessageBox.style.width = "400px"
    m_UosMessageBox.style.height = "130px";
    m_UosMessageBox.style.position = "absolute";
    m_UosMessageBox.style.zIndex = TopZIndex();
    
    document.body.appendChild(m_UosMessageBox);
  }
  else
  {
    m_UosMessageBox.style.zIndex = TopZIndex(); //Show on top of other items
  }
  // whether the message box exists or not, the innerHTML needs to be set otherwise the displayed KGname may be incorrect
  if (_kgName == null || _kgName == "")
    m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Rename Knowledge Gene</td></tr><tr><td rowspan='2' valign='top'><img src='images/KGLogo.png' height='50' width='50'/></td><td>Please enter a new name for the Knowledge Gene<sup>&#174;</sup></td></tr><tr><td align='right'><button type='button' onclick='CloseUOSMessageBox();KGUserObjectSummaryControl_StartKGRename(" + _kgId + ", \"" + _parentControlDivId + "\")'>OK</button><button id = defaultButton type='button' onclick='KGUserObjectSummaryControl_CancelKGRename(" + CurrentlyRenamingKGID + ", \"" + _parentControlDivId + "\");'>Cancel</button></td></tr></table></div>";
  else
    m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>Rename Knowledge Gene</td></tr><tr><td rowspan='2' valign='top'><img src='images/KGLogo.png' height='50' width='50'/></td><td>Are you sure you want to rename this Knowledge Gene<sup>&#174;</sup> to \"" + _kgName + "\"</td></tr><tr><td align='right'><button type='button' onclick='KGUserObjectSummaryControl_CommitKGRename(" + _kgId + ")'>Yes</button><button id = defaultButton type='button' onclick='KGUserObjectSummaryControl_CancelKGRename(" + CurrentlyRenamingKGID + ", \"" + _parentControlDivId + "\");'>Cancel</button></td></tr></table></div>";
}

/* New version KG stuff */
function EnsureNewVersionKGMessage(_userId, _kgId, _newPublishedKGId, e)
{
  m_UosMessageBox = document.getElementById("DeleteKGMessageBox");
  
  if(m_UosMessageBox == null)
  {
    m_UosMessageBox = document.createElement("div");
    m_UosMessageBox.setAttribute("id", "DeleteKGMessageBox");
    m_UosMessageBox.style.display = "none";
    m_UosMessageBox.style.width = "500px"
    m_UosMessageBox.style.height = "260px";
    m_UosMessageBox.style.position = "absolute";
    
    document.body.appendChild(m_UosMessageBox);
  }
  
  m_UosMessageBox.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td class='NewVersionMsgBoxHeader'>New Version Available</td></tr><tr><td class='NewVersionKGText'>The Author has published a new version of this Knowledge Gene. Please be aware that the Author may have deleted (or changed the context of) Knowdes to which you have added your own content. If so, unavoidably this content would be lost. BUT you do not have to adopt the new Knowledge Gene, the current version will always remain available to you unless you yourself delete it from your library.<br/><br/>However, your own content will be carried over in all other circumstances so you may wish adopt the new version.  Both versions remain available to you so we recommend you explore the new version and make your decision at leisure.</td></tr><tr><td align='right'><span class='NewVersionKGTextLink' onclick='javascript:KGNewVersionClick(" + _userId + "," + _kgId + "," + _newPublishedKGId + ")'>Show new version</span>&nbsp;&nbsp;<span id = defaultButton class='NewVersionKGTextLink' onclick='javascript:CloseUOSMessageBox()'>Cancel</span></td></tr></table></div>";
  m_UosMessageBox.style.zIndex = TopZIndex();;
  
  PositionUosMessageBox("SiteOverlays_LoginView1_KGPublishOptionControl1_KGPublishOptionTable", false, e);
}

function KGNewVersionClick(_userId, _kgId, _newPublishedKGId)
{
  CloseUOSMessageBox();
  
  KGTabbedWindowsControl_MyHK_KGSelected(null, _userId, _newPublishedKGId, false, 0);
}



// JScript File
// For KGUserProfileControl 

function KGUserProfileControl_ChangePersonalDetailsClick()
{
  // debugger;
  var args = 'action=ChangeDisplayMode|mode=Update';
  KGUserProfileControl_CallbackTrigger(args);
}

function KGUserProfileControl_UpdateClick(_btn)
{
  var hiddenFieldId = _btn.getAttribute("HiddenFieldId");
  var hiddenField = document.getElementById(hiddenFieldId);
  var inputControlIds = eval( '(' + hiddenField.value + ')' );
  
  var args = 'action=Update';
  args += '|FirstName=' + ReadTextBoxValue(inputControlIds.txtFirstName);
  args += '|LastName=' + ReadTextBoxValue(inputControlIds.txtLastName);
  args += '|Email=' + ReadTextBoxValue(inputControlIds.txtEmail);
  args += '|SecurityQuestionIdx=' + ReadDropListIdx(inputControlIds.dropListSecurityQuestions);
  args += '|SecurityAnswer=' + ReadTextBoxValue(inputControlIds.txtSecurityAnswer);
  args += '|GenderIdx=' + ReadDropListIdx(inputControlIds.dropListGender);
  args += '|DOBYearIdx=' + ReadDropListIdx(inputControlIds.dropListDOBYear);
  args += '|DOBMonthIdx=' + ReadDropListIdx(inputControlIds.dropListDOBMonth);
  args += '|DOBDayIdx=' + ReadDropListIdx(inputControlIds.dropListDOBDay);
  args += '|Address1=' + ReadTextBoxValue(inputControlIds.txtAddress1);
  args += '|Address2=' + ReadTextBoxValue(inputControlIds.txtAddress2);
  args += '|City=' + ReadTextBoxValue(inputControlIds.txtCity);
  args += '|ZIPCode=' + ReadTextBoxValue(inputControlIds.txtZIPCode);
  args += '|CountryIdx=' + ReadDropListIdx(inputControlIds.dropListCountry);
  
  
  KGUserProfileControl_CallbackTrigger(args);
}

function ReadTextBoxValue(_textBoxId)
{
  // don't throw anything if the control doesn't exist, it might not have been added
  var value;
  if (_textBoxId)
  {
    var tb = document.getElementById(_textBoxId);
    if (tb)
      value = tb.value;
  }
  return value;
}

function ReadDropListIdx(_dropListId)
{
  // don't throw anything if the control doesn't exist, it might not have been added
  var idx;
  if (_dropListId)
  {
    var ddl = document.getElementById(_dropListId);
    if (ddl)
      idx = ddl.selectedIndex;
  }
  return idx;
}

function KGUserProfileControl_CancelUpdateClick()
{
  // debugger;
  var args = 'action=ChangeDisplayMode|mode=Display';
  KGUserProfileControl_CallbackTrigger(args);
}

function KGUserProfileControl_CallbackDone_Wrapped(controlDivID, args, context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  var container = document.getElementById(controlDivID);
  
  if(container != null)
  {
    container.innerHTML = args;
    if (args.indexOf("Exception") != 0 && args.indexOf("timmedout") != 0) // no exception
    {
      // refresh the profile header on the user's own profile page incase the details changed
      if (window.Pfl_KGProfileHeaderControl_CallbackTrigger)
        setTimeout("Pfl_KGProfileHeaderControl_CallbackTrigger('action=repopulate')", 10);
    }
  }
  else
    KGUserProfileControl_CallbackError('Can not find UserProfileForm element.');    
}

function KGUserProfileControl_CallbackError_Wrapped(controlDivID, args, context)
{
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    var controlDiv = document.getElementById(controlDivID);
          
    if(controlDiv != null)
      controlDiv.innerHTML = args;
    else
      alert('Callback on KGUserProfileControl has failed: ' + args);
  }
}

/* My Preferences */

function KGMyPrefsControl_CheckBoxClicked(_cb, _preferenceID)
{
  var args = 'id=' + _cb.id + '|prefid=' + _preferenceID;
  if(_cb.checked)
  {
    args += '|enabled=1';
  }
  else
  {
    args += '|enabled=0';
  }
  
  KGMyPrefsControl_CallbackTrigger(args);
  
  _cb.disabled = true;
}

function KGMyPrefsControl_ProcessCallBackError(_args, _context)
{
  var error = 'Error in KGMyPreferencesControl callback.';
  if(_args.length > 0)
    error += ' ' + _args;
  alert(error);
}

function KGMyPrefsControl_CallbackTrigger_Wrapped(_args, _callbackScript)
{
  var args;

  // Construct the callback arguments
  if(_args != null)
  { 
    args = _args;
    
    if(args.length > 0)
    {
      // trigger the callback
      eval(_callbackScript);
    }
  }
}

function KGMyPrefsControl_CallbackDone(args, context)
{  
  if(args.indexOf('Exception') == 0)
    alert(args);
  else
  {
    var results = args.split('|');
    if(results.length > 2)
    {
      var id = results[0];
      var prefid = results[1];
      var value = results[2];
      
      // search for the control container
      var holder = document.getElementById(id);
      
      if(holder != null && holder.parentNode != null)
      {
        var holderCell= holder.parentNode;
        
        // show check box and hide loading div
        holder.disabled = false;
        
      }//end if(holder ....
      else
      {
        KGMyPrefsControl_ProcessCallBackError('Checkbox bolder not found.', '');
      }
    }
  }
}

// JScript File
var m_contextString;
var m_dblClick = new Boolean(false);

function KGGoGlobalControl_CallbackTrigger_Wrapped(_cbreference, _treeID)
{
//debugger;
	if(m_contextString == "" || m_contextString == null)
		GrabHighlightedContext(_treeID);
	var args = 'Action=' + m_contextString + '|ConceptID=' + _treeID.SelectedNode.Value;
	m_contextString = "";
	eval(_cbreference);
}

function GrabHighlightedContext(_treeID)
{
	m_contextString = "";
  var aTreeView = null;
  var aTreeNode = null;
  var nodeId = _treeID.SelectedNode.ID;
  var treeId = _treeID.TreeViewID;
  
  if(treeId != null && treeId !='' && treeId != '-1' && eval('window.'+ treeId+'!=null'))
    aTreeNode = eval(treeId + '.FindNodeById(\'' + nodeId + '\')');

  if(aTreeNode != null)
  { 
    aTreeView = aTreeNode.ParentTreeView;
    
    if(aTreeNode.ID != null && aTreeNode.ID != '')
      conceptTreeControl_preTreeNodeID = aTreeNode.ID;
    
    if(aTreeView != null && aTreeView.TreeViewID != '')
      conceptTreeControl_preTreeViewID = aTreeView.TreeViewID;
  }

  while(aTreeNode != null)
  {
    aTreeNode.SaveState();
    m_contextString = aTreeNode.Text + " " + m_contextString;
    aTreeNode = aTreeNode.ParentNode;
  }
    
} // end function

function KGGoGlobalControl_CallbackDone_Wrapped(args, context, tableID)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
	var domainTableId = tableID + "_GoGlobalTable";
  m_DomainTable = document.getElementById(domainTableId);
  if(m_DomainTable == null)
		m_DomainTable = document.getElementById("GoGlobalTable");
  SetOuterHtml(m_DomainTable,args);
  ShowKGGoGlobalControl();
}

function KGGoGlobalControl_ProcessCallBackError_Wrapped(args, context)
{
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
  	document.getElementById(_thisClientID).innerHTML = '<tr><td>An error has occurred in RegisterJavaScript() of KGSuggestionControl.</td></tr>';
  }
}
function KGTopicsControl_OnNodeSelect(_nodeText, _nodeId, _topLevelTopicId, _hasChildren)
{
 //debugger;
  try
  {
    SetSessionProperty('Topics_SelectedTopicName', _nodeText.replace('&','%26'));
    var keys = 'Topics_SelectedTopicGroupId|ConceptTabbedView_SelectedTab|IndexedDocListMode|Topics_CategoryJustClicked|SelectedKnowdeSiblingInfo';
	  var values = _nodeId + '|CS_' + _topLevelTopicId + '|Category|true|';
    SetSessionProperty(keys, values, true);

    /*SetSessionProperty('Topics_SelectedTopicGroupId', _nodeId);
    SetSessionProperty('ConceptTabbedView_SelectedTab', 'CS_' + _topLevelTopicId);
    SetSessionProperty('IndexedDocListMode', 'Category');
    SetSessionProperty('Topics_CategoryJustClicked', true);
    
    // new default map will be load, clear old session
    SetSessionProperty('SelectedKnowdeSiblingInfo', '');	*/
    
    // reload the concept tree
    if (_hasChildren.toLowerCase() == "false") // only the lowest level categories have semantic trees
    {
      if (window.KGNavigationControl_SwitchTabs)
      {
        KGNavigationControl_SwitchTabs('CS_' + _topLevelTopicId, _nodeText);
        if(_topLevelTopicId > 0)
        {
          if (window.KGNavigationControl_ShowHideSemanticTreeCheckBox)
            KGNavigationControl_ShowHideSemanticTreeCheckBox(1);
        }
        KGNavigationControl_TreeNavBarRePopulate();
      }
    }
    
    // reload the home content control if we're on the home page, otherwise redirect to home page
    var currentLocation = window.location.href;
    var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
    if (currentPage.indexOf('home') > -1 || currentPage.length == 0)
    {
        // select the Indexed Docs tab
      globalIndexedDocsPageLoaded = false;
      //KGTabbedWindowsControl_SelectTabById('Indexed Documents');
      
      // let the map view reload when it is viewed
      globalMapViewControlLoaded = false;

      SetSessionProperty('KGMapViewCollapsed',false);
      var mapViewCollapsed = PaneBStatus();
      if (mapViewCollapsed == false) // map view is visible, reload it
        MapViewControl1_CallbackTrigger();
      else // map view is not visible - open the splitter
      {
        //globalMapViewControlLoaded = false;
        DoExpandMapViewPane();
      }
    }
    else if(currentPage.indexOf('configurecommunityspace') > -1 || currentPage.length == 0)
    {
      var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
      window.location = hostURL + 'configurecommunityspace.aspx';
    }
    else
    {
      var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
      window.location = hostURL + 'home.aspx';
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }

}


// Handle tree node expand or collapsed 
function TopicsControl_SetTreeNodeStatus(_node, _hiddenFieldClientID, _sessionNameForExpandedNodes, _scrollFunctionName, _srmIndex) 
{
  if(_node != null)
  {
    var seperator = '@';
    var nodeID = _node.ID;
    var box = document.getElementById(_hiddenFieldClientID);
    if(box != null)
    {
      var nodesstatus = box.value;
      if(_node.Expanded)
      {
        // then this node will be collapsed
        box.value = nodesstatus.replace(nodeID+seperator,'');
      }
      else
      {
        // will be expanded
        if(nodesstatus.indexOf(nodeID) < 0)
        {
          // not recorded yet
          box.value = nodesstatus + nodeID + seperator;
        } //end index if
      } //end expanded if
      SetSessionProperty(_sessionNameForExpandedNodes, box.value);
    }
    else
    {
        alert('Topic tree hidden field not found.');
    } //end box null if
  } //end node null if
  
  return true; 
}// end function




function KGTopicsControl_ProcessCallBackError_Wrapped(_args, _context, _topicsControlClientID)
{
  //debugger;
  try
  {
    var holder = document.getElementById(_topicsControlClientID);
    if (holder != null)
        holder.innerHTML = 'Exception occurred.';
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}


function Topics_Repopulation(_args, _context)
{
  //debugger;
  try
  {
    var repop = _args.split('[@|@]');
    var repopulateStatus = repop[0].split('=');
    if(repopulateStatus[1] == 'true')
    {
      _args = repop[1];
      var holderId = _args.substring(0, _args.indexOf('='));
      var holder = document.getElementById(holderId);
      if(holder != null)
        holder.innerHTML = _args.substring(_args.indexOf('=')+1);
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function TopicsControl_RepopulateCallbackDone()
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
}


function KGTopicsControl_CallBackDone()
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
}


// temp fix for ConceptTabbedView - so don't show back button for categories tab
function KGTopicsControl_isTopicSelected()
{
  return false;
}
// KGToolbar JScript File
var globalHelpID;
var KGButtonToolbar_SearchResultBackButtonClick = false;
var KGButtonToolbar_CurrentOwnerKey = -1;
var m_splitCookieExpiration = 8760; // cookie expiration date in hours from current time. 8760 = 1 year
var globalRetToMapView = "false"; // for knowing whether to show map full-screen after changing splitter mode
var m_buttonToolbar_knowdeShortcutSelect; // the knowde shortcut drop down list object
var m_buttonToolbar_docVersionSelect; //the document version drop down list object
var KGButtonToolbar_previousHistoryItem;
var KGButtonToolbar_currentHistoryItem;
var LoadMapView_isBackButtonClick = false;
var globalAuthorOfCurrentKG = -1;
var waitForLoadMapCallback = true;
var globalUserKGPermission = false;
var m_KGDocVersionArray; // stores the document versions for the current KG
var m_KnowdeDocVersionArray; // stores any document versions for the current KGs knowdes
var globalCatClick = new Boolean(false);
var m_readyForResize = false;

var m_kgInMyHK = 0;

// callback done
function KGButtonToolbar_CallbackDone(_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 + ')');
    
  KGButtonToolbar_previousHistoryItem = retMessage.PreviousHistoryItem;
  KGButtonToolbar_currentHistoryItem = retMessage.CurrentHistoryItem;

  // initialise the back button click global variable
  KGButtonToolbar_SearchResultBackButtonClick = false;
  
  // set help ID
  globalHelpID = retMessage.HelpID;
    
  if(retMessage.KnowdePermission == true || retMessage.KnowdePermission == "True" || retMessage.KnowdePermission == "true")
  {
		globalUserKGPermission = true;
  }
  else
  {
		globalUserKGPermission = false;
  }
  
  if (retMessage.Action == 'DocumentHistoryBack')
  {
    if (retMessage.CloseDocumentTab == "True")
      SetSessionProperty('KGParsingDocument', '-1');
    if(globalSplitterSetting == "split")
    {
			ShowSplitterArrowDown();
		}
  }
  else if (retMessage.Action == 'AuthorSelected' || retMessage.Action == 'DocumentSelected')
  {
    // ensure mapview pane is collapsed
		var paneTop = document.getElementById("Splitter1_pane_0");
		if(paneTop.clientHeight > 0)
			DoCollapseMapViewPane();
  }
  else if(retMessage.Action == 'subscribeMyHKClicked')
  {
    CloseMyKnowledgeMessageBox();
    // update "My Knowledge Genes" in the profile tab
    if (window.Pfl_KGMyKnowledgeControl_CallbackTrigger) // check incase the profile tab hasn't been loaded
      setTimeout("Pfl_KGMyKnowledgeControl_CallbackTrigger('Action=repopulate')", 10);
    // reload the communityTab
    if (window.LoadCommunityTab)
      window.setTimeout('LoadCommunityTab("ListView")', 1);

  }
  else if (retMessage.Action == 'LoadMapView')
  {
    //document.getElementById('CategoriesTreeCheckbox').parentNode.style.display = 'none';
    // rest the delay variable
    waitForLoadMapCallback = null;
  }
  else if (retMessage.Action == 'DocList')
  {
    //document.getElementById('CategoriesTreeCheckbox').parentNode.style.display = 'block';
  }
  if(retMessage.SplitView.toString() == "True")
  {
		SwitchToSplitView('skip');
  }
  else
  {
		SwitchToFullView('skip', retMessage.ExpandMap);
  }
  
  // setup the KnowdeShortcuts list if necessary
  if ( retMessage.KnowdeShortcuts != null )
  {
    if ( m_buttonToolbar_knowdeShortcutSelect == null )
      m_buttonToolbar_knowdeShortcutSelect = new KGButtonToolbar_KnowdeShortcutSelect();
    
    if (m_buttonToolbar_knowdeShortcutSelect.KGID != retMessage.CurrentHistoryItem.KGID
    || retMessage.Action == "KnowdeShortcutAdded" )
    {
      m_buttonToolbar_knowdeShortcutSelect.Populate(retMessage.KnowdeShortcuts);
      m_buttonToolbar_knowdeShortcutSelect.KGID = retMessage.CurrentHistoryItem.KGID;
    }
  }    
  
  // hide/display the relevant buttons
  KGButtonToolbar_UpdateToolbar(retMessage)
  
  if (retMessage.Action == 'StartTextViewEditing')
  {
    // ensure the edit toolbar is in text view mode
    // KGButtonToolbar_ChangeEditbarMode('TextView');
  }
  
  //Adjust Splitter Height if panes exist
  /*if (window.Splitter1 && window.Splitter1.Panes)
  {
		resetHeights();
		setPaneSize();
  }*/
  
  // do we need to initialise the document version drop down list object?
  if (m_buttonToolbar_docVersionSelect == null)
    m_buttonToolbar_docVersionSelect = new KGButtonToolbar_DocVersionSelect();
  
  if (m_buttonToolbar_docVersionSelect.KGID != retMessage.CurrentHistoryItem.KGID)
  {
    m_KGDocVersionArray = retMessage.KGDocumentVersions;
    m_KnowdeDocVersionArray = retMessage.KnowdeDocumentVersions;
    m_buttonToolbar_docVersionSelect.Populate(m_KGDocVersionArray);
    m_buttonToolbar_docVersionSelect.MarkEditedVersions(m_KnowdeDocVersionArray);
    m_buttonToolbar_docVersionSelect.KGID = retMessage.CurrentHistoryItem.KGID;
  }
}

function KGButtonToolbar_GetDocVersionSelect_Wrapped(_id)
{
  return document.getElementById(_id);
}



// DocVersionSelect class
function KGButtonToolbar_DocVersionSelect()
{
  this.select = KGButtonToolbar_GetDocVersionSelect();
  this.newOption;
  this.deleteOption;
  this.KGID;
  
  this.Initialise = function()
  {
  //debugger;
    // 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)
  {
    var optionid = this.CreateOptionId(_value);
    var option = document.getElementById(optionid);
    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))
      this.AddOption("Default Text Version", "default");
    
    // create new Text Version
    if(Map_TextEditOnly == 0)
    { // text edit only permission won't be able to create text version
      this.newOption = this.AddOption("Create New Text Version", "new");
    }
    
    // do we need to initialise the newTextVersionControl overlay object?
    if (m_newTextVersionControl == null)
      m_newTextVersionControl = new KGNewTextVersionControl();
    
    if (_docVersions != null)
    {
      // If there are some non default text versions, add an options to delete
      if (_docVersions.length > 0 && Map_TextEditOnly == 0)
      {// text edit only permission won't be able to delete text version
        this.AddDeleteOption()
      }
      
     var defaultSelectedValue = 'default';
      var containsCurrentSelection = 0;
      // loop through _docVersions array
      for (var arrayIndex=0; arrayIndex < _docVersions.length; arrayIndex++)
      {
        if(arrayIndex == 0 && (m_bEditable && Map_TextEditOnly == 1)) // no default available
           defaultSelectedValue = _docVersions[arrayIndex].verID; //this.CreateOptionId(_value);
        this.AddOption(_docVersions[arrayIndex].name, _docVersions[arrayIndex].verID, this.newOption);
        
        if(m_textViewDocVersion != null && _docVersions[arrayIndex].verID == m_textViewDocVersion)
          containsCurrentSelection = 1;
      }
      
      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;
      }    
    }
  };
  
  this.AddDeleteOption = function()
  {
    this.deleteOption = this.AddOption("Delete Text Version(s)", "delete");
    if (m_deleteTextVersionControl == null)
      m_deleteTextVersionControl = new KGDeleteTextVersionControl();
  };
  
  // 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;
        DisplayTextViewInTab("KnowdeSelected-ReloadTextView");
        break;
      default: // for all other selectedValues
        m_textViewDocVersion = selectedValue;
        DisplayTextViewInTab("KnowdeSelected-ReloadTextView");
    }
  };
  
  // adds asterisk to any options in _knowdeDocList for currently selected knowde
  this.MarkEditedVersions = function(_knowdeDocList)
  {
    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 = "ButtonToolbar_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 box

}


function KGButtonToolbar_GetKnowdeShortcutSelect_Wrapped(_id)
{
  return document.getElementById(_id);
}

// DocVersionSelect class
function KGButtonToolbar_KnowdeShortcutSelect()
{
  this.select = KGButtonToolbar_GetKnowdeShortcutSelect();
  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)
  {
    // create a new option object
    var shortcut = document.createElement('option');
    shortcut.text = _text;
    shortcut.value = _value;
    shortcut.id = this.CreateOptionId(_value);
    // add to the droplist
    
    try
    {
      this.select.add(shortcut, null); // standards compliant
    }
    catch(ex)
    {
      this.select.add(shortcut); // IE only
    }
 
    
    return shortcut;
  };
  
  // adds each entry in the _shortcuts array to the droplist
  this.Populate = function(_shortcuts)
  {
    // clear the drop list
    this.Initialise();
    
    // default text version
    this.AddOption("Original Entry Knowde", "default");
    
   
    if (_shortcuts != null)
    {
      // loop through _shortcuts array
      for (var shortcutIndex =0; shortcutIndex < _shortcuts.length; shortcutIndex++)
      {
        this.AddOption(_shortcuts[shortcutIndex].text, _shortcuts[shortcutIndex].knowdeID);
      }
    }
  };
 
  // select onchange event handler
  this.Changed = function(e)
  {
    var selectedValue = this.select.value;
    switch(selectedValue)
    {

      case "default":
        // reset the mapview by just saying we've selected a KG
        SetSessionProperty('DealWithMyHK_KGSelected', Active_KGID);
        SetSessionProperty('MapViewDisplayMode', 'KGMapView');
        MapViewControl1_CallbackTrigger();
        //KGTabbedWindowsControl_CallbackTrigger('KnowdeSelected');        
        break;
      default: // for all other selectedValues
        // Set the session and refresh in KGServer
        SetSessionProperty('SelectedKGID', selectedValue);
        SetSessionProperty('MapViewDisplayMode', 'KGMapView');
        MapViewControl1_CallbackTrigger();
        //KGTabbedWindowsControl_CallbackTrigger('KnowdeSelected');        
        break;
    }
  };
 
  
  return true;
}

function KnowdeShortcutSelectionChanged(_e)
{
  //debugger;
  var i = 0;

}


// shows and hides the buttons based on the JSON retMessage values
function KGButtonToolbar_UpdateToolbar_Wrapped(_retMessage, _addToMyHKBtnID, _removeFromMyHKBtnID, _editingBtnID, _removeKnowdeShortcutBtnID, _knowdePermBtnID)
{
  var addToMyHKBtn = document.getElementById(_addToMyHKBtnID);
  var removeFromMyHKBtn = document.getElementById(_removeFromMyHKBtnID);
  var startEditingBtn = document.getElementById(_editingBtnID);
  var knowdePermBtn = document.getElementById(_knowdePermBtnID);
  
  globalAuthorOfCurrentKG = KGButtonToolbar_currentHistoryItem.AuthorPersonID;
   
  var hideButtons = _retMessage.HideButtons
  var displayButtons = _retMessage.DisplayButtons
  
  // do we need to show the removeKnowdeShortcut or not?  it depends on what is selected...
  // only show it if we've currently got a shortcut selected
  if ( !m_buttonToolbar_knowdeShortcutSelect || ( m_buttonToolbar_knowdeShortcutSelect && m_buttonToolbar_knowdeShortcutSelect.select.value == "default" ) )
  {
    // don't show it
    hideButtons[hideButtons.length-1] = _removeKnowdeShortcutBtnID;    
  }
  else
  {
    // show it  
    displayButtons[displayButtons.length-1] = _removeKnowdeShortcutBtnID;    
  }
  
  for (var buttonID=0; buttonID < hideButtons.length; buttonID++)
  {
    var button = document.getElementById(hideButtons[buttonID]);
    if (button)
    {
      button.style.display = 'none';//.className = 'ButtonToolbar_Hidden';
    }
  }
  
  var checkbox = document.getElementById("CategoriesTreeCheckbox");
  var button = document.getElementById("KGButtonToolbar_KeyConceptBtn");
  if (checkbox != null && checkbox.checked)
  {
		if(button)
			button.style.display = 'inline';//.className = 'ButtonToolbar_Shown';
	}
	else
	{
		if(button)
			button.style.display = 'none';//.className = 'ButtonToolbar_Hidden';
	}
	
	
  for (var buttonID=0; buttonID < displayButtons.length; buttonID++)
  {
    var button = document.getElementById(displayButtons[buttonID]);
    if (button)
    {
      button.style.display = 'inline';//.className = 'ButtonToolbar_Shown';
      
    }
  }
  
  // whether we can show the startEditing button 
  // e.g. if you close the splitter and hide the button, then reopen the splitter
  //   - need to know whether the user is allowed to see the button
  if (startEditingBtn.style.display != 'none')
    startEditingBtn.isOkToShow = true;
  else
    startEditingBtn.isOkToShow = false;
    
    
  if (_retMessage.CurrentHistoryItem.KGID != "")
  {
    addToMyHKBtn.onclick = function(e){KGButtonToolbar_MyHKBtnOnClick('KnowledgeGene', _retMessage.CurrentHistoryItem.KGID, true, e)};
    removeFromMyHKBtn.onclick = function(e){KGButtonToolbar_MyHKBtnOnClick('KnowledgeGene', _retMessage.CurrentHistoryItem.KGID, false, e)};
    
    if(removeFromMyHKBtn.style.display != 'none')
    {
      m_kgInMyHK = 1;
    }
    else if(addToMyHKBtn.style.display != 'none')
    {
      m_kgInMyHK = 0;
    }
  }
  UpdateAddMyOwnWhatTooltip();
	
  // hide any buttons that shouldn't be showing when the map's closed
  var mapViewCollapsed = PaneBStatus(); 
  if (mapViewCollapsed) // necessary incase the map was closed
    KGButtonToolbar_hideOrShowMapButtons(false);
      
  // show the preview full textview button if in edit mode and the popup help is not already open
  var helpBox = document.getElementById("KGHelpControlID1");
  if(m_bEditable == true && (helpBox != null && helpBox.className != "OverlayPosition"))
  {
    KGTextTabControl_HideOrShowPreviewFullTVButton(true);
  }else
    KGTextTabControl_HideOrShowPreviewFullTVButton(false);
  
    
  KGButtonToolbar_hideOrShowButtonDivider(); // this needs to go after updating the other buttons
  
}

function KGButtonToolbar_hideOrShowButton(_buttonID, _show)
{
  //if(_buttonID.indexOf('KnowdePerm') != -1)
    //debugger;
    
  var btn = document.getElementById(_buttonID);
  if(btn != null)
  {
    if(_show)
    {
      btn.style.display = 'inline';
    }
    else
    {
      btn.style.display = 'none';
    }
  }
}

function KGButtonToolbar_clearMapViewButtons()
{
  KGButtonToolbar_hideOrShowMapButtons();
}

// similar docs button click handler
function KGButtonToolbar_similarDocsBtnOnClick(_forDefaultKnowde)
{
  var args = 'Action=similarDocsClicked';
  if(m_bEditable == true || (_forDefaultKnowde != null && _forDefaultKnowde == true))
    args += '|ForDefaultKnowde=true';
  KGButtonToolbar_CallbackTrigger(args);
}

// _subscribe = true to add, false to remove
// _objectType = KnowledgeGene or IndexedDoc
// _objectId = KGID or DocumentID
function KGButtonToolbar_MyHKBtnOnClick(_objectType, _objectId, _subscribe, e)
{ 
  if (_subscribe == false)
  {
    var toolbarId = KGButtonToolbar_getToolbarId();
    KGMyKnowledgeControl_DislayRemoveKGMessage(toolbarId, e);
  }
  
  // Test if the current user has logged in 
  // YES: allow the operation to go ahead
  //  NO: Redirect User to the new sign in / sign up page
  if(isAuthenticated())
  {
    var args = 'Action=subscribeMyHKClicked|ObjectType=' + _objectType + '|ObjectId=' + _objectId + '|Subscribe=' + _subscribe;
    KGButtonToolbar_CallbackTrigger(args);
  }
  else
  {
    redirectToSignInSignUpPage('AddToMyHK', _objectId);  
  }
}

// any author click except for back
function KGButtonToolbar_AuthorSelected(_authorPersonId)
{
  //trigger callback on ButtonToolbar
  var args = "Action=AuthorSelected|AuthorPersonID=" + _authorPersonId;
  KGButtonToolbar_CallbackTrigger(args);
}

// load map view
function KGButtonToolbar_loadMapView()
{
  ProceedWithTour();
  if(LoadMapView_isBackButtonClick)
  {
    LoadMapView_isBackButtonClick = false;
  }
  else
  {
    var args = "Action=LoadMapView"
    args += "|KGID=" + Active_KGID;
    if (m_bEditable == true)
      args += "|MapEditing=true";
    
    KGButtonToolbar_CallbackTrigger(args);
  }
}

function KGButtonToolbar_DocumentSelected()
{
  var args = "Action=DocumentSelected";
  KGButtonToolbar_CallbackTrigger(args);
}

//doc list loaded
function KGButtonToolbar_IndexedDocListLoaded(_clearHistory)
{
  var args = "Action=DocList";
  if ( window.Active_KGID !== undefined )
  {
		if ( Active_KGID != "" )
		{
		 args += "|KGID=";
		 args += Active_KGID;
		}
  }
  if (_clearHistory == true)
    args += "|ClearHistory=true"
  KGButtonToolbar_CallbackTrigger(args);
}

// view application button click handler
function KGButtonToolbar_AppSelected(_i)
{
  //KGTabbedWindowsControl_SelectTabById('AppTab' + _i)
  var args = "Action=AppSelected|AppID="+_i;
  KGButtonToolbar_CallbackTrigger(args);
}

//////////
// handle toolbar when when map editing starts
function KGButtonToolbar_StartEditing()
{
  if (waitForLoadMapCallback)
  {
    // if LoadMapCallback callback hasn't finished yet, delay this callback
    setTimeout("KGButtonToolbar_StartEditing()", 100);
  }
  else
  {
    // ensure the edit toolbar is in map view mode
      KGButtonToolbar_ChangeEditbarMode('MapView');

    // show the edit toolbar
    if(Map_TextEditOnly == 0)
      KGButtonToolbar_ShowHideEditBar(true);
    
    // show the docversion dropdown list
    if(Map_MultiVersionTextView == 1)
      m_buttonToolbar_docVersionSelect.Show();
    
    var args = "Action=StartEditing";
    KGButtonToolbar_CallbackTrigger(args);
    
    var skipSession = false;
    if(global_newKGCreatedSplitViewSet == true)
    {
      global_newKGCreatedSplitViewSet = false;
      skipSession = 'skipSetSession';
    }
   
    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)
    {
      KGButtonToolbar_hideOrShowChangeObjButton(true);
      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;
          KGButtonToolbar_switchConnTypeButton(m_arithmeticConnectorMode);
          KGButtonToolbar_hideOrShowConnTypeButton(true);
        }
      }
    }
  }
}

//////////
// handle toolbar when when map editing stops
function KGButtonToolbar_StopEditing()
{
	KGButtonToolbar_loadMapView();
  // hide the editing toolbar as long as textview is not in edit mode
  // now the edit mode apply to both mapview and text view
  //if (m_bTextViewWritable == false)
    KGButtonToolbar_ShowHideEditBar(false);
  
  // hide the docversion dropdown list
  m_buttonToolbar_docVersionSelect.Hide();
  
  var args = "Action=StopEditing|TextViewEditing=" + false;
  KGButtonToolbar_CallbackTrigger(args);
  
  // if the user was in full view before they started editing, put it back to full view
  //if (!WM_readCookie('SplitView'))
  //  SwitchToFullView();
}

//////////
// handle toolbar when when text editing starts
function KGButtonToolbar_StartTextViewEditing()
{
  // show the edit toolbar
  KGButtonToolbar_ShowHideEditBar(true);

  var args = "Action=StartTextViewEditing";
  KGButtonToolbar_CallbackTrigger(args);
}

//////////
// handle toolbar when when text editing stops
function KGButtonToolbar_StopTextViewEditing()
{
  // hide the editing toolbar as long as the mapview is not in edit mode
  if (m_bEditable == false)
    KGButtonToolbar_ShowHideEditBar(false);
  var args = "Action=StopTextViewEditing|MapEditing=" + m_bEditable;
  KGButtonToolbar_CallbackTrigger(args);
}

// callback trigger
function KGButtonToolbar_CallbackTrigger_Wrapped(args, _KGButtonToolbar_cbreference)
{
  if (m_bEditable == true)
    args += "|MapEditing=true";
  if (m_bTextViewWritable == true)
    args += "|TextViewEditing=true";
  var mapViewCollapsed = PaneBStatus();
  if (!mapViewCollapsed)
    args += "|ShowingMapPane=true";
  eval(_KGButtonToolbar_cbreference);
}

function KGButtonToolbar_ProcessCallBackError_Wrapped(_args, _context, _KGButtonToolbarClientID)
{
  var holder = document.getElementById(_KGButtonToolbarClientID);
  if (holder != null)
      holder.innerHTML = 'Exception occurred.';
}

function switchSubscribeButton_Wrapped(_subscribed, _addToMyHKBtnID, _removeFromMyHKBtnID)
{
  var addToMyHKBtn = document.getElementById(_addToMyHKBtnID);
  var removeFromMyHKBtn = document.getElementById(_removeFromMyHKBtnID);

  var mapViewCollapsed = PaneBStatus(); 
    
  if (_subscribed == true || _subscribed == "true") // just subscribed
  {
    if (mapViewCollapsed) // both buttons are hidden, but tell it to show the remove button when it next shows them
    {
      m_hiddenMyHkBtnID = _removeFromMyHKBtnID;
    }
    else // showing the map and the map buttons, so show the remove button now
    {
      addToMyHKBtn.style.display = 'none';
      removeFromMyHKBtn.style.display = 'inline';
    }
  }
  else // just unsubscribed
  {
    if (mapViewCollapsed)
    {
      m_hiddenMyHkBtnID = _addToMyHKBtnID;
    }
    else
    {
      addToMyHKBtn.style.display = 'inline';
      removeFromMyHKBtn.style.display = 'none';
    }
  }
}

// hide the IconButton
function KGButtonToolbar_hideIconButton_Wrapped(_viewIconsButtonID)
{
  var iconButton = document.getElementById(_viewIconsButtonID);
  if (iconButton)
    iconButton.style.display = 'none';//.className = "ButtonToolbar_Hidden";
}

// show the IconButton
function KGButtonToolbar_showIconButton_Wrapped(_viewIconsButtonID)
{
  var iconButton = document.getElementById(_viewIconsButtonID);
  if (iconButton)
    iconButton.style.display = 'inline';//.className = "ButtonToolbar_Shown";
}

function KGButtonToolbar_ShowHideEditBar_Wrapped(_show, _editingToolbarClientID)
{
  var editingToolbar = document.getElementById(_editingToolbarClientID);
  if (editingToolbar != null)
  {
    if (_show == true && editingToolbar.className == "ButtonToolbar_Hidden")
      editingToolbar.className = "ButtonToolbar_editingToolbar";
    else if (_show == false && editingToolbar.className == "ButtonToolbar_editingToolbar")
      editingToolbar.className = "ButtonToolbar_Hidden";      
  }
  Splitter1.adjustSize(true);
}

// Called when the mouse floats over a toolbar button, making it highlighted
// _button: the button floated over
function KGEditingToolbar_ButtonOver(_button)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    // add the "button over" css class
    if (_button.className.indexOf("EditingToolbar_ButtonOver") == -1)
      _button.className = _button.className + " EditingToolbar_ButtonOver";
  }
}

// Called when the mouse floats out of toolbar button, removing the highlight
// _button: the button floated over
function KGEditingToolbar_ButtonOut(_button)
{
  // remove the "button over" css class
  _button.className = _button.className.replace(/ EditingToolbar_ButtonOver/g, "");
}

function KGEditingToolbar_SelectButton(_button)
{
  // add the "button selected" css class
  if (_button.className.indexOf("EditingToolbar_Selected") == -1)
    _button.className = _button.className + " EditingToolbar_Selected";
}

function KGEditingToolbar_DeSelectButton(_button)
{
  // remove the "button selected" css class
  _button.className = _button.className.replace(/ EditingToolbar_Selected/g, "");
}

function KGEditingToolbar_ToggleSelection(_button)
{
  if (_button.className.indexOf("EditingToolbar_Selected") == -1)
    KGEditingToolbar_SelectButton(_button);
  else
    KGEditingToolbar_DeSelectButton(_button);
}

function KGButtonToolbar_GreyOutButton(_button)
{
  _button.className = "EditingToolbar_Greyed";
}

function KGButtonToolbar_UnGreyButton(_button)
{
  _button.className = "EditingToolbar_Button";
}

function KGEditingToolbar_StyleChange(_styleDropList, _mode, _namePrefix)
{
  if (_mode == "TextView")
  {
    TextViewStyleChanges(_styleDropList);
    // update the undoredo buttons
    eval(_namePrefix + '_UpdateUndoRedoBtns()');
  }
}

function KGEditingToolbar_Bold(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
    {
      TextViewBold();
      KGEditingToolbar_ToggleSelection(_button);
      // update the undoredo buttons
      eval(_namePrefix + '_UpdateUndoRedoBtns()');
    }
  }
}

function KGEditingToolbar_Italic(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
    {
      TextViewItalic();
      KGEditingToolbar_ToggleSelection(_button);
      // update the undoredo buttons
      eval(_namePrefix + '_UpdateUndoRedoBtns()');
    }
  }
}

function KGEditingToolbar_Underline(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
    {
      TextViewUnderline();
      KGEditingToolbar_ToggleSelection(_button);
      // update the undoredo buttons
      eval(_namePrefix + '_UpdateUndoRedoBtns()');
    }
  }
}

function KGEditingToolbar_DecIndent(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
    {
      TextViewDecIndent();
      // update the undoredo buttons
      eval(_namePrefix + '_UpdateUndoRedoBtns()');
    }
  }
}

function KGEditingToolbar_IncIndent(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
    {
      TextViewIncIndent();
      // update the undoredo buttons
      eval(_namePrefix + '_UpdateUndoRedoBtns()');
    }
  }
}

function KGEditingToolbar_Olist(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
    {
      TextViewOList();
      // update the undoredo buttons
      eval(_namePrefix + '_UpdateUndoRedoBtns()');
    }
  }
}

function KGEditingToolbar_Ulist(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
    {
      TextViewUList();
      // update the undoredo buttons
      eval(_namePrefix + '_UpdateUndoRedoBtns()');
    }
  }
}

function KGEditingToolbar_InsertImage(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
      TextViewInsertImage();
  }
}

function KGEditingToolbar_InsertFile(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
      TextViewInsertFile();
  }
}

function KGEditingToolbar_InsertLink(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
    {
      TextViewInsertLink();
      // update the undoredo buttons
      eval(_namePrefix + '_UpdateUndoRedoBtns()');
    }
  }
}

function KGEditingToolbar_Cut(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
    {
      if (TextViewCut())
      {
        // update the cut copy and paste buttons
        eval(_namePrefix + '_UpdateCutCopyPasteBtns()');
        // update the undoredo buttons
        eval(_namePrefix + '_UpdateUndoRedoBtns()');
      }
    }
    else if (_mode == "MapView")
    {
      CutKnowde();
    }
  }
}

function KGEditingToolbar_Copy(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
    {
      if (TextViewCopy())
      {
        // update the cut copy and paste buttons
        eval(_namePrefix + '_UpdateCutCopyPasteBtns()');
        // update the undoredo buttons
        eval(_namePrefix + '_UpdateUndoRedoBtns()');
      }
    }
    else if (_mode == "MapView")
    {
      CopyKnowde();
    }
  }
}

function KGEditingToolbar_Paste(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
    {
      if(TextViewPaste())
      {
        // update the cut copy and paste buttons
        eval(_namePrefix + '_UpdateCutCopyPasteBtns()');
        // update the undoredo buttons
        eval(_namePrefix + '_UpdateUndoRedoBtns()');
      }
    }
    else if (_mode == "MapView")
    {
      PasteKnowde();
    }
  }
}

function KGEditingToolbar_Move(_button)
{
	PasteOntoNewKnowdeFromEditMenu("toolbarButton", null, "Top")
}

function KGEditingToolbar_Delete(_button)
{
	DeleteCurrentKnowde();
}

function SetTitle(_element, _mode, _namePrefix)
{
  var isIE;
  if (navigator.appName == "Microsoft Internet Explorer")
    isIE = true;
  else
    isIE = false;
        
  if (!isIE && _mode == "TextView" && _element.title.indexOf("not permit") == -1)
  {
    if(_element.id.indexOf('_Copy') != -1) 
        _element.title = "This browser does not permit access to the clipboard.  Please use the browser menu or Ctrl+C for Copy.";
    else if(_element.id.indexOf('_Cut') != -1) 
        _element.title = "This browser does not permit access to the clipboard.  Please use the browser menu or Ctrl+X for Cut.";
    else if(_element.id.indexOf('_Paste') != -1) 
        _element.title = "This browser does not permit access to the clipboard.  Please use the browser menu or Ctrl+V for Paste.";
  }
  else if (_mode == "MapView" && _element.title.indexOf("not permit") != -1)
  {
    if(_element.id.indexOf('_Copy') != -1) 
        _element.title = "Copy";
    else if(_element.id.indexOf('_Cut') != -1) 
        _element.title = "Cut";
    else if(_element.id.indexOf('_Paste') != -1) 
        _element.title = "Paste";
  }
}
function KGEditingToolbar_Undo(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
    {
      // call the TextView function
      TextViewUndo();
      // update the undoredo buttons
      eval(_namePrefix + '_UpdateUndoRedoBtns()');
    }
    else if (_mode == "MapView")
    {
      Undo();
    }
  }
}

function KGEditingToolbar_Redo(_button, _mode, _namePrefix)
{
  // ensure the button is active
  if (_button.className.indexOf("EditingToolbar_Greyed") == -1)
  {
    if (_mode == "TextView")
    {
      // call the TextView function
      TextViewRedo();
      // update the undoredo buttons
      eval(_namePrefix + '_UpdateUndoRedoBtns()');
    }
    else if (_mode == "MapView")
    {
      Redo();
    }
  }
}

// set the selection in the style drop list
function KGTextViewEditingToolbar_UpdateStyleSelector()
{
  var selection = m_EditFrame.contentWindow.document.queryCommandValue("formatblock");
  switch (selection)
  {
  case "Normal":
    document.getElementById("KGTextViewEditingToolbar_Normal").selected = true;
    break;
  case "Heading 1":
    document.getElementById("KGTextViewEditingToolbar_Heading1").selected = true;
    break;
  case "Heading 2":
    document.getElementById("KGTextViewEditingToolbar_Heading2").selected = true;
    break;
  case "Heading 3":
    document.getElementById("KGTextViewEditingToolbar_Heading3").selected = true;
    break;
  }
}

// set the selection on the bold, italic and underline buttons
function KGEditingToolbar_UpdateTextFormatBtns_Wrapped(_boldBtnClientID, _italicBtnClientID, _underlineBtnClientID)
{
  var boldBtn = document.getElementById(_boldBtnClientID);
  var italicBtn = document.getElementById(_italicBtnClientID);
  var underlineBtn = document.getElementById(_underlineBtnClientID);
  
  var selectboldBtn = m_EditFrame.contentWindow.document.queryCommandState("Bold");
  var selectitalicBtn = m_EditFrame.contentWindow.document.queryCommandState("Italic");
  var selectunderlineBtn = m_EditFrame.contentWindow.document.queryCommandState("Underline");
  
  if (selectboldBtn)
    KGEditingToolbar_SelectButton(boldBtn);
  else
    KGEditingToolbar_DeSelectButton(boldBtn);
  
  if (selectitalicBtn)
    KGEditingToolbar_SelectButton(italicBtn);
  else
    KGEditingToolbar_DeSelectButton(italicBtn);
  
  if (selectunderlineBtn)
    KGEditingToolbar_SelectButton(underlineBtn);
  else
    KGEditingToolbar_DeSelectButton(underlineBtn);
}

// activate the cut, copy and paste buttons when the commands are available
function KGEditingToolbar_UpdateCutCopyPasteBtns_Wrapped(_cutBtnClientID, _copyBtnClientID, _pasteBtnClientID)
{
  var cutButton = document.getElementById(_cutBtnClientID);
  var copyButton = document.getElementById(_copyBtnClientID);
  var pasteButton = document.getElementById(_pasteBtnClientID);
  
  var enableCutButton;
  var enableCopyButton;
  var enablePasteButton;

  if (navigator.appName == "Microsoft Internet Explorer")
  {
    enableCutButton = m_EditFrame.contentWindow.document.queryCommandEnabled("Cut");
    enableCopyButton = m_EditFrame.contentWindow.document.queryCommandEnabled("Copy");
    enablePasteButton = m_EditFrame.contentWindow.document.queryCommandEnabled("Paste");
  }
  else //disable the cut copy paste buttons for non IE browsers
  {
    enableCutButton = false;
    enableCopyButton = false;
    enablePasteButton = false;
  }
  
  if (enableCutButton)
    KGButtonToolbar_UnGreyButton(cutButton);
  else
    KGButtonToolbar_GreyOutButton(cutButton);

  if (enableCopyButton)
    KGButtonToolbar_UnGreyButton(copyButton);
  else
    KGButtonToolbar_GreyOutButton(copyButton);

  if (enablePasteButton)
    KGButtonToolbar_UnGreyButton(pasteButton);
  else
    KGButtonToolbar_GreyOutButton(pasteButton);
}

// activate the undo and redo buttons when the commands are available
function KGEditingToolbar_UpdateUndoRedoBtns_Wrapped(_mode, _undoBtnClientID, _redoBtnClientID, _enableUndoBtn, _enableRedoBtn)
{
  //debugger;
  var undoButton = document.getElementById(_undoBtnClientID);
  var redoButton = document.getElementById(_redoBtnClientID);
  var enableUndoBtn;
  var enableRedoBtn;
  if (_mode == "TextView")
  {
    enableUndoBtn = m_EditFrame.contentWindow.document.queryCommandEnabled("Undo");
    enableRedoBtn = m_EditFrame.contentWindow.document.queryCommandEnabled("Redo");
  }
  else if (_mode == "MapView")
  {
    enableUndoBtn = _enableUndoBtn;
    enableRedoBtn = _enableRedoBtn;
  }
  
  if (enableUndoBtn)
    KGButtonToolbar_UnGreyButton(undoButton);
  else
    KGButtonToolbar_GreyOutButton(undoButton);
  
  if (enableRedoBtn)
    KGButtonToolbar_UnGreyButton(redoButton);
  else
    KGButtonToolbar_GreyOutButton(redoButton);
}

var m_KGButtonToolbar_EditbarMode;
var m_KGTextViewButtonToolbar_EditbarMode;

function KGButtonToolbar_ChangeEditbarMode(_mode)
{
  KGEditingToolbar_ChangeEditbarMode(_mode);
}

// Switch edit toolbar mode
function KGButtonToolbar_ChangeEditbarMode_Wrapped(_mode, _styleSelectorClientID, _editBtn_boldClientID, _editBtn_italicClientID, _editBtn_underlineClientID, _editBtn_decIndentClientID, _editBtn_incIndentClientID, _editBtn_OlistClientID, _editBtn_UlistClientID, _editBtn_imageClientID, _editBtn_fileClientID, _editBtn_linkClientID, _editBtn_cutClientID, _editBtn_copyClientID, _editBtn_pasteClientID, _editBtn_moveClientID, _editBtn_deleteClientID, _editBtn_undoClientID, _editBtn_redoClientID, _editBtn_setTextClientID, _namePrefix)
{
  //debugger;
  //if ((_mode == 'MapView' && _mode != m_KGButtonToolbar_EditbarMode) || ((_mode == 'TextView' && _mode != m_KGTextViewButtonToolbar_EditbarMode)))
  //{
    var styleSelector = null;
    if(_styleSelectorClientID != null && _styleSelectorClientID != '')
      styleSelector = document.getElementById(_styleSelectorClientID);
    var boldButton = null;
    if(_editBtn_boldClientID != null && _editBtn_boldClientID != '')
      boldButton = document.getElementById(_editBtn_boldClientID);
    var italicButton = null;
    if(_editBtn_italicClientID != null && _editBtn_italicClientID != '')
      italicButton = document.getElementById(_editBtn_italicClientID);
    var underlineButton = null;
    if(_editBtn_underlineClientID != null && _editBtn_underlineClientID != '')
      underlineButton = document.getElementById(_editBtn_underlineClientID);
    var decIndentButton = null;
    if(_editBtn_decIndentClientID != null && _editBtn_decIndentClientID != '')
      decIndentButton = document.getElementById(_editBtn_decIndentClientID);
    var incIndentButton = null;
    if(_editBtn_incIndentClientID != null && _editBtn_incIndentClientID != '')
      incIndentButton = document.getElementById(_editBtn_incIndentClientID);
    var oListButton = null;
    if(_editBtn_OlistClientID != null && _editBtn_OlistClientID != '')
      oListButton = document.getElementById(_editBtn_OlistClientID);
    var uListButton = null;
    if(_editBtn_UlistClientID != null && _editBtn_UlistClientID != '')
      uListButton = document.getElementById(_editBtn_UlistClientID);
    var insertImageButton = null;
    if(_editBtn_imageClientID != null && _editBtn_imageClientID != '')
      insertImageButton = document.getElementById(_editBtn_imageClientID);
    var insertFileButton = null;
    if(_editBtn_fileClientID != null && _editBtn_fileClientID != '')
      insertFileButton = document.getElementById(_editBtn_fileClientID);
    var insertLinkButton = null;
    if(_editBtn_linkClientID != null && _editBtn_linkClientID != '')
      insertLinkButton = document.getElementById(_editBtn_linkClientID);
    var cutButton = document.getElementById(_editBtn_cutClientID);
    var copyButton = document.getElementById(_editBtn_copyClientID);
    var pasteButton = document.getElementById(_editBtn_pasteClientID);
    if(_editBtn_moveClientID != null && _editBtn_moveClientID != '')
			var moveButton = document.getElementById(_editBtn_moveClientID);
    if(_editBtn_deleteClientID != null && _editBtn_deleteClientID != '')
      var deleteButton = document.getElementById(_editBtn_deleteClientID);
    var undoButton = document.getElementById(_editBtn_undoClientID);
    var redoButton = document.getElementById(_editBtn_redoClientID);
    var setTickerTextButton = null;
    if(_editBtn_setTextClientID != null && _editBtn_setTextClientID != '')
      setTickerTextButton = document.getElementById(_editBtn_setTextClientID);
    
    switch(_mode)
    {
    case "TextView":
      if (m_buttonToolbar_docVersionSelect != null)
        m_buttonToolbar_docVersionSelect.select.disabled = false;
      styleSelector.disabled = false;
      KGButtonToolbar_UnGreyButton(boldButton);
      KGButtonToolbar_UnGreyButton(italicButton);
      KGButtonToolbar_UnGreyButton(underlineButton);
      KGButtonToolbar_UnGreyButton(decIndentButton);
      KGButtonToolbar_UnGreyButton(incIndentButton);
      KGButtonToolbar_UnGreyButton(oListButton);
      KGButtonToolbar_UnGreyButton(uListButton);
      KGButtonToolbar_UnGreyButton(insertImageButton);
      KGButtonToolbar_UnGreyButton(insertFileButton);
      KGButtonToolbar_UnGreyButton(insertLinkButton);
      eval(_namePrefix + '_UpdateCutCopyPasteBtns()');
      eval(_namePrefix + '_UpdateUndoRedoBtns()');
      break;
    case "MapView":
      if (m_buttonToolbar_docVersionSelect != null)
        m_buttonToolbar_docVersionSelect.select.disabled = true;
      if (m_bEditable == true && Map_TextEditOnly == 0)
      {
      /*styleSelector.disabled = true;
      KGButtonToolbar_GreyOutButton(boldButton);
      KGButtonToolbar_GreyOutButton(italicButton);
      KGButtonToolbar_GreyOutButton(underlineButton);
      KGButtonToolbar_GreyOutButton(decIndentButton);
      KGButtonToolbar_GreyOutButton(incIndentButton);
      KGButtonToolbar_GreyOutButton(oListButton);
      KGButtonToolbar_GreyOutButton(uListButton);
      KGButtonToolbar_GreyOutButton(insertImageButton);
      KGButtonToolbar_GreyOutButton(insertFileButton);
      KGButtonToolbar_GreyOutButton(insertLinkButton);*/
      KGButtonToolbar_UnGreyButton(cutButton);
      KGButtonToolbar_UnGreyButton(copyButton);
      KGButtonToolbar_UnGreyButton(pasteButton);
      KGButtonToolbar_UnGreyButton(moveButton);
      KGButtonToolbar_UnGreyButton(deleteButton);
      KGButtonToolbar_GreyOutButton(undoButton);
      KGButtonToolbar_GreyOutButton(redoButton);
      }
      if (setTickerTextButton.className == "ButtonToolbar_TextButtonDivActive")
        setTickerTextButton.className = "ButtonToolbar_TextButtonDivInactive";
      break;
    case "TextViewReset":
      if (m_buttonToolbar_docVersionSelect != null)
        m_buttonToolbar_docVersionSelect.select.disabled = true;
      styleSelector.disabled = false;
      KGButtonToolbar_UnGreyButton(boldButton);
      KGButtonToolbar_UnGreyButton(italicButton);
      KGButtonToolbar_UnGreyButton(underlineButton);
      KGButtonToolbar_UnGreyButton(decIndentButton);
      KGButtonToolbar_UnGreyButton(incIndentButton);
      KGButtonToolbar_UnGreyButton(oListButton);
      KGButtonToolbar_UnGreyButton(uListButton);
      KGButtonToolbar_UnGreyButton(insertImageButton);
      KGButtonToolbar_UnGreyButton(insertFileButton);
      KGButtonToolbar_UnGreyButton(insertLinkButton);
      // deselect buttons
      KGEditingToolbar_DeSelectButton(boldButton);
      KGEditingToolbar_DeSelectButton(italicButton);
      KGEditingToolbar_DeSelectButton(underlineButton);
      KGButtonToolbar_GreyOutButton(undoButton);
      KGButtonToolbar_GreyOutButton(redoButton);
      KGButtonToolbar_GreyOutButton(cutButton);
      KGButtonToolbar_GreyOutButton(copyButton);
      KGButtonToolbar_GreyOutButton(pasteButton);
      break;
    }
    
    // update the global var
    if(_mode == 'MapView')
      m_KGButtonToolbar_EditbarMode = _mode;
    else if(_mode == 'TextView')
      m_KGTextViewButtonToolbar_EditbarMode = _mode;
  //}
}


// get the write text view button
function KGButtonToolbar_getEditingButton_Wrapped(_editingButtonID)
{
  var btn = document.getElementById(_editingButtonID);
  return btn;
}


// delay loading images until they're needed http://developer.yahoo.com/yui/imageloader/
// when the images are loaded they don't have src
var editingToolbarGrp;
var editingToolbarLoadImages;
var texteditingToolbarGrp;
var texteditingToolbarLoadImages;
function setUpImagesEditingToolbar(_editingToolbarId,_startEditingButtonId)
{
  // means all the images in the group will load when click _startEditingButtonId
  editingToolbarGrp = new YAHOO.util.ImageLoader.group(_startEditingButtonId, 'click'); 
  
  // add a custom event - means can load images with editingToolbarLoadImages.fire();
  // trigger it from drawInitialMap if edit mode automatically
  editingToolbarLoadImages = new YAHOO.util.CustomEvent();
  editingToolbarGrp.addCustomTrigger(editingToolbarLoadImages);
  // it won't load the images up more than once because it's clever
  
  // add all the images in the toolbar to the group
  var editingToolbar = document.getElementById(_editingToolbarId);
  var images = editingToolbar.getElementsByTagName("img");
  var img;
  var src;
  // new attribute srcToLoad added at server to avoid hard-coding anything here, it's the image url
  for (var j=0; j<images.length; j++)
  {
    img = images[j];
    src = img.getAttribute('srcToLoad');
    if (src)
      editingToolbarGrp.registerSrcImage(img.id, src);
  }
  
  // register textview editing toolbar images
  var rowt = document.getElementById('TextViewControlContent');
  if(rowt != null)
  {
    for(var ci=0; ci < rowt.childNodes.length; ci++)
    {
      if(rowt.childNodes[ci].id.indexOf('TextViewEditingToolbar') != -1)
      {
        setUpTextViewImagesEditingToolbar(rowt.childNodes[ci].id, _startEditingButtonId);
        break;
      }else if(rowt.childNodes[ci].id.indexOf('TextViewEditingToolbarContainer') != -1)
      {
        setUpTextViewImagesEditingToolbar(rowt.childNodes[ci].childNodes[0].id, _startEditingButtonId);
        break;
      }
    }
  }
}

function setUpTextViewImagesEditingToolbar(_editingToolbarId,_startEditingButtonId)
{
  texteditingToolbarGrp = new YAHOO.util.ImageLoader.group('TextViewEditSwitch', 'click'); // also attach to the text tab strip start editing button
  
  // add a custom event - means can load images with editingToolbarLoadImages.fire();
  // trigger it from drawInitialMap if edit mode automatically
  texteditingToolbarLoadImages = new YAHOO.util.CustomEvent();
  texteditingToolbarGrp.addCustomTrigger(texteditingToolbarLoadImages);
  // it won't load the images up more than once because it's clever
  
  var editingToolbar = document.getElementById(_editingToolbarId);
  if(editingToolbarGrp != null && editingToolbar != null)
  {
    // add all the images in the toolbar to the group
    var images = editingToolbar.getElementsByTagName("img");
    var img;
    var src;
    // new attribute srcToLoad added at server to avoid hard-coding anything here, it's the image url
    for (var j=0; j<images.length; j++)
    {
      img = images[j];
      src = img.getAttribute('srcToLoad');
      if (src)
      {
        editingToolbarGrp.registerSrcImage(img.id, src.replace('../',''));
        if(texteditingToolbarGrp != null)
          texteditingToolbarGrp.registerSrcImage(img.id, src.replace('../',''));
      }
    }
  }
  
}

function HideSelectedKnowdeHalo_delayed()
{
   HideSelectedKnowdeHalo(globalLastSelectedKnowde, globalLastMapDirection); 
}

function SwitchToSplitView(_sessionSkip, _cookieSkip, _collapsedMapViewPane)
{
	// set session property if not in callback
	if(_sessionSkip != 'skip')
	{
	  if(_sessionSkip != 'skipSetSession')
		  SetSessionProperty('SplitView', "true");
		  
		if (!_cookieSkip)
		  WM_setCookie('SplitView', 'true', m_splitCookieExpiration);
		// check current single view state... is it map?
		if(!PaneBStatus())
			globalRetToMapView = "true";
		else
			globalRetToMapView = "false";
	    
	  if(_collapsedMapViewPane == null || _collapsedMapViewPane != true)
	  {
		  // split view 50/50
		  DoExpandMapViewPane("split");
		}
		
	}
	// show splitter bar
	var splitterPaneMap = Splitter1.Panes[0];
	var splitterBar = splitterPaneMap.element.parentNode.nextSibling;
  if(_collapsedMapViewPane == null || _collapsedMapViewPane != true)
	{
	  splitterBar.className = 'VerticalSplitterBar';
	}
	// change toolbar visibility
	//document.getElementById("KGButtonToolbar_SplitView").style.display = "none";
	//document.getElementById("KGButtonToolbar_FullView").style.display = "block";
	// show the splitter arrows
	var splitterArrowDown = document.getElementById('SplitterArrowDown');
	if(_collapsedMapViewPane == null || _collapsedMapViewPane != true)
	{
	  splitterArrowDown.className = 'arrowDown'; //arrowDown
	}
	var splitterArrowUp = document.getElementById('SplitterArrowUp');
	splitterArrowUp.className = 'arrowUp'; //arrowUp
	// update global variable for splitter handler js
	globalSplitterSetting = "split";
	if(window.Active_KGID)
		if(Active_KGID != "")
	    updateHandlersAfterSwitch('split');
				
	if(m_globalFullDocked == true)
  {
    m_globalFullDocked = false;
    
    // close it
    CloseDockedKGHelpControl('HelpFrame', null, true);
  }
}

function SwitchToFullView(_sessionSkip, _expandMap)
{
//debugger;
	// clear session property if not in callback
	if(_sessionSkip != 'skip')
	{
		SetSessionProperty('SplitView', "false");
		WM_killCookie('SplitView');
		// check global to know whether to show map or docs
		if(globalRetToMapView == "true")
			DoExpandMapViewPane("fully");
		else
			DoCollapseMapViewPane();
	}
	/*if (_expandMap && _expandMap.toLowerCase() == "true")
	  setTimeout('DoExpandMapViewPane("fully")',10);*/
	if(globalCatClick == true)
	{
		// make sure cat control loads full index docs after edit mode
		setTimeout('DoCollapseMapViewPane()',10);
		globalCatClick = false;
	}

	// hide the splitter bar & arrows...
	if(_expandMap != null)
	{
		if(_expandMap.toLowerCase() == "true")
		{
			// hide splitter bar
			var splitterBottomPane = Splitter1.Panes[0];
			if(splitterBottomPane.Height > 0)
			{
				// splitter has been opened before this call... so dont hide arrows
			}
			else
			{
				var splitterPaneMap = Splitter1.Panes[0];
				var splitterBar = splitterPaneMap.element.parentNode.nextSibling;
				splitterBar.className = 'HiddenSplitterBar';
				var splitterArrowDown = document.getElementById('SplitterArrowDown');
				splitterArrowDown.className = 'HiddenArrowDown'; //arrowDown
				var splitterArrowUp = document.getElementById('SplitterArrowUp');
				splitterArrowUp.className = 'HiddenArrowUp'; //arrowUp
			}
		}
	}
	// update global variable for splitter handler js
	//globalSplitterSetting = "single";
	if(window.Active_KGID)
		if(Active_KGID != "")
	    updateHandlersAfterSwitch('single');
}

var m_hiddenMyHkBtnID;
function KGButtonToolbar_hideOrShowMapButtons_Wrapped(_show, _addToMyHKBtnID, _removeFromMyHKBtnID, _resetMapViewBtnID, _knowdePermBtnID, _pdfExporterBtnID, _printMapBtnID, _wordExporterBtnID)
{
  // this function hides or shows buttons relating to the map
  // probably because the splitter hid/showed the map, maybe without causing a callback
  // so if you add a button to the 'hide' code here, you probably need to add it to the 'show' part here as well
  //    e.g. close the splitter to hide the map, reopen it - there's no callback, all the buttons that got hidden need to come back
  var knowdePermBtn = document.getElementById(_knowdePermBtnID);
  var resetMapViewBtn = document.getElementById(_resetMapViewBtnID);
  var pdfExporterBtn = document.getElementById(_pdfExporterBtnID);
  var printMapBtn = document.getElementById(_printMapBtnID);
  var wordExporterBtn = document.getElementById(_wordExporterBtnID);
  var editBtn = KGButtonToolbar_getEditingButton();
 
  if (_show)
  {
    if (!Active_KGID)
      return;
      
    if (editBtn != null && editBtn.isOkToShow) 
    {
      editBtn.style.display = "inline";
    }
    
    if (!m_bEditable)
    { // these buttons are only visible in non-edit mode
      if (m_hiddenMyHkBtnID)
      {
        //show either the add to / remove from my hk button
        var myHkBtn = document.getElementById(m_hiddenMyHkBtnID);
        myHkBtn.style.display = 'inline';
        m_hiddenMyHkBtnID = null; // don't want to reuse it
      }
    }    
    resetMapViewBtn.style.display = 'inline';
    pdfExporterBtn.style.display = 'inline';
    printMapBtn.style.display = 'inline';
    if (wordExporterBtn)
      wordExporterBtn.style.display = 'inline';
    //we will only be here if we've already loaded the map, and we're reopening the splitter
    //  so it should be ok to just show the ones we had before
    //if the map gets reloaded, then a callback will be triggered in loading the map, 
    //  so the buttons will get refreshed there instead
  }
  else // hide
  {
    if (editBtn != null) 
    {
      editBtn.style.display = "none";
    }
    
    var addToMyHKBtn = document.getElementById(_addToMyHKBtnID);
    var removeFromMyHKBtn = document.getElementById(_removeFromMyHKBtnID);
    if (addToMyHKBtn.style.display != 'none')
    {
      m_hiddenMyHkBtnID = _addToMyHKBtnID;
      addToMyHKBtn.style.display = 'none';
    }
    else if (removeFromMyHKBtn.style.display != 'none')
    {
      m_hiddenMyHkBtnID = _removeFromMyHKBtnID;
      removeFromMyHKBtn.style.display = 'none';
    }
    
    if(knowdePermBtn != null)
			knowdePermBtn.style.display = 'none';
    resetMapViewBtn.style.display = 'none';
    pdfExporterBtn.style.display = 'none';
    printMapBtn.style.display = 'none';
    if (wordExporterBtn)
      wordExporterBtn.style.display = 'none';
  }
  
  KGButtonToolbar_hideOrShowButtonDivider(); // needs to be at the end
}

function KGButtonToolbar_hideOrShowStandardToolbar_Wrapped(_show, _toolbarID)
{
  var toolbar = document.getElementById(_toolbarID);
  if (_show)
  {
    toolbar.style.display = '';
  }
  else // hide
  {
    toolbar.style.display = 'none';
  }
}

function updateHandlersAfterSwitch(_switch, _kgid)
{
	/*try
	{
	  var kgid;
	  if (_kgid)
	    kgid = _kgid;
	  else if (window.Active_KGID)
	    kgid = Active_KGID;
	  else
	    return;
	    
		var Handler = document.getElementById(kgid);
		var kgNameHandler = document.getElementById('KGName_' + kgid);
		if(_switch == 'split')
		{
			Handler.href = Handler.href.replace("function temp(){ SwitchPaneView('map');return;","");
			Handler.href = Handler.href.replace("function%20temp(){%20SwitchPaneView('map');return;","");
			Handler.href = Handler.href.replace("} temp();","");
			Handler.href = Handler.href.replace("}%20temp();","");
			Handler.href = Handler.href.replace(', false, true)',', false, false)');
			Handler.href = Handler.href.replace(',%20false,%20true)',', false, false)');
			Handler.href = Handler.href.replace('KGTabbedWindowsControl_MyHK_KGSelected', 'ShowTextView');
			Handler.href = Handler.href.replace('KGTabbedWindowsControl_KGSelected', 'ShowTextView');
			if (kgNameHandler && kgNameHandler.href) // KGExecuteMapControl - kgNameHandler has onclick not href
			  kgNameHandler.href = Handler.href;
			Handler.className = "doc_UrlSelected";
			Handler.innerHTML = 'Now showing the Knowledge Gene<sup>&#174;</sup>, click here to view the document';
		}
		else
		{
			Handler.href = Handler.href.replace("function temp(){ SwitchPaneView('map');return;","");
			Handler.href = Handler.href.replace("function%20temp(){%20SwitchPaneView('map');return;","");
			Handler.href = Handler.href.replace("} temp();","");
			Handler.href = Handler.href.replace("}%20temp();","");
			Handler.href = Handler.href.replace(', false, true)',', false, false)');
			Handler.href = Handler.href.replace(',%20false,%20true)',', false, false)');
			Handler.href = Handler.href.replace('ShowTextView','KGTabbedWindowsControl_MyHK_KGSelected');
			if (kgNameHandler && kgNameHandler.href) // KGExecuteMapControl - kgNameHandler has onclick not href
			  kgNameHandler.href = Handler.href;
			Handler.className = "doc_UrlSelected";
			Handler.innerHTML = 'Click here to view the Knowledge Gene<sup>&#174;</sup>';
		}
	}
	catch(Exception)
	{
	}*/
}

function SwitchPaneView(_showPane)
{
    // Start by making sure that start editing isn't visible.  If it's supposed to be, it will be shown later on.
    var editBtn = KGButtonToolbar_getEditingButton();
    if (editBtn != null) 
    {
      editBtn.style.display = "none";
    }
    
	if(_showPane == 'map')
	{
		DoExpandMapViewPane('fully');
	}
	else
	{
		DoCollapseMapViewPane();
	}
}

function KGButtonToolbar_hideOrShowButtonDivider_Wrapped(_btnDividerId)
{
  // if any of the buttons after the divider are visible, show the divider, otherwise hide it
  // assuming there's always a button before the divider - either split view or single view is always shown
  // call this after updating the other buttons
  var btnDivider = document.getElementById(_btnDividerId);
  var sib = btnDivider.nextSibling;
  
  //while (sib)
  do
  {
    if (sib.nodeType != 3 && sib.style.display != 'none' && sib.style.display != '' && sib.className != 'ButtonToolbar_Hidden')
    {
      btnDivider.style.display = 'inline';
      return;
    }
    //sib = sib.nextSibling;
  }while(sib = sib.nextSibling)
  
  btnDivider.style.display = 'none';
}

function ButtonToolbar_handlePdfExporterBtn_onmouseout()
{
  PDFExporterControl_HideMenuTimer = setTimeout("PDFExporterControl_HideMenu()", PDFExporterControl_HideMenuTimerLength);
}

function ButtonToolbar_handlePrintMapBtn_onmouseout()
{
  PDFExporterControl_HideMenuTimer = setTimeout("PDFExporterControl_HideMenu()", PDFExporterControl_HideMenuTimerLength);
}

function KGButtonToolbar_CategoryHomePage()
{
  // hide the standardToolbar
  KGButtonToolbar_hideOrShowStandardToolbar(false);
  // show the ViewHKMaps button
  KGButtonToolbar_hideOrShowViewHKMapsButton(true);
}

function KGButtonToolbar_ViewHyperknowledgeMaps()
{
  // hide the ViewHKMaps button
  KGButtonToolbar_hideOrShowViewHKMapsButton(false);
  // show the standardToolbar
  KGButtonToolbar_hideOrShowStandardToolbar(true);
  // load the indexed docs tab
  //KGTabbedWindowsControl_CallbackTrigger('TabSelected, Indexed Documents');
}

function KGButtonToolbar_switchConnTypeButton_Wrapped(_btnId, _arithType)
{
  var btn = document.getElementById(_btnId);
  if (_arithType)
  {
    btn.className = "ButtonToolbar_ConnTypeLogic";
  }
  else
  {
    btn.className = "ButtonToolbar_ConnTypeArith";
  }
}
// KnowledgeGeneListControl JScript File

var globalKGListTimer;
var tempKGListSelectedItem;
var globalKGListSelectedItem;
var globalMyKnowledgeGridClientID;
var m_MyKnowledgeRemoveKGMessageBox = null;
var CurrentlyShowingMyKnowledgeMessageBox;

function KGMyKnowledgeControl_Grid_OnInit(_knowledgeGenesGridClientID)
{
 globalMyKnowledgeGridClientID = _knowledgeGenesGridClientID;
}

function KGMyKnowledgeControl_CallbackDone(_args, _context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  CloseMyKnowledgeMessageBox();
  
  // check for exceptions
  if(_args.length == 0 || _args.indexOf("System exception caught") == 0) // this might be too specific and miss some exceptions, but need to avoid showing message box if e.g. a KG happens to have 'exception' in its name or description
  {
    if (_args.indexOf('deadlocked on lock resources with another process') > -1)
      alert("Sorry, our servers are too busy at the moment\n\nPlease try again later");
    else
      alert("AJAX Failure:\n\n" + args);
    return;
  }
  
  // get the parameters
  var argsSplit = _args.split('[@|@]');
  var json = argsSplit[0];
  var htmlContent = argsSplit[1];
  
  var retMsg = eval( '(' + json + ')' );
  var holderId = retMsg.HolderId;
  
  var holder = document.getElementById(holderId);
  if (!holder)
  {
    KGMyKnowledgeControl_CallbackError('The holder doesn\'t exist ' + holderId);
    return;
  }
  
  // fill the control
  SetOuterHtml(holder, htmlContent);
  
  if (retMsg.Kgid == Active_KGID)
  {
    // update the button toolbar
    switchSubscribeButton(false);
  }
}

function KGMyKnowledgeControl_Grid_OnRemoveSelect(_kgid, _parentControlDivId, _callbackTriggerName, e)
{
  CancelBubble(e);
  KGMyKnowledgeControl_DislayRemoveKGMessage(_parentControlDivId, e);
  var args='Action=unsub|kgid='+ _kgid;
  eval(_callbackTriggerName + "('" + args + "')");
}

function KGMyKnowledgeControl_CallbackTrigger_Wrapped(_args, _getPageInfoName, _cbReference)
{
  // pass back the current page numbers
  // alternative could be to save it in the session, but could lead to a lot of bugs if it isn't cleared properly
  var pageInfo = eval(_getPageInfoName + "()");
  _args += '|curPage=' + pageInfo.CurPage;
  
  // this is only required when removing a kg
  //    if it's the only one on the last page, we'll need to decrease the current page (done at the server)
  if (_args.indexOf("Action=unsub") > -1 && pageInfo.CurPage > 1 && pageInfo.IsShowingSingleItem())
    _args += '|pageBack=true';
  
  CallbackTrigger_Wrapped(_args, _cbReference);
}

function KGMyKnowledgeControl_CallbackError(args, context)
{
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
   
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    var alertMessage = "The KGMyKnowledgeControl encountered an error. \n\n" + args;
    alert(alertMessage);
  }
}

function KGMyKnowledgeControl_DislayRemoveKGMessage(_parentControlDivId, e)
{
  m_MyKnowledgeRemoveKGMessageBox = document.getElementById("MyKnowledgeRemoveKGMessageBox");
  
  if(m_MyKnowledgeRemoveKGMessageBox == null)
  {
    m_MyKnowledgeRemoveKGMessageBox = document.createElement("div");
    m_MyKnowledgeRemoveKGMessageBox.setAttribute("id", "MyKnowledgeRemoveKGMessageBox");
    m_MyKnowledgeRemoveKGMessageBox.style.display = "none";
    m_MyKnowledgeRemoveKGMessageBox.style.width = "420px"
    m_MyKnowledgeRemoveKGMessageBox.style.height = "100px";
    m_MyKnowledgeRemoveKGMessageBox.style.position = "absolute";
    m_MyKnowledgeRemoveKGMessageBox.style.zIndex = TopZIndex();
    
    m_MyKnowledgeRemoveKGMessageBox.innerHTML= "<div style=\"position:absolute;width:420px;height:100px;border:gray solid 1pt;background:white\"><table width=\"100%\"><tr><td width = \"15%\" align=\"right\" style=\"font-size: xx-small\"><br/><br/><img src=\"Images/loadingbar.gif\" /></td><td width = \"75%\" align=\"left\" style=\"font-size: xx-small\"><br/><br/>Removing Knowledge Gene<sup>&#174;</sup> from My Knowledge Genes....<br/>Note, this Knowledge Gene<sup>&#174;</sup> map will still be available in the original author's My Profile page.</td><tr><td width = \"10%\" align=\"right\" style=\"font-size: xx-small\"><br/><br/></td></tr></table></div>";

    //m_MyKnowledgeRemoveKGMessageBox.innerHTML = "<div style='position:absolute;width:420px;height:120px;border:gray solid 1pt;background:white'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' bgcolor='#BFD4F3' style='color:black;font-size:12pt'>Removing Knowledge Gene from My Knowledge</td></tr><tr><td rowspan='2' bgcolor='#ffffff' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td bgcolor='#ffffff'>Please wait...<br />Note, this Knowledge Gene will still be available in the original author's My Profile page.</td></tr></table></div>";
    
    var parentControlDiv = document.getElementById(_parentControlDivId);
    InsertAdjacentElement(parentControlDiv,"afterBegin", m_MyKnowledgeRemoveKGMessageBox);
  }
  else
  {
    m_MyKnowledgeRemoveKGMessageBox.style.zIndex = TopZIndex(); //Show on top of other items
  }
  
  PositionMyKnowledgeMessageBox(_parentControlDivId, e);
}

function TopZIndex()
//Find highest z index in current document and returns this value + 1 (so that
//the control using this value will appear on top of everything currently in  
//the page, but will appear behind everything called subsequently).  JPC.
//(inspired by http://domscripting.com/presentations/atmedia2006/slides/, slide 12)
{
  var maxZindex = 0;
  var elems = document.getElementsByTagName("div");
  
  for (var ti=0; ti<elems.length; ti++)
  {
    if (elems[ti].style.zIndex > maxZindex)
    {
       maxZindex = parseInt(elems[ti].style.zIndex);
    }
  }

  return maxZindex + 1;
}


/////////////////////
// Positions the suppled message box in the centre of the map view
function PositionMyKnowledgeMessageBox(_parentControlDivId, e)
{
  var parentControl = document.getElementById(_parentControlDivId); 
  
  //Displays messagebox in middle of visible screen.  JPC.
  e = e || window.event;
  var x = e.x || e.pageX;
  var y = e.y || e.pageY;
  m_MyKnowledgeRemoveKGMessageBox.style.top = y + 20;     
  m_MyKnowledgeRemoveKGMessageBox.style.left = x - 15; // - (m_MyKnowledgeRemoveKGMessageBox.style.width / 2);
  m_MyKnowledgeRemoveKGMessageBox.style.display = "block";
  m_MyKnowledgeRemoveKGMessageBox.style.zIndex = TopZIndex();
  m_MyKnowledgeRemoveKGMessageBox.style.visibility = "visible";
  CurrentlyShowingMyKnowledgeMessageBox = true;
}

//////////////////
// Closes the message box
function CloseMyKnowledgeMessageBox()
{
  if(m_MyKnowledgeRemoveKGMessageBox != null)
  {
    m_MyKnowledgeRemoveKGMessageBox.style.visibility = "hidden";
    m_MyKnowledgeRemoveKGMessageBox.style.display = "none";
    CurrentlyShowingMyKnowledgeMessageBox = false;
  }
}
// JScript File
// for KGProfileHeaderControl 

function KGProfileHeaderControl_AddToMyNetwork(_userAddingId, _userAddedId, _callbackTriggerName)
{
  KGProfileHeaderControl_AddRemove(_userAddingId, _userAddedId, 'add', _callbackTriggerName);
}

function KGProfileHeaderControl_RemoveFromMyNetwork(_userAddingId, _userAddedId, _callbackTriggerName, e)
{
  KGProfileHeaderControl_AddRemove(_userAddingId, _userAddedId, 'remove', _callbackTriggerName);
  CancelBubble(e);
}

function KGProfileHeaderControl_AddRemove(_userAddingId, _userAddedId, _action, _callbackTriggerName)
{
  if(_userAddingId != null && _userAddedId != null && _action != null)
  {
    var args = 'action=' + _action + '|UserAddingId=' + _userAddingId + '|UserAddedId=' + _userAddedId;
    eval(_callbackTriggerName + "('" + args + "')");
    // currently, add and remove are never visible on the profile tab, 
    // so if we get here should callback to the Community tab's profile header
    // but passing in the callback trigger name incase it changes in future
  }
  return true;
}// end function

function KGProfileHeaderControl_CallbackDone(args, context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  // extract the predefined control client IDs
  var s = args.split('|');
  if(s.length > 1)
  {
    var id = s[0];
    var action = s[1];
    var htmlText = s[2];
    
    // search for the control container
    var holder = document.getElementById(id);
    
    // Test if the container is found
    // Yes: replace the innerHTML with the callback result
    //  No: call CallbackError with Content div not found error message
    if(holder != null)
    {
      SetOuterHtml(holder,htmlText);   
      if (action == "add" || action == "remove")
      {
        if (window.myNetworkControl_CallbackTrigger)
          setTimeout("myNetworkControl_CallbackTrigger('action=repopulate')", 10);
      }
    }//end if(holder ....
    else
    {
      KGProfileHeaderControl_CallbackError('ContentDiv not found in KGProfileHeaderControl.', '');
    }
  }
}

function KGProfileHeaderControl_CallbackError(args, context)
{
  alert('Error in KGProfileHeaderControl callback');
}

function myNetworkControl_AddRemove(_userAddingId, _userAddedId, _action)
{
  if(_userAddingId != null && _userAddedId != null && _action != null)
  {
    var args = 'action=' + _action + '|UserAddingId=' + _userAddingId + '|UserAddedId=' + _userAddedId;
    myNetworkControl_CallbackTrigger(args);
  }
  return true;
}// end function

function myNetworkControl_CallbackDone(args, context)
{ 
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  // extract the predefined control client IDs
  var s = args.split('|');
  if(s.length > 1)
  {
    var json = s[0];
    var htmlText = s[1];
    
    var retMsg = eval( '(' + json + ')' );
    var holderId = retMsg.HolderId;
    
    // search for the control container
    var holder = document.getElementById(holderId);
    
    // Test if the container is found
    // Yes: replace the innerHTML with the callback result
    //  No: call CallbackError with Content div not found error message
    if(holder != null)
    {
      SetOuterHtml(holder,htmlText);   
      var action = retMsg.Action;
      if (action == "add" || action == "remove")
      {
        var userAddedId = retMsg.UserAddedId;
        if (window.Com_KGProfileHeaderControl_CallbackTrigger && window.Com_GetSelectedProfileId && Com_GetSelectedProfileId() == userAddedId)
          setTimeout("Com_KGProfileHeaderControl_CallbackTrigger('action=repopulate')", 10);
      }
    }//end if(holder ....
    else
    {
      myNetworkControl_ProcessCallBackError('ContentDiv not found in KGMyNetworkControl.', '');
    }
  }
}

function myNetworkControl_ProcessCallBackError(_args, _context)
{
  alert('Error in KGMyNetworkControl callback');
}

function myNetworkControl_AddToMyNetwork(_userAddingId, _userAddedId)
{
  myNetworkControl_AddRemove(_userAddingId, _userAddedId, 'add');
}

function myNetworkControl_RemoveFromMyNetwork(_userAddingId, _userAddedId, e)
{
  myNetworkControl_AddRemove(_userAddingId, _userAddedId, 'remove');
  CancelBubble(e);
}

function MyNWSitesControl_RemoveLink(_personID, _linkID, e)
{
  var args = 'action=remove|id=' + _linkID;
  MyNWSitesControl_CallbackTrigger(args);
  CancelBubble(e);
}

function MyNWSitesControl_CreateLink_Wrapped(_nameTextBoxID, _urlTextBoxID)
{
  var validated = Page_ClientValidate('NewMyNWSiteValidation');
  if(validated)
  {
    // trigger callback to save the link to DB
    var namebox = document.getElementById(_nameTextBoxID);
    var urlbox = document.getElementById(_urlTextBoxID);
    if(namebox != null && urlbox != null)
    {
      var args = 'action=add|name=' + namebox.value.replace('|', '[@hkpipe@]') + '|url=' + urlbox.value.replace('|', '[@hkpipe@]');
      MyNWSitesControl_CallbackTrigger(args);
      MyNWSites_SaveLoadingIcon('Saving...', true);
    }
  }
}

function MyNWSitesControl_ProcessCallBackError(_args, _context)
{
  var error = 'Error in KGMyNetworkingSitesControl callback.';
  if(_args.length > 0)
    error += ' ' + _args;
  alert(error);
}

function MyNWSitesControl_CallbackTrigger_Wrapped(_args, _callbackScript)
{
  var args;

  // Construct the callback arguments
  if(_args != null)
  { 
    args = _args;
    
    if(args.length > 0)
    {
      // trigger the callback
      eval(_callbackScript);
    }
  }
}

function MyNWSitesControl_CallbackDone(args, context)
{ 
  MyNWSites_SaveLoadingIcon('', false);
  
  if(args.indexOf('Exception') == 0)
    alert(args);
  else
  {
    var results = args.split('|');
    if(results.length > 1)
    {
      var id = results[0];
      var isValid = results[1];
      var htmlText = results[2];
      
      // search for the control container
      var holder = document.getElementById(id);
      
      if(holder != null)
      {
        SetOuterHtml(holder,htmlText);  
        
        if (isValid && isValid.toLowerCase() != "false")
          MyNWSitesControl_ResetFields(); 
      }//end if(holder ....
      else
      {
        MyNWSitesControl_ProcessCallBackError('ContentDiv not found.', '');
      }
    }
  }
}

function MyNWSitesControl_ResetFields_Wrapped(_nameTextBoxID, _urlTextBoxID)
{
    var namebox = document.getElementById(_nameTextBoxID);
    var urlbox = document.getElementById(_urlTextBoxID);
    if(namebox != null && urlbox != null)
    {
      namebox.value = '';
      urlbox.value = 'http://';
    }
    
    MyNWSitesControl_ResetValidators();
}

function MyNWSitesControl_ResetValidators_Wrapped(_validatorSummaryCellId)
{
  var validatorSummaryCell = document.getElementById(_validatorSummaryCellId);
  
  if (validatorSummaryCell)
  {
    var valSum = validatorSummaryCell.firstChild;
    if (valSum)
      validatorSummaryCell.removeChild(valSum);
    // originally when the control first loads, the validator summary cell is empty
  }
}

// Hide or show save loading div
function MyNWSites_SaveLoadingIcon_Wrapped(_loadingDivID, _btnID, _loadingText, _show)
{
  var loadingDiv = document.getElementById(_loadingDivID);
  var saveBtn = document.getElementById(_btnID);
  if(loadingDiv != null && saveBtn != null)
  {
    if(_show == true)
    {
      saveBtn.style.display = 'none';
      loadingDiv.innerHTML = '<table cellspacing="0" cellpadding="0" border="0"><tr><td style="font-size:10px;">&nbsp;' + _loadingText + '...</td><td><img src="images/spinner.gif" width="16" height="16" border="0"></td></tr></table>';
      loadingDiv.style.display = 'block';
    }else
    {
      loadingDiv.style.display = 'none';
      loadingDiv.innerHTML = '';
      saveBtn.style.display = 'block';
    }
  }

}

var globalHCCRenderCount = 0;
var globalHCCRenderComplete = false;
var globalHCCCurrentWidth;
var globalCategoriesMovesHistory = new CategoriesMovesHistory();

function HorizontalCategoriesControl_Render_Wrapped(_width, _containerClientID, _menuID, _cbreference)
{
	if(_globalCookieTestResult)
	{
		var control = document.getElementById(_containerClientID); //the div containing the menu and bookmarks
		var menu = document.getElementById(_menuID);
		// this function ensures that the control has been rendered before proceeding
		if (control == null || menu == null)
		{
			setTimeout("HorizontalCategoriesControl_Render()", 200);
		}
		else
		{
		  if (_width)
		  {
		    control.style.width = _width + 'px';
		    globalHCCCurrentWidth = _width;
		  }
			var availableWidth = HorizontalCategoriesControl_CalculateAvailableWidth(control, _width);

		  menu.firstChild.style.visibility = "hidden";
		  menu.style.display = "inline";
		  
      var controlwidth = control.clientWidth || control.offsetWidth;
			// the controlwidth will be 0 if the control hasn't finished rendering so wait until it has
      if (controlwidth <= 0 && globalHCCRenderCount != 10)
      {
				if (globalVisibleTab == "TSC_myprofile" || globalVisibleTab == "TSC_genes")
					setTimeout("HorizontalCategoriesControl_Render()", 500);
				else
					return;
		  }
      else
      {
				// reset glob var
        globalHCCRenderCount = 0;
        
        if (!_width) // because it was set earlier in this method. Shouldn't matter, it should just set it to the same again
          globalHCCCurrentWidth = controlwidth;
        
			  // check to see if the menu and book markcontrol fit in the HCC
  	    
			  // if they don't fit we need to redraw the menu with less items
			  var menuitems = menu.getElementsByTagName("td");
  			   
			  var length = menuitems[0].clientWidth;
			  for (var index=1; index < menuitems.length; index++)
			  {
				  length += "," + menuitems[index].clientWidth;
			  }
			  var bBin = document.getElementById("TCC_HorizontalCategoriesControl1_BreadBin");
			  if(bBin != null)
				  bBin.style.display = "none";
			  // this will be the index of the first item to be added to "more"    
			  var args = 'Action=RenderMenu';
			  args += '|availableWidth='+availableWidth;
			  args += '|lengthStr='+length;
			  eval(_cbreference); // callback to categories control
			}
		}
  }
}

function HorizontalCategoriesControl_Reload_Wrapped(_containerClientID, _menuID, _cbreference)
{
	var args = 'Action=ReloadMenu';
	eval(_cbreference);
}

function HorizontalCategoriesControl_CalculateAvailableWidth(_control, _width)
{
	var controlWidth = _width || _control.clientWidth || _control.offsetWidth;
	var availableWidth;
	var SplitterControl = document.getElementById("Splitter1");
	if(SplitterControl != null && SplitterControl.clientWidth != null)
	{
		if(SplitterControl.clientWidth < controlWidth)
			availableWidth = SplitterControl.clientWidth - 52 - 160;//allow an extra 52px for the "more" item
		else
			availableWidth = controlWidth - 52 - 160;//allow an extra 52px for the "more" item
	}
	else
	{
		var BubbleControl = document.getElementById("KGBubbleControl1");
		if(BubbleControl != null)
		{
			if(BubbleControl.offsetWidth < controlWidth)
				availableWidth = BubbleControl.offsetWidth - 52 - 260;
			else
				availableWidth = controlWidth - 52 - 160;//allow an extra 52px for the "more" item
		}
		else
		{
			availableWidth = controlWidth - 52 - 160;//allow an extra 52px for the "more" item
		}
  }
  return availableWidth;
}

function HorizontalCategoriesControl_Resize_Wrapped(_width, _containerClientID, _menuID, _cbreference)
{
  var control = document.getElementById(_containerClientID); //the div containing the menu and bookmarks
  var menu = document.getElementById(_menuID);
  
  if (control != null && menu != null)
  {
		if (_width)
		  control.style.width = _width + 'px';
    var availableWidth = HorizontalCategoriesControl_CalculateAvailableWidth(control, _width);
    
    var args = 'Action=ResizeMenu';
    args += '|availableWidth='+availableWidth;
		eval(_cbreference); // callback to categories control
  }
}

function HorizontalCategoriesControl_MenuItemSelected_Wrapped(_sender, _eventArgs, _topLevelTopicId, _cbreference, _loggedInUser)
{
  if (window.CloseApplicationControl && m_applicationControlOpen && !m_appForceOpen)
  {
    CloseApplicationControl();
  }
  var currentLocation = window.location.href;
  //var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
  //var hostURLForRedirect = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
  if(m_bEditable)
  {
		globalCatClick = true;
	}
  var hostURLForRedirect;
  var currentPage;
  if(currentLocation.indexOf("orderSuccessful") > 0)
  {
    currentPage = currentLocation.substring(currentLocation.indexOf("orderSuccessful"));
    hostURLForRedirect = currentLocation.substring(0, currentLocation.indexOf("orderSuccessful"));
  }
  else if (currentLocation.indexOf("orderFailed") > 0)
  {
    currentPage = currentLocation.substring(currentLocation.indexOf("orderFailed"));
    hostURLForRedirect = currentLocation.substring(0, currentLocation.indexOf("orderFailed"));
  }
  else
  {
    currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
    hostURLForRedirect = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
  }
  
  var item = _eventArgs.get_item();
  var cb = document.getElementById('CategoriesTreeCheckbox');
  
  if(item.Text == "" || item.Text == undefined)
  {		
		return;
	}
	
	if (isAuthenticated() == true)
  {
    var userID = WM_readCookie('UserID');
	  WM_setCookie('User' + userID + '_category', item.ID, m_catCookieExpiration);
	}
  
  if(currentPage.toLowerCase().indexOf('apphome.aspx') == -1 &&
  (currentPage == 'Home.aspx' || currentPage == 'home.aspx' || currentPage.match('home') == 'home' || currentPage.match('Home') == 'Home'))
	{
	  if (window.Global_SemanticTreeHolderID && !Global_SemanticTreeHolderID)
		{
			//NavigationControl not ready, switch tabs calls will cause problems
			_eventArgs.set_cancel(true);
			return;
		}
		if(m_bEditable == true)
			SwitchEditableFlag();
		var homeLinkClicked = 0;
		
		globalFeaturedCategory = "true";
		
		var keys = 'Topics_SelectedTopicName|Topics_SelectedTopicGroupId|Topics_CategoryJustClicked|IndexedDocListMode|ConceptTabbedView_SelectedTab|SelectedKnowdeSiblingInfo'
    var values = item.Text.replace('&','%26') + '|' + item.ID + '|true|Category|' + 'CS_' + _topLevelTopicId + '|';
    SetSessionProperty(keys, values, true);
    
		setGenesTabMode("Category");
		_sender.IsSelecting = true;
		ChangeTab("genes", "genes", true);		
		_sender.IsSelecting = false; // could set these further apart, but they're only used in the ChangeTab function atm.
		//  if move set to false, make sure you catch it in early returns
		// could pass it in to ChangeTab - but then there are lots of other calls to ChangeTab that don't need that parameter
		//TabContainerControl_CallbackDirection("genes");
		
		if(cb != null)
		{
			cb.disabled = false;
			HorizontalCategoriesControl_DisableCheckBox(cb);
			HorizontalCategoriesControl_OnCheckboxClick(cb, item);
		}

		// updates here may also need to go in hk.js HomeLinkClicked for clicking our top left icon
		//SetSessionProperty('ConceptTabbedView_SelectedTab', 'CS_' + _topLevelTopicId);
		// new default map will be load, clear old session
		//SetSessionProperty('SelectedKnowdeSiblingInfo', '');	
	  
		// reload the home page, otherwise redirect to home page
		if (homeLinkClicked == 0 && (currentPage.indexOf('home') > -1 || currentPage.length == 0))
		{
      if (item.ParentItem != null || item.ParentMenu.MenuId == HorizontalCategoriesControl_getBreadcrumbMenuID())
      {
        // the clicked item is in a submenu.  Show the breadcrumb trail
			  var args = 'Action=ShowBreadcrumbTrail';
		    eval(_cbreference); // callback to categories control
			}
			else
			{
			  // clear the breadcrumb trail
		    HorizontalCategoriesControl_UpdateBreadcrumbTrail("");
		  }
      
			//draw the tree
			//KGNavigationControl_SwitchTabs('CS_' + _topLevelTopicId, item.Text);
			//KGNavigationControl_TreeNavBarRePopulate();
		  
			// select the Category Home tab
			globalIndexedDocsPageLoaded = false;
			//KGTabbedWindowsControl_CallbackTrigger("CategorySelected", null, false);
	    
			/*SetSessionProperty('KGMapViewCollapsed',false);
			var mapViewCollapsed = PaneBStatus();
			if (mapViewCollapsed == true) // map view is not visible - open the splitter
				DoExpandMapViewPane();*/
		}
		else
		{ 
			SetSessionProperty('ConceptTabbedView_SelectedTab', 'Personal')
			KGNavigationControl_SwitchTabs('Personal');
			var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
			if(currentPage == 'Home.aspx' || currentPage == 'home.aspx' || currentPage.match('home') == 'home' || currentPage.match('Home') == 'Home')
			{
				SetSessionProperty('Topics_SelectedTopicName', item.Text.replace('&','%26'));
				SetSessionProperty('Topics_SelectedTopicGroupId', item.ID);
				SetSessionProperty('Topics_CategoryJustClicked', true);
		
				KGNavigationControl_TreeNavBarRePopulate();
				globalIndexedDocsPageLoaded = false;
			  //KGTabbedWindowsControl_CallbackTrigger("CategorySelected", null, false);
				/*SetSessionProperty('KGMapViewCollapsed',false);
				var mapViewCollapsed = PaneBStatus();
				if (mapViewCollapsed == true) // map view is not visible - open the splitter
					DoExpandMapViewPane();*/
					
				// clear the breadcrumb trail
		    HorizontalCategoriesControl_UpdateBreadcrumbTrail("");
			}
			else
			{
				window.location = hostURL + 'home.aspx';
			}

		}
		// delete history after category change
		if(window.KGButtonToolbar_IndexedDocListLoaded)
			KGButtonToolbar_IndexedDocListLoaded(true);
	  
	  // update tab selection
	  if (_sender.SelectedItem != null)
	  {
			// update tab selection
			// UNHIGLIGHT 
			HorizontalCategoriesControl_Unhighlight(_sender);
		  
		  // HIGHLIGHT 
		  HorizontalCategoriesControl_HighlightItem(item);
		  
			//UPDATE TAB & RENDER
			_sender.SelectedItem = item; // selected item should be the actual selected item not the top level item, otherwise unhighlight doesn't deselect the children, also sign in sign up could get the selected item id as "more"
			_sender.render();
	  }
	}
	else
	{
		globalFeaturedCategory = "true";
		var item = _eventArgs.get_item();
		if(item.ID != -1)
		{
		  if(currentPage.toLowerCase().indexOf("apphome.aspx") == -1)
			  window.location = hostURLForRedirect + 'home.aspx?category=' + item.ID;
			else
			  window.location = hostURLForRedirect + 'AppHome.aspx?category=' + item.ID;
		}
		else
		{
		  SetSessionForHomeClick();
			if (_loggedInUser == 'False')
			{
				// hide semantic tree, would be deal with in server side
			}
			else
				SetSessionProperty('Home_Link_Clicked', 'true');
			window.location = hostURLForRedirect + 'home.aspx';
		}
	}	
}

function HorizontalCategoriesControl_MenuItemMouseOver(_sender, _eventArgs)
{
  var menuItem = _eventArgs.get_item();
  if (menuItem.getItems().length > 0)//if the item has children to show
  {
    var menuGroupID = HorizontalCategoriesControl_GetMenuItemElementID(menuItem);
    HorizontalCategoriesControl_ShowMenuGroup(menuGroupID, 0, menuItem.ParentIndex);
  }
  
  if (menuItem.Text != "Home" && menuItem.Text != "more" && menuItem.ParentItem == null)
  {
		if (window.event)
		{
			// dont process any further if 'help' is switched off
			var performBubble = document.getElementById("KGBubbleControl1_BubbleVisibilityContainer");
			if(performBubble)
			{
				if(performBubble.style.display == "none")
				{
					return;
				}
			}else
			{
			  return;
			}	
			
			if(window.HideBubble)
			{
			  // find element & its position to pass to the help bubble
			  var targ = event.target||event.srcElement;
			  var TopLeftPositionArray = findElementCoords(targ);
			  var BottomRightPositionArray = findBRElementCoords(targ);
			  var borderOffset = 'false';
			  // updateBubblePosition
			  updateBubblePosition(TopLeftPositionArray, BottomRightPositionArray, borderOffset, 'false');
			  if (menuItem.Text == "Semantic Tree")
			  {
				  HoverTimerForBubble = setTimeout("UpdateBubble('Show Semantic Tree Other')",globalHoverUpdateTimerDelay);
			  }
			  else
			  {
				  HoverTimerForBubble = setTimeout("UpdateBubble('Category Hover')",globalHoverUpdateTimerDelay);
			  }
			}
		}
		else
		{
		  	// dont process any further if 'help' is switched off
			var performBubble = document.getElementById("KGBubbleControl1_BubbleVisibilityContainer");
			if(performBubble)
			{
				if(performBubble.style.display == "none")
				{
					return;
				}
			}
			else
			{
			  return;
			}
			//debugger;
			// find element & its position to pass to the help bubble
			var menu = document.getElementById("HorizontalCategoriesControl1_Menu");
      var menuitems = menu.getElementsByTagName("td");
      var length = 0;// = menuitems[menuItem.get_index()].clientWidth 
      for(k = menuItem.get_index(); k >= 0; k--)
      {
       length += menuitems[k].clientWidth;
      }
			var TopLeftPositionArray = new Array();
      TopLeftPositionArray[0]= length + _sender.element.offsetLeft;
      TopLeftPositionArray[1]= _sender.element.offsetTop + _sender.element.offsetHeight;

			var BottomRightPositionArray = TopLeftPositionArray
			var borderOffset = 'false';
			// updateBubblePosition
			updateBubblePosition(TopLeftPositionArray, BottomRightPositionArray, borderOffset, 'false');
			if (menuItem.Text == "Semantic Tree")
			{
				HoverTimerForBubble = setTimeout("UpdateBubble('Show Semantic Tree Other')",globalHoverUpdateTimerDelay);
			}
			else
			{
				HoverTimerForBubble = setTimeout("UpdateBubble('Category Hover')",globalHoverUpdateTimerDelay);
			}
		}
  }
}


function HorizontalCategoriesControl_MenuItemMouseOut(_sender, _eventArgs)
{
  clearTimeout(HoverTimerForBubble);
  if(window.HideBubble)
  {
    globalHideBubbleTime = setTimeout("HideBubble('true');", globalHoverUpdateTimerDelay);
  }
}

function HorizontalCategoriesControl_CallbackDone_Wrapped(_args, _context, _thisClientID)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
 
   
  var argsSplit = _args.split('[@|@]');
  var action = argsSplit[0];
  switch (action)
  {
    case "RenderMenu":
    case "ResizeMenu":
    case "ReloadMenu":
      globalHCCRenderComplete = true;
      HorizontalCategoriesControl_UpdateMenu(argsSplit[1]);
      m_readyForResize = true;
      if (action == "RenderMenu")
      { // incase a breadcrumb trail has been loaded and is still hidden. We only need this in the initial render
        HorizontalCategoriesControl_ShowLoadedBreadcrumbTrail();
      }
    break;
    case "ShowBreadcrumbTrail":
      HorizontalCategoriesControl_UpdateBreadcrumbTrail(argsSplit[1]);
      break;
    case "MoveSubCommunitySpace":
      // check for exceptions
      if (_args.indexOf("Exception") == 0 || _args.length == 0)
      {
        HorizontalCategoriesControl_CallbackError(_args, _context);
        return;
        // looking for indexOf == 0 instead of > -1 incase it's genuine html that happens to contain 'Exception' in there
        // e.g. a user called "... Exceptional ..." 
      }
      HorizontalCategoriesControl_HandleMoveCalbackDone(argsSplit[1]);
      break;
  }
}

function HorizontalCategoriesControl_CallbackError(_args, _context)
{
  var alertMessage = "The HorizontalCategoriesControl encountered an error. \n\n" + _args;
  alert(alertMessage);
}
		
function HorizontalCategoriesControl_GetBreadbin()
{
  var breadbinId = HorizontalCategoriesControl_GetBreadbinId();
  return document.getElementById(breadbinId);
}

function HorizontalCategoriesControl_HideBreadcrumbTrail(breadbin)
{
  // set display none - can still get it back if we need to, unless/until it gets clears
  // don't need to pass in breadbin
  if (!breadbin)
    breadbin = HorizontalCategoriesControl_GetBreadbin();
    
  if (breadbin)
  {
    breadbin.style.display = "none";
    
    // move the genes tab content up
    var genesTab = document.getElementById("TCC_genes");
    if (genesTab)
      genesTab.style.borderTop = "solid 20px white";
      // can't do this with css - see comment in HorizontalCategoriesControl_ShowLoadedBreadcrumbTrail
  }
}

function HorizontalCategoriesControl_ShowLoadedBreadcrumbTrail(breadbin)
{
  // set display - just showing one that we've already loaded, only if there is one 
  // don't need to pass in breadbin
  if (!breadbin)
    breadbin = HorizontalCategoriesControl_GetBreadbin();
    
  var breadcrumbMenu = HorizontalCategoriesControl_GetBreadcrumbMenu();
  // test whether the breadcrumb menu has been loaded
  // note it could be loaded by clicking an item; or it could be loaded (but hidden) in the initial load if there was a category in the query string
  //    so it's better to actually check the menu rather than trying to set a variable to test it
  if (breadcrumbMenu && breadcrumbMenu.element && breadcrumbMenu.element.innerHTML != "" && breadcrumbMenu.get_items().get_length() > 0)
  {
    // show the breadcrumbs
    breadbin.style.display = "block";
    
    // move the genes tab content down
    var genesTab = document.getElementById("TCC_genes");
    if (genesTab)
      genesTab.style.borderTop = "solid 42px white";
      // can't use css classes because there's another TabContainerShown/Hidden class for the tab
      // can't set 2 classes for the tab and update this one because in some places the class gets overwritten (className = "TabContainerShown")
      //    if I changed all those to 'replace', would have to hope no one added another in future
      //genesTab.className.replace("TabUnderBreadcrumbs", "TabUnderHcc");
  }
}

function HorizontalCategoriesControl_UpdateBreadcrumbTrail(_args)
{
  // call with _args = "" to clear it
  var breadbin = HorizontalCategoriesControl_GetBreadbin();
  if (breadbin) 
  {
    var menu = HorizontalCategoriesControl_GetBreadcrumbMenu();
    menu.Hide(); 
      // sometimes there's an ExpandGroup timeout set on the menu, so it calls ComponentArt_Menu_ExpandGroup after the menu's been written over here, and causes a runtime error 'ParentItemElement' is null
      // the timeout we need to clear is menu.ExpandTimeoutId (and probably menu.ExpandTimeoutGroupIndex) //clearTimeout(menu.ExpandTimeoutId);
      // but calling Hide clears those and more, incase there's anything else that could go wrong
    
  
    updateHolder(_args, breadbin);
    if (_args) // call with _args = "" to clear it
      HorizontalCategoriesControl_ShowLoadedBreadcrumbTrail(breadbin)
    else 
      HorizontalCategoriesControl_HideBreadcrumbTrail(breadbin);
  }
}

function HorizontalCategoriesControl_GetMenu()
{
  return eval(HorizontalCategoriesControl_getMenuID());
}

function HorizontalCategoriesControl_GetBreadcrumbMenu()
{
  return eval(HorizontalCategoriesControl_getBreadcrumbMenuID());
}

function HorizontalCategoriesControl_Unhighlight(menu)
{
  menu.SelectedItem.IsSelected = false;
	var tempSenderIterator = menu.SelectedItem;
	var hasSenderParent = new Boolean(true);
	while(hasSenderParent)
	{
		if(tempSenderIterator.ParentItem != null)
		{
			tempSenderIterator.ParentItem.IsSelected = false;
			tempSenderIterator = tempSenderIterator.ParentItem;
		}
		else
		{
			hasSenderParent = false;
		}
	}
	//need to render the menu after doing this (ComponentArt method)
	//but don't put it in this method, because in an item select, we unhighlight then rehighlight
	//  and don't want to call render twice 
}

function HorizontalCategoriesControl_HighlightItem(_item)
{
  _item.IsSelected = true;
	var tempItemIterator = _item;
	var hasItemParent = new Boolean(true);
	while(hasItemParent)
	{
		if(tempItemIterator.ParentItem != null)
		{
			tempItemIterator.ParentItem.IsSelected = true;
			tempItemIterator = tempItemIterator.ParentItem;
		}
		else
		{
			hasItemParent = false;
		}
	}
	//need to render the menu after doing this (ComponentArt method)
	//but don't put it in this method, because in an item select, we unhighlight then rehighlight
	//  and don't want to call render twice 
}

function HorizontalCategoriesControl_UpdateMenu_Wrapped(_args, _menuHolderClientID, _menuClientID)
{
  var caMenu = HorizontalCategoriesControl_GetMenu();
  caMenu.Hide(); // hide the existing menu to make sure any timeouts get cleared before the menu is written over
  clearTimeout(caMenu.PropertyCalculationTimeoutId);
    
	var holder = document.getElementById(_menuHolderClientID);
  updateHolder(_args, holder);
  var menu = document.getElementById(_menuClientID);
  menu.style.display = "inline";
  
  // if we do a show/hide here in the js instead of during the callback, it's easier to switch it back later
  //    e.g. if we change tabs and there isn't a callback to the categories control
  // so at the server we always show the selection (as long as selection is enabled)
  if (HorizontalCategoriesControl_IsShowSelection())
  {
    //HorizontalCategoriesControl_ShowSelection(); // shown by default
  }
  else
  {
    HorizontalCategoriesControl_HideSelection();
  }
}

function HorizontalCategoriesControl_IsShowSelection()
{
	// allow show which category is selected if we're on the home page and the genes tab is selected
	//var currentLocation = window.location.href;
	//var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
	//if (currentPage.indexOf('home') != -1 && globalVisibleTab.toLowerCase().indexOf('genes') != -1)
	
	// if we're not on the home page, selection is disabled for the menu at the server, so it doesn't matter whether we show or hide it, you still won't see it
	if (window.globalVisibleTab && globalVisibleTab.toLowerCase().indexOf('genes') != -1)
	  return true;
	else
    return false;
}

function HorizontalCategoriesControl_ShowSelection()
{
  var menu = HorizontalCategoriesControl_GetMenu();
  if (menu.SelectedItem && !menu.IsSelecting) // if a select is in progress, save some work rendering the menu, 
                         // since the selected item is already out of date and it'll be redone anyway in the select
  {
    HorizontalCategoriesControl_HighlightItem(menu.SelectedItem);
    menu.render();
  }
}

function HorizontalCategoriesControl_HideSelection()
{
  var menu = HorizontalCategoriesControl_GetMenu();
  HorizontalCategoriesControl_Unhighlight(menu);
  menu.render();
  // don't actually unselect it by changing the SelectedItem, this way we can put it back easily if you switch tabs
}

function updateHolder(_args, _holder)
{
	var cdatas = _args.split('<![CDATA[');
  
  if (_holder != null)
  {
	  _holder.innerHTML = _args;
	  
	  var z = 0;
	  for(z = 1; z < cdatas.length; z++)
	  {
		  var posStart = cdatas[z].indexOf('window');      
		  var posEnd = cdatas[z].lastIndexOf('}') + 1;
		  if(posStart > -1 && posEnd > -1)
		  {
		  	if (posEnd < posStart)
		  	{
		      posEnd = cdatas[z].lastIndexOf(']') + 1;
		      var jscript = cdatas[z].substring(posStart, posEnd);
			    if(jscript.length != 0)
			    {
			      eval(jscript);
			    }
		    }
		    else
		    {
			    var jscript = cdatas[z].substring(posStart, posEnd);
			    if(jscript.length != 0)
			    {
				    eval(jscript);
				    var posNameStart = jscript.indexOf('window');
				    var posNameEnd = jscript.indexOf('=');
				    if(posNameStart > -1 && posNameEnd > -1)
				    {
				      var functionName = jscript.substring(posNameStart, posNameEnd);
				      eval(functionName+'()');
				    }
			    }
			  }
		  }
	  }
	}
}

function HorizontalCategoriesControl_ProcessCallBackError_Wrapped(_categoriesControlId)
{
  try
  {
    var holder = document.getElementById(_categoriesControlId);
    if (holder != null)
        holder.innerHTML = 'Exception occurred.';
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function HorizontalCategoriesControl_DisableCheckBox_Wrapped(_checkbox, _menu)
{ 
  // update client template to make checkbox checked/unchecked
  if (_menu && _menu.ClientTemplates)
  { 
    var clientTemplate = _menu.ClientTemplates[0][1];
    if (clientTemplate)
    {
      if (_checkbox.disabled && clientTemplate.indexOf('display:none') == -1)
        _menu.ClientTemplates[0][1] = clientTemplate.replace('display:block','display:none');
      if (!_checkbox.disabled && clientTemplate.indexOf('display:none') > -1)
        _menu.ClientTemplates[0][1] = clientTemplate.replace('display:none','display:block');
    }
  }
}

function HorizontalCategoriesControl_ConfigureClicked(e, _itemID)
{
  CancelBubble(e);
  
  var strID = _itemID + "";
  KGPrivateSpaceAdminControl_OpenPrivateSpace(strID);
}

function HorizontalCategoriesControl_ShowMenuGroup(_menuGroupID, _iteration, _parentIndex)
{
  if (_iteration == null)
    _iteration = 0;
  else
    _iteration++;
  
  // get the menu group container
  var menuGroup = document.getElementById(_menuGroupID);
  if (menuGroup == null && _iteration <= 10)
  {
    // wait until it gets shown
    setTimeout("HorizontalCategoriesControl_ShowMenuGroup('" + _menuGroupID + "', " + _iteration + ", " + _parentIndex + ")", 100);
  }
  else if (_iteration > 10)
  {
    // this prevents the timeout from looping indefinitely if something goes wrong
    return;
  }
  else
  {
    // ensure the container is the correct size
    menuGroup.parentNode.style.height = menuGroup.clientHeight + 2 + 'px';
    menuGroup.parentNode.style.width = menuGroup.clientWidth + 2 + 'px';
    //debugger;
    if (navigator.appName != "Microsoft Internet Explorer" && _parentIndex == -1)
    {
			if(PanesAreSplit())
			{
				var paneTop = document.getElementById("Splitter1_pane_0");
				if(paneTop != null)
					menuGroup.parentNode.style.top = parseInt(paneTop.style.height.replace("px","")) + parseInt(menuGroup.parentNode.style.top.replace("px","")) + menuGroup.parentNode.offsetTop + 25;
			}
			else
			{
				menuGroup.parentNode.style.top = parseInt(menuGroup.parentNode.style.top.replace("px","")) + menuGroup.parentNode.offsetTop + 25;
			}
    }
  }
}

// finds the DOM element id for a component art menuItem object
function HorizontalCategoriesControl_GetMenuItemElementID(_menuItem)
{
  var indexArray = new Array();
  indexArray.push(_menuItem.get_index());
  
  while(_menuItem.ParentItem != null)
  {
    _menuItem = _menuItem.ParentItem;
    indexArray.push(_menuItem.get_index());
  }
  
  var groupId = _menuItem.ParentMenu.MenuId;
	var menuGroup = document.getElementById(groupId);
  var menuitems = menuGroup.getElementsByTagName("td");
  
  var menuItemElement = menuitems[indexArray[indexArray.length-1]];// get the menuItemElement at the index position given by the last array item
  groupId = "G" + menuItemElement.id;// get the id for the menuGroup that belongs to this menuItem
  indexArray.pop();// remove the last array item    

  while (indexArray.length > 0)
  {
  	var menuGroup = document.getElementById(groupId);// get the menuGroup
    var menuitems = menuGroup.getElementsByTagName("nobr");// only one of these tags per menuitem (there are additional tds if a menu item has children)

    var menuItemElement = menuitems[indexArray[indexArray.length-1]];// get the menuItemElement at the index position given by the last array item
    
    // the dom nesting is different for items with children an those without.
    // first check the parentNode for the item id, then check higher up.
    menuItemId = menuItemElement.parentNode.id || menuItemElement.parentNode.parentNode.parentNode.parentNode.id
    groupId = "G" + menuItemId;// get the id for the menuGroup that belongs to this menuItem
    indexArray.pop();// remove the last array item    
  }

  return groupId;
}

// the user clicked an up/down arrow to reorder the subcategories
function HorizontalCategoriesControl_MoverClick(_itemID, _dirn, _btn, e)
{
  try
  {
    CancelBubble(e);
    
    if (_btn.className.indexOf("Grey") > -1) // button is disabled, className is set to MoveUpGrey or MoveDownGrey
      return; 
    // the button still has onclick set even if it's grey and disabled - otherwise we need to update the onclick function sometimes when we reorder
    // and CancelBubble for grey button is good
      
    // get the item
    var menu = HorizontalCategoriesControl_GetMenu();
    var item = menu.FindItemById(_itemID);
    
    // double check it's moveable
    var oldPos = item.get_index();
    if (_dirn == "up" && oldPos == 0)
      return;
    else if (_dirn == "down" && oldPos == item.ParentItem.get_items().get_length())
      return;
    
    CollapseSubItems(item, menu, e);
    
    // life is easier if we always move something down, so we only need to keep track of the groupId(=item Id)
    //  - if the user clicked up, it's equivalent to clicking down on the item above
    var downItem;
    if (_dirn == "down")
      downItem = item;
    else if (_dirn == "up")
      downItem = HorizontalCategoriesControl_GetItemMovingDown(item);
    var groupId = downItem.GetProperty("ID");
    
    // move it ont ohe client first
    HorizontalCategoriesControl_MoveItemDownOnClientOnly(downItem, e);
    
    //fire callback
    //  callbacks might not reach the server in the expected order, so use the CategoriesMovesHistory object
    globalCategoriesMovesHistory.AddMove(groupId);
    var args = "Action=MoveSubCommunitySpace|MoveInfo=" + globalCategoriesMovesHistory.ToString();
    HorizontalCategoriesControl_CallbackTrigger(args);
  }
  catch(ex)
  { // try catch means don't fire the callback if something goes wrong
    alert("An exception occurred in the script. Error name: " + ex.name + ". Error message: " + ex.message); 
  }
}

function HorizontalCategoriesControl_GetItemMovingDown(_itemMovingUp)
{
  var pos = _itemMovingUp.get_index() - 1;
  return _itemMovingUp.ParentItem.Items()[pos];
}

function HorizontalCategoriesControl_MoveItemUpOnClientOnly(item)
{
  var downItem = HorizontalCategoriesControl_GetItemMovingDown(item);
  HorizontalCategoriesControl_MoveItemDownOnClientOnly(downItem);
}
    
function HorizontalCategoriesControl_MoveItemDownOnClientOnly(item, e)
{
  // updates how it looks on the client, but doesn't fire a callback

  var oldPos = item.get_index();
  var newPos = oldPos + 1;
  var parentItem = item.ParentItem; 
    
  // update the ComponentArt control/////////////////////////////
  var parentItems = parentItem.get_items();
  //    update the up/down arrows, if necessary
  if (oldPos == 0 || newPos == parentItems.get_length() - 1) // moved away from top or to the bottom
  {
    // for the CA - swap the clientTemplateIDs - so if you close the menu and reopen it it's swapped the greyed out arrows
    //    note - swap means we don't have to know what the templates are called here
    var otherItem = parentItem.Items()[newPos];
    
    var tempClientTemplateId = item.ClientTemplateId;
    item.ClientTemplateId = otherItem.ClientTemplateId;
    otherItem.ClientTemplateId = tempClientTemplateId;
  }
  //    move the item
  parentItems.insert(item, newPos); // don't remove it first - it makes CA throw an error if you move one then move another, the StorageIndex array goes wrong
  
  // render the changes///////////////////////////////////////////
  //    possible to call menu.render() - but it'll close all the sub-menus. 
  //    So either call render then reopen chain down to item's parent (I don't like the look of that)
  //    or update the UI without calling render (just a case of swapping 2 table rows)
  
  // update the UI without calling render
  var parentTable;
  try
  {
    var parentTableId = HorizontalCategoriesControl_GetMenuItemElementID(parentItem);
    parentTable = document.getElementById(parentTableId);
  }
  catch(ex)
  {// the HorizontalCategoriesControl_GetMenuItemElementID method might throw an error, if the menu's already closed
  }
  if (parentTable) // parent table might have been closed already
    SwapMoverTableRows(parentTable, oldPos, newPos)
}

function CollapseSubItems(_item, menu, e)
{
  // to change css class and close child items
  var itemElId = HorizontalCategoriesControl_GetMenuItemElementID(_item);
  if (itemElId.indexOf('G') == 0) // it's returning IDs starting with "G", which do usually exist, but the elements with the mouse out don't start with "G"
    itemElId = itemElId.substring(1);
    
  itemEl = document.getElementById(itemElId);
  ComponentArt_Menu_Support.ComponentArt_Menu_ItemMouseOut(itemEl, e);
  
  ComponentArt_Menu_Support.ComponentArt_Menu_CollapseGroup(menu, _item.StorageIndex);
}

function SwapMoverTableRows(_table, _oldPos, _newPos)
{
  var movingRow = _table.rows[_oldPos];
  var moveToRow = _table.rows[_newPos];  
  
  // handle the up and down arrows
  if (_oldPos == 0) // moving away from the top
  {
    // swap the class names for the up arrow - the one going to the top needs to be greyed out, the other doesn't
    SwapMoverProperties(movingRow, moveToRow, "MoveUp")
  }
  
  if (_newPos == _table.rows.length - 1) // moving to the bottom
  {
    // swap the class names for the down arrow - the one going to the bottom needs to be greyed out, the other doesn't
    SwapMoverProperties(movingRow, moveToRow, "MoveDown")
  }
  
  // swap the rows
  // _table.moveRow(oldPos, newPos); // is IE only 
  
  var movingRowClone = movingRow.cloneNode(true);
  var moveToRowClone = moveToRow.cloneNode(true);
  
  movingRow.parentNode.replaceChild(moveToRowClone, movingRow);
  moveToRow.parentNode.replaceChild(movingRowClone, moveToRow);
}

function SwapMoverProperties(_row1, _row2, _type)
{
  // we're relying on class names starting with _type (e.g. MoveUp, MoveUpGrey, MoveDownGrey)
  var mover1 = GetMoverFromParentEl(_row1, _type);
  var mover2 = GetMoverFromParentEl(_row2, _type);
    
  var tempClass = mover1.className;
  mover1.className = mover2.className;
  mover2.className = tempClass;
  
  var tempTitle = mover1.title;
  mover1.title = mover2.title;
  mover2.title = tempTitle;
}
    
function GetMoverFromParentEl(_parentEl, _type)
{
  // this works as long as the class names for the movers start with "MoveUp" or "MoveDown"
  var method = function(el){return (el.className.indexOf(_type) != -1);};
  var result = YAHOO.util.Dom.getElementsBy(method,null,_parentEl);
  return result[0];
}   

function HorizontalCategoriesControl_HandleMoveCalbackDone(_args)
{
  if (!_args || _args == "{}") 
    return;
  
  var retMsg = eval( '(' + _args + ')' );
  
  if (retMsg.Error == 'true')
  {
    var alertMessage = "Unfortunately Knowledge Genes was unable to save your changes due to an error.";
    alertMessage += "\n\n" + retMsg.Msg;
    alertMessage += "\n\nPlease reload the page.";
    alertMessage += "\nIf you continue to see this message, please contact our support team." ;
    alert(alertMessage);
  
    // undo the failed moves, they'll have been made on the client before the callback was fired
    var groupIds = retMsg.GroupIDs.replace(/,$/,'').split(','); // remove any final comma before splitting (there might not be one)
    var menu = HorizontalCategoriesControl_GetMenu();
    var item;
    for (var j=groupIds.length-1; j>=0; j--) // loop over them backwards to undo each change in order
    {
      item = menu.FindItemById(groupIds[j]);
      HorizontalCategoriesControl_MoveItemUpOnClientOnly(item)
    }
  }
  
  // clear the old ones from the history
  // do this even if there was an error, we won't use them again
  if (retMsg.HandledIndex)
  {
    globalCategoriesMovesHistory.RemoveToIndex(retMsg.HandledIndex);
  }
}

// object to store a history of the moves made when reordering sub categories
// along with an index to keep them in order and inline with the server
// because callbacks might not hit the server in the right order, so:
//  send the whole history back to the server in each callback (using the ToString method)
//  at the server, compare the last history index with an 'expectedIndex' session property (Page.Session["CategoriesMoveIndex"])
//    if it's the same, just do the last move, the same as normal, then increment 'expectedIndex'
//    if it's bigger, it means the callback has arrived out of order. So do all the moves from 'expectedIndex' to the end, and update 'expectedIndex'
//    if it's smaller, it means we've already handled it because a later callback arrived first, so do nothing
//  in callbackdone, clear the handled moves out of the history so it doesn't get too big
function CategoriesMovesHistory()
{
  this.Moves = new Array();
  this.MoveIndex = 0; // the index of the next move to be added - this should NEVER go down (but gets cleared when the page reloads, as does the session property)
  
  this.AddMove = function(_groupId)
  {
    var move = new CategoriesMove(this.MoveIndex, _groupId);
    this.Moves.push(move);
    this.MoveIndex++;
  }
  
  // remove all entries up to and including index
  //    shift removes the first entry - works because the array is always sorted by index
  this.RemoveToIndex = function(_index)
  {
    while (this.Moves[0] && this.Moves[0].Index <= _index)
      this.Moves.shift(); 
  }
  
  // returns each (comma separated) move separated by @
  // regex removes the final '@'
  this.ToString = function()
  {
    var result = '';
    for (j in this.Moves)
    {
      result += this.Moves[j].ToString() + '@'; 
    }
    result = result.replace(/@$/,''); 
    return result;
  }
}

// 'Move' object stores info about a move the user made to reorder the sub categories
function CategoriesMove(_index, _groupId)
{
  this.Index = _index;
  this.GroupId = _groupId;
  
  // returns comma separated values
  this.ToString = function()
  { 
    return this.Index + ',' + this.GroupId;
  }
}


// JScript File

m_currentTextIndex = 0;

var m_bblCookieExpiration = 8760; // cookie expiration date in hours from current time. 8760 = 1 year
var m_bblStarted;
BubbleContent = new Array();
BubbleContent2 = new Array();
m_currentTextIndex = 0;
m_BubbleTimeOutID = null;


// KGBubbleControl_CallbackTrigger is defined in the code behind
function KGBubbleControl_CallbackTrigger_Wrapped(_args, _callbackScript)
{
  var args;
  if (_args && _args.constructor && _args.constructor.toString().indexOf("Array") > -1)
    //This is a hack until the map editing help is moved into a model
    args = 'Action=' + _args[0] + "|key=" + _args[1] + "|params=" + _args[2];
  else
  {
    args = 'Action=' + _args; // + "|params=" + _params; 
  }
  
  if(args.length > 0) // Otherwise the callback code will throw an exception
  {
    eval(_callbackScript);    
  }
}

function KGBubbleControl_CallbackDone(_args, _context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  // if the string "Exception:" occurs then something has gone wrong
  // zero length may occur if the user has an empty (as opposed to null) text view
  if(_args.indexOf("Exception", 0) >= 0)
  {
    alert("AJAX Failure:\n\n" + _args);
    return;
  }

  BubbleContent.length = 0;  // reset the array
  BubbleContent = _args.split("|");
  if(BubbleContent[1])
		BubbleContent2 = BubbleContent[1].split("@@@");
 	else
 		BubbleContent2 = BubbleContent[0].split("@@@");
 	
 	var bubbleTextHolder = document.getElementById("KGBubbleControl1_iframeBubble");
 	bubbleTextHolder.innerHTML = BubbleContent2[0];
 	
 	globalBubbleFullText = BubbleContent2[1];
 	ShowBubble();
}
  			

function KGBubbleControl_CallbackError(_args, _context)
{
  alert(_args);
}

function ShowBubble()
{
	// hide 'help'
  var control = document.getElementById("KGBubbleControl1_HelpBubble");
  if (control)
  {
		if(globalBubbleBottom == "true")
		{
			control.style.visibility = "hidden";
			control.style.display = "inline-block";
			var Bubble = document.getElementById("KGBubbleControl1_HelpBubble");
			var BubblePadding = document.getElementById("KGBubbleControl1_HelpBubblePadding");
			Bubble.style.top = Bubble.style.top.replace("px","") - BubblePadding.clientHeight;
			control.style.visibility = "visible";
		}
		else
		{
			control.style.display = "block";
			control.style.display = "inline-block";
    }
    globalBubbleBottom = "false";
  }
  
  // hide the droplists for earlier IE versions
	if(navigator.appVersion.match("MSIE 7.0") != "MSIE 7.0" && navigator.appName == "Microsoft Internet Explorer")
		HideDropLists();
	
}

function HideBubble(_editHide)
{
	// hide 'help'
	if(m_bEditable == false || _editHide == 'true')
	{
		var control = document.getElementById("KGBubbleControl1_HelpBubble");
		if (control)
		{
		  if(navigator.appVersion.match("MSIE 7.0") != "MSIE 7.0" && navigator.appName == "Microsoft Internet Explorer")
		  {
		    var isKGSignInControlVisible = false;
		    if(window.KGSignInControl_IsControlVisible)
		    {
		      isKGSignInControlVisible = KGSignInControl_IsControlVisible();
		    }
		    var isKGSuggestionControlVisible = false;
		    if(window.KGSuggestionControl_IsControlVisible)
		    {
		      isKGSuggestionControlVisible = KGSuggestionControl_IsControlVisible();
		    }
			  if (control.style.display != "none" && !isKGSuggestionControlVisible && !isKGSignInControlVisible)
		      ShowDropLists();
	    }
	    control.style.display = "none";
		}
  }
}

function ShowBubbleContainer()
{
	// hide 'help'
  /*var control = document.getElementById("KGBubbleControl1_BubbleVisibilityContainer");
  if (control)
  {
    control.style.display = "inline-block";
  }*/
}

function HideBubbleContainer()
{
	// hide 'help'
  var control = document.getElementById("KGBubbleControl1_BubbleVisibilityContainer");
  if (control)
  {
    control.style.display = "none";
  }
}


function openBubbleInNewWindow()
{
  var control = document.getElementById("KGBubbleControl1_iframeBubble");
  if (control.src != null && control.src != "")
    var helpWindow = window.open(globalBubbleFullText);
  else
  {
    var helpWindow = window.open();
    helpWindow.document.write(globalBubbleFullText);
  }
}

// JScript File
  /* when resizing, document.detachEvent doesn't seem to work - it only picks up the mouseup 
  if you're over the control that received the mousedown, even if the function's 
  been attached to document.
  To make the resize code work with Firefox, it may be worth looking at:
  http://www.webreference.com/programming/javascript/mk/column2/*/
var resizeData = null; //This gets a value as soon as a resize starts
var resizeInnerEl = null; // for Firefox when inner table's content can be large elements

function resizeObject() 
{
	this.el = null; //pointer to the object
	this.grabx = null;     //Some useful values
	this.graby = null;
    this.width = null;
	this.height = null;
	this.left = null;
	this.top = null;
}

function resizeMouseDown(e,_id) 
{
    e = e || window.event;
      
    var el = document.getElementById(_id);
    //grab the current position and save it
	if (el == null) 
	{
		resizeData = null;
		return;
	}		

	resizeData = new resizeObject();
	resizeData.el = el;
	resizeData.x = e.clientX;
	resizeData.y = e.clientY;
	resizeData.width = el.offsetWidth;
	resizeData.height = el.offsetHeight;
	resizeData.left = el.offsetLeft;
	resizeData.top = el.offsetTop;
	
	if(_id == 'KGHelpControlID1')
	{
	  resizeInnerEl = document.getElementById(_id + '_Table');
	  if(resizeInnerEl != null)
	  {
	    resizeInnerEl.width = resizeData.width;
	    resizeInnerEl.height = resizeData.height;
	  }
	}
	
	// Attach the events to the document so it doesn't pick up any other such calls until it's finished
    document.onmousemove = resizeMouseMove;
    document.onmouseup = resizeMouseUp;
    
    CancelBubble(e);

    document.onselectstart = new Function("return false");
}

function resizeMouseMove(e)
{
  e = e || window.event;
  //only resize widthways if we're above the minimum
  if ( resizeData.width + (e.clientX - resizeData.x) > 410 )
  {
    resizeData.el.style.width = resizeData.width + (e.clientX - resizeData.x) + "px";
  }
  resizeData.el.style.height = resizeData.height + (e.clientY - resizeData.y) + "px";
  
  
  if(resizeInnerEl != null)
  {
    if ( resizeData.width + (e.clientX - resizeData.x) > 410 )
    {
      resizeInnerEl.width = resizeData.width;
    }
    resizeInnerEl.height = resizeData.height;
  }
	
  CancelBubble(e); 
}

function resizeMouseUp(e)
{
  e = e || window.event;
  if (resizeData != null) 
  {
 	// Update the session variable
    SetSessionProperty(resizeData.el.id + 'Position',resizeData.el.style.cssText);
 	resizeData = null;
  }

  // Stop capturing events
  document.onmousemove = null;  
  document.onmouseup = null;
  
  CancelBubble(e);  
}


/* Control dragging code from http://www.brainjar.com/dhtml/drag/, 24/04/08 */
/* JPC 05/08/08: had to add some extra code for when pointer moved over iframe during drag */
// Determine browser and version.
function Browser() 
{
  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) 
  {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) 
  {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) 
  {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

var browser = new Browser();

// Global object to hold drag information.
var dragObj = new Object();
dragObj.zIndex = 0;

function dragStart(e, id) 
{
  e = e || window.event;
  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id)
   dragObj.elNode = document.getElementById(id);
  else 
  {
    dragObj.elNode = e.target || e.srcElement;

    // If this is a text node, use its parent element.
    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  // Get cursor position with respect to the page.

  if (window.scrollX)
  {
    x = e.clientX + window.scrollX;
    y = e.clientY + window.scrollY;
  }
  else
  {
    x = e.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = e.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }

  // Save starting positions of cursor and element.
  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = GetPixelLeft(dragObj.elNode);
  dragObj.elStartTop   = GetPixelTop(dragObj.elNode);
  startDifferenceX = dragObj.cursorStartX - dragObj.elStartLeft;
  startDifferenceY = dragObj.cursorStartY - dragObj.elStartTop;

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

  // Update element's z-index.
  dragObj.elNode.style.zIndex = 500;//++dragObj.zIndex;

  // Capture mousemove and mouseup events on the page.
  if (document.addEventListener)
  {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    document.body.addEventListener("mouseout",   testMouseOut, true);
    e.preventDefault();
    if(window.globalShowingWebDoc && !globalShowingWebDoc) //can't attach events to web doc iframe because the src has a different domain
    {
      document.getElementById("HelpFrame").contentWindow.document.documentElement.addEventListener("mousemove", frameGo, true);
      document.getElementById("HelpFrame").contentWindow.document.documentElement.addEventListener("mouseup",   dragStop, true);
    }
  }
  else
  {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    document.body.attachEvent("onmouseout",   testMouseOut);
    e.returnValue = false;
    if(window.globalShowingWebDoc && !globalShowingWebDoc)
    {
      document.getElementById("HelpFrame").contentWindow.document.documentElement.attachEvent("onmousemove", frameGo);
      document.getElementById("HelpFrame").contentWindow.document.documentElement.attachEvent("onmouseup",   dragStop);
    }
  }
  CancelBubble(e);
}

function testMouseOut(event)
{
  var targ = event.target || event.srcElement;
  if (targ == document.body)
  {
    dragStop();
  }
  else if (window.globalShowingWebDoc && globalShowingWebDoc)
  { // if the mouse goes over a web doc, hide the iframe
    // because iframe for web doc won't register mouse up so drag won't stop
    var toEl = event.relatedTarget || event.toElement;
    if (toEl && toEl.id == "HelpFrame")
    {
      m_HelpFrame.style.visibility = 'hidden';
    }
  }
}

function frameGo(event)
{
  var x, y;
  // Get cursor position with respect to the page.
  if (window.scrollX)
  {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }
  else
  {
    x = event.clientX + document.body.scrollLeft
      + document.documentElement.scrollLeft;
    y = event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop + m_MapHelpBox.scrollTop;
  }

  // Move drag element by the same amount the cursor has moved.
  dragObj.elNode.style.left = (dragObj.elNode.offsetLeft+ x - startDifferenceX) + "px";
  dragObj.elNode.style.top  = (dragObj.elNode.offsetTop + y - startDifferenceY) + "px";
}

function dragGo(event) 
{
  var x, y;

  // Get cursor position with respect to the page.
  if (window.scrollX)
  {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }
  else
  {
    x = event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
    
  // Move drag element by the same amount the cursor has moved.
  dragObj.elNode.style.left =
    (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  =
    (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";
  }

function dragStop(event) 
{
	//debugger;
  // Stop capturing mousemove and mouseup events.
  if (document.removeEventListener)
  {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
    document.body.removeEventListener("mouseout",   testMouseOut, true);
    if(window.globalShowingWebDoc && !globalShowingWebDoc)
    {
      document.getElementById("HelpFrame").contentWindow.document.documentElement.removeEventListener("mousemove", frameGo, true);
      document.getElementById("HelpFrame").contentWindow.document.documentElement.removeEventListener("mouseup",   dragStop, true);
    }
    else if (window.m_HelpFrame)
    {
      m_HelpFrame.style.visibility = '';
    }
  }
  else
  {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
    document.body.detachEvent("onmouseout",   testMouseOut);
    if(window.globalShowingWebDoc && !globalShowingWebDoc)
    {
      document.getElementById("HelpFrame").contentWindow.document.documentElement.detachEvent("onmousemove", frameGo);
      document.getElementById("HelpFrame").contentWindow.document.documentElement.detachEvent("onmouseup",   dragStop);
    }
    else if (window.m_HelpFrame)
    {
      m_HelpFrame.style.visibility = '';
    }
  }
    // Update the session variable
  SetSessionProperty(dragObj.elNode.id + 'Position',dragObj.elNode.style.cssText);
  
  if (window.m_dragBox && m_dragBox.CurrentlyDragging)
  {
    KGDragStop(event);
  }
  
  // find x & y coords of all drop lists - hide list if there is an overlay.
	if(navigator.appVersion.match("MSIE 7.0") != "MSIE 7.0" && navigator.appName == "Microsoft Internet Explorer")
	{
		m_MapHelpBox = document.getElementById("KGHelpControlID1");
		 //If the control exists on the page
    if (m_MapHelpBox != null)
    {
			if(m_MapHelpBox.className != "OverlayPositionHidden")
			{
				// find elements x & y coords
				var elemCoords = findElementCoords(m_MapHelpBox);
				var elemCoordsAndWidth = m_MapHelpBox.clientWidth + elemCoords[0];
				var elemCoordsAndHeight = m_MapHelpBox.clientHeight + elemCoords[1];
			}
			// retrieve and hide all droplists.
			var droplist = document.getElementsByTagName("SELECT");
			for(var num=0;num<droplist.length;num++)
			{
				//only hide the visible boxes
				if(droplist[num].className == "list_dropList")
				{
					var dropCoords = findElementCoords(droplist[num])
					var dropCoordsAndWidth = droplist[num].clientWidth + dropCoords[0];
					var dropCoordsAndHeight = droplist[num].clientHeight + dropCoords[1];
					
					if(dropCoords != null && elemCoords != null && (dropCoords[0] >= elemCoords[0] || dropCoordsAndWidth >= elemCoords[0]) && (dropCoords[0] <= elemCoordsAndWidth || dropCoordsAndWidth <= elemCoordsAndWidth))
					{
						//overlays in the x-range
						if((dropCoords[1] >= elemCoords[1] || dropCoordsAndHeight >= elemCoords[1]) && (dropCoords[1] <= elemCoordsAndHeight || dropCoordsAndHeight <= elemCoordsAndHeight))
						{
							//overlays in the x & y ranges
							droplist[num].style.display = "none";
						}
						else
						{
							droplist[num].style.display = "inline";
						}
					}
					else
					{
						droplist[num].style.display = "inline";
					}
				}
			}
		}
	}

}

// KGHelpControl JScript File
var objectiveImgs=new Array(); 
objectiveImgs[0]='images/help/objectiveexample.png'; 
var m_helpCookieExpiration = 8760; 

var currentObjectiveImg = 0;
var m_HelpFrame = null;
var m_DockedHelpFrame = null;
var helpText;

var globalShowingWebDoc = false;
// if true then the docked control is full expanded to cover the whole bottom panel
var m_globalFullDocked = false;

var m_previousHighLightedPath = '';

//var m_bHelpFrameLoadSiblingKnowde = false;
//var m_bHelpFrameManualScroll = false;

//var m_helpFrameScrollTimeOut = null;


//var m_helpFrameHighlightColor = '#EAF4F7'; 
//var m_helpFrameHighlightBorderLeftStyle = '2px #A7A9E2 solid'; //8EA4DB A7A9E2
//var m_helpFrameHighlightBorderLeftPadding = '5';

var m_newTextViewWindow;
//var m_helpFrameScrollDelay = 50; // ms
//var m_helpFrameScrollMoreOnTopTimeOut;
//var m_dockedFrameScrollMoreOnTopTimeOut;

//var m_helpFrameLoadingDivTimeOut;

//var m_helpFrameCallbackStatus = 'none';


function KGHelpControl_CallbackTrigger_Wrapped(_key, _params, _callbackScript, _imgDockInPageID)
{
  //debugger;
  // Make sure we clear the contents of the document window
  /*if(_key != 'NewWindowTextView' && m_bHelpFrameLoadSiblingKnowde == false)
    ClearHelpFrame(false);
    
  globalShowingWebDoc = false;
  // show textview view mode option if in read mode
  // need to use set time out otherwise iframe height become 0 in Safari and Chrome
  if(m_bEditable == true)
    window.setTimeout('HideOrShowTextViewOptionDiv(false)',5);
  else
    window.setTimeout('HideOrShowTextViewOptionDiv(true)', 5);
    
  var MapHelpBox = document.getElementById("KGHelpControlID1");
  MapHelpBox.title = "Associated Text";
  
  var imgDockInPage = document.getElementById(_imgDockInPageID);
  if (imgDockInPage.style.display == "none")
    imgDockInPage.style.display = "";
  
  var args;
  //debugger;
  // Construct the callback arguments
  if(_key != null)
  { 
    args = 'key=' + _key + "|params=" + _params;
    
    if(args.length > 0)
    {
      m_helpFrameCallbackStatus = 'trigger';
      if(_key.indexOf('ReloadTextView') == -1)
      {
        // show loading div
        if(args.indexOf('LoadTrigger=Scrolling') == -1)//(m_bHelpFrameLoadSiblingKnowde == false)
        {
          if(m_helpFrameLoadingDivTimeOut != null)
          {
            clearTimeout(m_helpFrameLoadingDivTimeOut);
            m_helpFrameLoadingDivTimeOut = null;
          }
          m_helpFrameLoadingDivTimeOut = window.setTimeout("HideOrShowHelpControlLoadingDiv(true, 'Loading...')",10);
        }
      }
      // trigger the callback
      eval(_callbackScript);    
    }
  }*/
}
				  
function KGHelpControl_CallbackDone(_args, _context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  /*m_helpFrameCallbackStatus = 'done';
  
  m_HelpFrame = document.getElementById("HelpFrame");
  
  var action = '';
  if(_args.indexOf('[@|@]') != -1)
  {
    action = _args.substring(0, _args.indexOf('[@|@]'));
    _args = _args.substring(_args.indexOf('[@|@]') + 5);
  }
  
  if(action.indexOf('-ReloadTextView') != -1)
  {
    // edit mode textview
    var ids = _args.split('@');
    var controlId = ids[0];
    var content = _args.substring(controlId.length+1);
    var hccontainer = document.getElementById('KGHelpControlID1');
    var tvControl = document.getElementById('TextViewControlContent');
    if(tvControl != null && hccontainer != null)
    {
      //debugger;
      if (tvControl.childNodes.length == 2) //IE
      {
        tvControl.childNodes[0].style.height = '30px';
        tvControl.childNodes[1].outerHTML = content;
        
        tvControl.childNodes[1].style.height = (hccontainer.clientHeight - 75) + 'px';
        tvControl.childNodes[1].style.width = (hccontainer.clientWidth - 5) + 'px';
              
        m_textViewControlSpanFixedSize = 1;

      }
      else if (tvControl.childNodes.length == 4) //FF - counts carriage returns in html as textnodes
      {
        tvControl.childNodes[0].style.height = '30px';
        var container = document.getElementById('TextViewControlContent');

        //tvControl.childNodes[2].outerHTML = content;
        // not support outerHtml
        var tempElement = document.createElement("div");
        tempElement.style.overflow = 'auto';
        
        var start = content.indexOf('<');
        if(start > 0)
          content = content.substring(start);
        var end = content.lastIndexOf('>');
        if(end < content.length -1)
          content = content.substring(0, end + 1);
          
        tempElement.innerHTML = content;
        
        var root = null;
        for(var i=0; i<tempElement.childNodes.length; i++) 
        {
          if(tempElement.childNodes[i].nodeType == 1) 
          {
            root = tempElement.childNodes[i];
            root.style.display = 'block';
            
            if(container != null)
            {
              root.style.height = (hccontainer.clientHeight - 75) + 'px';
              root.style.width = (hccontainer.clientWidth - 5) + 'px';
              
              m_textViewControlSpanFixedSize = 1;
            }
            break;
          }
        }
        
        if(root)
          tvControl.replaceChild(root, tvControl.childNodes[2]);
                  
      }
      setTimeout("LoadTextView()",300);
      
    }
      HideOrShowHelpControlLoadingDiv(false);

      m_helpFrameCallbackStatus = 'none';
  }
  else
  { // read only text view
    if(_args.indexOf('|<TextViewInfo>|') != -1)
    {
      var values = _args.split('|<TextViewInfo>|');
      // set selected knowde id
      var ids = values[0].split('@');
      // get action key
      var actionKey = ids[0];
      var viewmode = ids[1];
      if(actionKey != 'NewWindowTextView')
      {
        // get old kgId
        var oldFrameKGID = m_strFrameSelectedKGID;
        // set view mode
        m_strFrameViewMode = viewmode;
        // set kgId
        m_strFrameSelectedKGID = ids[2];
        // knowdeID
        m_strFrameSelectedKnowdeDBID = ids[3];
        // use client Id for the moment
        m_strFrameSelectedKnowdeID = ids[4];
        var knowdeContexts = values[0].substring(ids[0].length + ids[1].length + ids[2].length + ids[3].length + ids[4].length + 5).split('||');
        m_strFrameSelectedKnowdeContext = knowdeContexts[0];
        m_strFrameCentreKnowdeContext = knowdeContexts[1];
        
        //alert(m_strFrameSelectedKnowdeID + '|' + m_strFrameSelectedKnowdeContext);
        
        if(oldFrameKGID != m_strFrameSelectedKGID || m_bHelpFrameLoadSiblingKnowde == false)
        {
          // kg changed
          ClearHelpFrame(false);
        }
        
        if(m_strFrameViewMode == "Full" && m_currentTextViewViewMode == m_strFrameViewMode)
        {
          // load all textviews
          HandleHelpFrameLoadAll(values[1], values[2]);
        }
        else if(m_strFrameViewMode == "Single" && m_currentTextViewViewMode == m_strFrameViewMode) 
        {
          // load single textview
          var content = values[2];
          var kndText = GetCurrentKnowdeTextForTextView(m_strFrameSelectedKnowdeID);
          if(kndText != '')
          {
            if(content == '')
            {
              content = GetDefaultTextViewContentWithTitle(m_strFrameSelectedKnowdeID, kndText, 1, m_noTextViewFoundContent);
            }else
            {
              content = TrimTickerSpans(content);
              if (content.indexOf(m_textViewTickerSelectionHighlightColor) > -1)
                content = ReturnUnhighlightedTickerText(content);
                
              // check whether it has an existing title, if not, add the title manually
              if(CheckTextViewHasTitle(m_strFrameSelectedKnowdeID, kndText, content) == false)
                content = WrapTextViewContentWithTitle(m_strFrameSelectedKnowdeID, kndText, content);
            }
         }

          m_HelpFrame.contentWindow.document.write("<html><head><base target='_blank'><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body class='PersonalisedScrollBar' style='overflow:scroll;'>");
          m_HelpFrame.contentWindow.document.write(content);
          m_HelpFrame.contentWindow.document.write("</body></html>");
           
          // Copy the text view to the docked window if it exists
          var dockedText = document.getElementById("DockedHelpWindow");
          
          if (dockedText != null)
          {
            dockedText.contentWindow.document.open();
            dockedText.contentWindow.document.write("");
            dockedText.contentWindow.document.close();

            dockedText.contentWindow.document.write("<html><head><base target='_blank'><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body class='PersonalisedScrollBar' style='overflow:scroll;'>");
            dockedText.contentWindow.document.write(content);
            dockedText.contentWindow.document.write("</body></html>");
          }

          // Store the 'actual' text incase the user wishes to dock the help
          helpText = content;
        }
      }
      else if(m_newTextViewWindow != null)
      {
        // get highlighted knowde context
        var knowdeContexts = values[0].substring(ids[0].length + ids[1].length + ids[2].length + ids[3].length + ids[4].length + 5).split('||');
        var strFrameSelectedKnowdeContext = knowdeContexts[0];

        // new window full load
        HandleNewWindowTextViewLoadAll(values[1], values[2], strFrameSelectedKnowdeContext);
        
      }
      
   }
   else
   { 
      // Make sure we clear the contents of the document window
      ClearHelpFrame();

      m_HelpFrame.contentWindow.document.write("<html><head><base target='_blank'><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body class='PersonalisedScrollBar' style='overflow:scroll;'>");
      m_HelpFrame.contentWindow.document.write(_args);
      //if (window.ReturnUnhighlightedTickerText && _args.indexOf(m_textViewTickerSelectionHighlightColor) > -1)
        //_args = ReturnUnhighlightedTickerText(_args);
      //m_HelpFrame.contentWindow.document.body.innerHTML = _args;  // Removed this because it was causing the lines of text to disappear in the text view - bug 4277
      m_HelpFrame.contentWindow.document.write("</body></html>");
       
      // Copy the text view to the docked window if it exists
      var dockedText = document.getElementById("DockedHelpWindow");
      
      if (dockedText != null)
      {
        dockedText.contentWindow.document.open();
        dockedText.contentWindow.document.write("");
        dockedText.contentWindow.document.close();

        dockedText.contentWindow.document.write("<html><head><base target='_blank'><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body class='PersonalisedScrollBar' style='overflow:scroll;'>");
        dockedText.contentWindow.document.write(_args);
        dockedText.contentWindow.document.write("</body></html>");
      }

      // Store the 'actual' text incase the user wishes to dock the help
      helpText = _args;
    }
    
    // hide loading div
    //if(m_helpFrameLoadingDivTimeOut != null)
    //{
      //clearTimeout(m_helpFrameLoadingDivTimeOut);
     // m_helpFrameLoadingDivTimeOut = null;
    //}
    //m_helpFrameLoadingDivTimeOut = window.setTimeout("HideOrShowHelpControlLoadingDiv(false)",20);
    HideOrShowHelpControlLoadingDiv(false);

    m_helpFrameCallbackStatus = 'none';
  }*/
    
}

function IsHelpControlOpen()
{
  m_MapHelpBox = document.getElementById("KGHelpControlID1");
  if (m_MapHelpBox != null)
  {
    if(m_MapHelpBox.className != "OverlayPositionHidden")
      return true;
  }
  return false;
}
  			
function KGHelpControl_CallbackError(_args, _context)
{
  m_helpFrameCallbackStatus = 'none';
  
  alert(_args);
}

function ToggleImage(e)
{
  var pic = document.getElementById('HelpExample');
  e = e || window.event;
  var targ = e.target || e.srcElement;
  switch (targ.id)
  {
    case 'ObjectiveHelp':
      // We'd want to get the list of images here, but for now they're hard coded at the beginning of the file
      
      // Cycle through the available images
      if (currentObjectiveImg < objectiveImgs.length - 1)
        currentObjectiveImg++;
      else
        currentObjectiveImg = 0;
      pic.src = objectiveImgs[currentObjectiveImg];
      break;
  }
}

function SetHelpStateCookie()
{
  // If the element is on the help page, we need to remember that it has been closed
  var path = window.location.pathname;
  var page = path.substring(path.lastIndexOf('/') + 1);
  if ((page == 'MapTabbedView.aspx' || page == 'Home.aspx' || page == '') && KGMapHelpStateSetting != null)
  {
    WM_setCookie('KGMapHelpState',KGMapHelpStateSetting, m_cookieExpiration); // reset expiry date
  }
}

var helpBoxWidth;
var helpBoxHeight;
var helpBoxTop;
var helpBoxLeft;

function MaximiseKGHelpControl(_helpBoxID, _maximiseBtnId)
{
//debugger;
// get the help box
  var helpBox = document.getElementById(_helpBoxID);
  
  // store the help box'x current width, height and positioning for a 'restore'
  helpBoxWidth = helpBox.style.width;
  helpBoxHeight = helpBox.style.height;
  helpBoxTop = helpBox.style.top;
  helpBoxLeft = helpBox.style.left;
  
  // Set the help windows new properties
  helpBox.style.width = document.body.clientWidth;
  helpBox.style.height = document.body.clientHeight;
  helpBox.style.top = "0";
  helpBox.style.left = "0";
  
  // change image and onclick handler
  document.getElementById(_maximiseBtnId).className = "RestoreButtonImage";
  document.getElementById(_maximiseBtnId).onclick = function(){RestoreKGHelpControl('KGHelpControlID1', _maximiseBtnId)}; 
  
  if(!globalShowingWebDoc && document.frames)
  { 
    // don't have permission to do this for web docs (iframe refers to another domain)
    // added for text view (TS bug 4787)
    //setTimeout('document.frames[\'HelpFrame\'].location.reload(true)', 1000); 
  }
  
  HelpFrameDivResize('HelpFrame'); // might need to load more textview because the width is now bigger
}

function RestoreKGHelpControl(_helpBoxID, _restoreBtnId)
{
//debugger;
  var helpBox = document.getElementById(_helpBoxID);
  
  // reset the old size and positioning
  helpBox.style.top = helpBoxTop;
  helpBox.style.left = helpBoxLeft;
  helpBox.style.width = helpBoxWidth;
  helpBox.style.height = helpBoxHeight;
  
  // reload iFrame: - this fixes the annoying 'line of text missing' bug
  // this will break the aggregate text view and partial loading
  //if(helpBox.title == "Associated Text")
    //document.frames['HelpFrame'].location.reload(true);
  
  // change image and onclick handler
  document.getElementById(_restoreBtnId).className = "MaximiseButtonImage";
  document.getElementById(_restoreBtnId).onclick = function(){MaximiseKGHelpControl('KGHelpControlID1', _restoreBtnId)}; 
  
  HelpFrameDivResize('HelpFrame');
  // make sure scroll to the right position - if it's the text view not a web doc
  if (!globalShowingWebDoc)
    window.setTimeout('SetupHelpFrameKnowdeTextViewDivs()',1000);
    
  if(!globalShowingWebDoc && document.frames)
  { 
    // don't have permission to do this for web docs (iframe refers to another domain)
    // added for text view (TS bug 4787)
    //setTimeout('document.frames[\'HelpFrame\'].location.reload(true)', 1000); 
  }
}


function OpenInNewWindowKGHelpControl()
{
  //debugger;
  var control = document.getElementById("HelpFrame");
  if (control.src != null && control.src != "")
    var helpWindow = window.open(control.src);
  else if(m_strFrameViewMode == "Full")
  {
    var helpWindow = window.open();
    m_newTextViewWindow = helpWindow;
    helpWindow.opener = window;
    helpWindow.document.write("<html><head><script language='javascript' type='text/javascript' src='JavaScript/Yahoo.js'></script><script language='javascript' type='text/javascript' src='JavaScript/KGHelpControl.js'></script><script language='javascript' type='text/javascript' src='JavaScript/TextView.js'></script><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet' /></head>");
    helpWindow.document.write("<body style='overflow:hidden;'><IFRAME id='NewWindowHelpFrame' frameBorder='0' width='100%' height='100%' onload='parent.NewWindowTextViewOnLoad(\"" + m_strFrameSelectedKGID + "\", \"" + m_strFrameSelectedKnowdeID + "\", \"" + m_strFrameSelectedKnowdeContext + "\")'></IFRAME>");
    helpWindow.document.write("<input type='hidden' id='NewWindowTextViewHiddenField' value='" + m_FrameUnLoadedKnowdeIdString + "' /><DIV id='NewWindowTextViewDiv' style='display:none'>" + control.contentWindow.document.body.innerHTML + "</DIV><div id='NewWindowTextViewLoadingDiv' style='width: 100%; top:0px; left:0px; position:absolute; display:block;'><table width=\"100%\"><tr><td align=\"center\"><br/><br/><br/><div class='NewTextViewWindowLoadingDiv'><br/><img src=\"Images/loadingbar.gif\" /> Loading, please wait ...</div></td></tr></table></div>");
    helpWindow.document.write("<KGCoreControls:KGHelpControl ID='KGHelpControl1' runat='server' Title = 'Hyperknowledge' DivPosType = 'absolute' ControlName='KGHelpControl' /> </body></html>");
    
  }else if(m_strFrameViewMode == "Single")
  {
    var helpWindow = window.open();
    m_newTextViewWindow = helpWindow;
    helpWindow.opener = window;
    helpWindow.document.write(control.contentWindow.document.body.innerHTML);
  }
}

function NewWindowTextViewOnLoad(_kgID, _knowdeID, _knowdeContext)
{
  //debugger;
  var frame = document.getElementById('NewWindowHelpFrame');
  var hiddenDiv = document.getElementById('NewWindowTextViewDiv');
  var hiddenField = document.getElementById('NewWindowTextViewHiddenField');
  var loadingDiv = document.getElementById('NewWindowTextViewLoadingDiv');
    
  var toloadDivs = '';
  var loadedDivs = '';
  if(frame != null && hiddenField != null && hiddenDiv != null)
  {
    toloadDivs = hiddenField.value;
    loadedDivs = hiddenDiv.innerHTML;
    
    frame.contentWindow.document.write("<html><head></head><body style='overflow: auto;'>" + loadedDivs + "</body></html>");

    if(toloadDivs != '' && window.opener != null)
    {
      // do callback to load all the unloaded text views
      var args = "|KGId=" + _kgID + '|KnowdeId=' + _knowdeID + '|KnowdePathContext=' + _knowdeContext + '|KnowdeTitle=|CentreKnowdePathContext=|KnowdeIdList=' + toloadDivs;
      args += "|LoadSiblingKnowde=true";
      args += "|KnowdeLoaded=false";
      args += "|ViewMode=Full";
      
      window.opener.KGHelpControl_CallbackTrigger('NewWindowTextView', args);
      
      if(loadingDiv != null)
        loadingDiv.style.display = 'block';
    }
    else
    {
      if(loadingDiv != null)
        loadingDiv.style.display = 'none';
      window.setTimeout('SetupNewWindowTextViewDivs("'+_knowdeContext+'")', 200);

    }
  }else
  {
    // delay 
    window.setTimeout('NewWindowTextViewOnLoad("' + _kgID + '", "' + _knowdeID + '", "' + _knowdeContext + '")', 1000);
  }
  
}

function SetupNewWindowTextViewDivs(_knowdeContext)
{
//debugger;
  var frame = document.getElementById('NewWindowHelpFrame');
  // scroll to the right place
      if(_knowdeContext != null && _knowdeContext != '')
      {
            var method = function(el){if(el.id == _knowdeContext) return true; return false;};
            //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,frame.contentWindow.document.body);  
            var frameDivs = YAHOO.util.Dom.getChildrenBy(frame.contentWindow.document.body,method);   
            if(frameDivs.length > 0)
            {
              frame.contentWindow.document.body.scrollTop  = frameDivs[0].offsetTop - 10;
            }
      }
}


function DockInPageKGHelpControl(_helpBoxID, _newTabBtn, _dockBtn, _maxBtn, _resizeDiv)
{
  /*if(globalSplitterSetting == "single" || globalHideIndexedDocs == true)
  {
     m_globalFullDocked = true;
  }

  if(document.getElementById("GreyDiv") != null)
  {
    purge(document.getElementById("GreyDiv"));
	document.getElementById("Form1").removeChild(document.getElementById("GreyDiv"));
  }
  document.getElementById("m_cookieDiv").className = "m_cookieDivHidden";
  document.getElementById("miniGlobe").className = "miniGlobe";
  var tabbedControlDiv = document.getElementById("KGTabbedWindowsControl1");
  tabbedControlDiv.style.width = "1300px";
  if(m_globalFullDocked  == true)
  {
    hkLastChild(tabbedControlDiv).style.width = "0px";
    hkLastChild(tabbedControlDiv).style.height = "0px";
    if (window.ActiveXObject)
    {
      // can't set to invisable, the images in the grid still showing and will then overlay with the docked div
    }
    else
      hkLastChild(tabbedControlDiv).style.display = "none";
  }
  else
    hkLastChild(tabbedControlDiv).style.width = "800px";
  
  if(m_globalFullDocked  == true)
  {
    document.getElementById("SplitterArrowDown").parentNode.parentNode.style.overflow = "hidden";
  }
  else
  {
    // set the new css properties
    hkLastChild(document.getElementById("SplitterArrowDown").parentNode).style.height = "100%";
    hkLastChild(document.getElementById("SplitterArrowDown").parentNode).style.width = "100%";
    hkFirstChild(hkLastChild(document.getElementById("SplitterArrowDown").parentNode)).style.height = "97%";
  }

  document.getElementById("KGTabbedWindowsControl1_IndexedDocDiv").style.overflow = "visible";

  // get the docked control
  var controlToInsert = document.getElementById("DockedHelpWindow"); 
  var controlToInsert2 = document.getElementById("DockedHelpWindowOptions");
  var controlToInsert3 = document.getElementById("DockedHelpWindowContainer");
  var controlToInsert4 = document.getElementById("DockedHelpWindowTVOptions");
  var loadingDiv = document.getElementById("DockedHelpWindowLoadingDiv");

  // check if it exists (currently docked on the page)
  if(controlToInsert == null)
  {
    // this element is a 'container' for the tool bar (undock, close) and the iframe containing the text
    controlToInsert3 = document.createElement("div");
    controlToInsert3.setAttribute("id","DockedHelpWindowContainer");
    controlToInsert3.setAttribute("style","float:left");
    controlToInsert3 = InsertAdjacentElement(document.getElementById("KGTabbedWindowsControl1"),"afterBegin", controlToInsert3);

    if(m_globalFullDocked == true)
    {
    if(tabbedControlDiv.clientWidth > 0)
      controlToInsert3.style.width = tabbedControlDiv.clientWidth - 50 + 'px';
    if(document.getElementById("SplitterArrowDown").parentNode.parentNode.style.pixelHeight && document.getElementById("SplitterArrowDown").parentNode.parentNode.style.pixelHeight != '')
      controlToInsert3.style.height = document.getElementById("SplitterArrowDown").parentNode.parentNode.style.pixelHeight; //lastChild.firstChild
    else if(document.getElementById("SplitterArrowDown").parentNode.parentNode.offsetHeight && document.getElementById("SplitterArrowDown").parentNode.parentNode.offsetHeight != '')
      controlToInsert3.style.height = document.getElementById("SplitterArrowDown").parentNode.parentNode.offsetHeight;
    else
      controlToInsert3.style.height = "100%";
    }
    else
    {
      //debugger;
      if(globalHideIndexedDocs == true)
      {      
        controlToInsert3.style.width = screen.width;
        
        globalSplitterSetting = "split";
        SplitterControl('up');
      }
      else
        controlToInsert3.style.width = "400px";
      if(window.ActiveXObject && (document.getElementById("SplitterArrowDown").parentNode.parentNode.style.pixelHeight && document.getElementById("SplitterArrowDown").parentNode.parentNode.style.pixelHeight != ''))
        controlToInsert3.style.height = document.getElementById("SplitterArrowDown").parentNode.parentNode.style.pixelHeight; 
      else if(document.getElementById("SplitterArrowDown").parentNode.parentNode.offsetHeight && document.getElementById("SplitterArrowDown").parentNode.parentNode.offsetHeight != '')
        controlToInsert3.style.height = document.getElementById("SplitterArrowDown").parentNode.parentNode.offsetHeight;
      else
        controlToInsert3.style.height = "100%";   
    }
    controlToInsert3.style.styleFloat = "left";
    controlToInsert3.style.textAlign = "left";
        
    // If not, then create it and set the styling
    controlToInsert = document.createElement("iframe");
    controlToInsert.setAttribute("id","DockedHelpWindow");
    controlToInsert.setAttribute("frameBorder","no"); 
    controlToInsert = InsertAdjacentElement(document.getElementById("DockedHelpWindowContainer"),"afterBegin", controlToInsert);
    controlToInsert.style.height = "89%";
    if(m_globalFullDocked == true || globalHideIndexedDocs == true)
    {
      controlToInsert.style.width = controlToInsert3.style.width;
      document.getElementById("KGTabbedWindowsControl1").style.height = controlToInsert.style.height;
      document.getElementById("KGTabbedWindowsControl1").style.overflowY = "hidden";
    }
    else
      controlToInsert.style.width = "400px";
      
    
    //controlToInsert.style.styleFloat = "left";
    controlToInsert.style.textAlign = "left";
    
    // create a div to put the textview view mode option div
    controlToInsert4 = document.createElement("div");
    controlToInsert4.setAttribute("id","DockedHelpWindowTVOptions");
    controlToInsert4.style.marginTop = "20px";
    controlToInsert4.style.textAlign = "right";
    controlToInsert4.style.paddingRight = "10px";
    // if not in edit mode and not showing web docs, then show the option div
    if(m_bEditable != true && globalShowingWebDoc == false)
      controlToInsert4.style.display = "block";
    else
      controlToInsert4.style.display = "none";
    controlToInsert4 = InsertAdjacentElement(document.getElementById("DockedHelpWindowContainer"),"afterBegin", controlToInsert4);
    if(m_currentTextViewViewMode == "Full")
      controlToInsert4.innerHTML = "<SPAN class='ToSingleTextView' id='DockedTextViewModeSwitch' onclick='SwitchTextViewViewMode()'></SPAN>";
    else
      controlToInsert4.innerHTML = "<SPAN class='ToFullTextView' id='DockedTextViewModeSwitch' onclick='SwitchTextViewViewMode()'></SPAN>";


    // create a div to put the toolbar buttons into and set any styling  
    controlToInsert2 = document.createElement("div");
    controlToInsert2.setAttribute("id","DockedHelpWindowOptions");
    controlToInsert2 = InsertAdjacentElement(document.getElementById("DockedHelpWindowContainer"),"afterBegin", controlToInsert2); 
    controlToInsert2.innerHTML = "<img id='close' class='close_img' src='UserControls/Images/BaseControls/CloseButton.png' onclick=\"CloseDockedKGHelpControl('HelpFrame');CloseHelpControl();\"/><img id='undock' class='undock_img' src='UserControls/Images/BaseControls/imgUnDock.png' onclick=\"UnDockKGHelpControl('HelpFrame');\" />";

    // create a div to put the toolbar buttons into and set any styling  
    laodingDiv = document.createElement("div");
    laodingDiv.setAttribute("id","DockedHelpWindowLoadingDiv");
    laodingDiv = InsertAdjacentElement(document.getElementById("DockedHelpWindowContainer"),"afterBegin", laodingDiv); 
    laodingDiv.style.display = 'none';
    laodingDiv.style.position = 'absolute';
    laodingDiv.style.fontSize = 'xx-small';
    laodingDiv.style.fontFamily = 'Verdana';
    laodingDiv.style.backgroundColor = 'white';
    laodingDiv.style.width = '120px';
    laodingDiv.style.padding = '5px';
    laodingDiv.style.textAlign = 'center';
    laodingDiv.style.border = '1px solid Gray';    

  }
  
  // Open, clear, and then close the documents text - this fixes the missing line of text bug
  controlToInsert.contentWindow.document.open();
  controlToInsert.contentWindow.document.write("");
  controlToInsert.contentWindow.document.close();
  
  // copy in the new text
  controlToInsert.contentWindow.document.write("<head><base target='_blank'><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body class='PersonalisedScrollBar' style='overflow:scroll;' onscroll='parent.HelpFrameScrollTimeOut(\"DockedHelpWindow\")'>");
  controlToInsert.contentWindow.document.write(helpText);
  controlToInsert.contentWindow.document.write("</body>");
    
  if(document.frames)
  {
    document.frames['DockedHelpWindow'].location.reload(true);
  }

  // store the help box'x current width, height and positioning for a 'restore'
  helpBoxWidth = controlToInsert.style.width;
  helpBoxHeight = controlToInsert.style.height;
  helpBoxTop = controlToInsert.style.top;
  helpBoxLeft = controlToInsert.style.left;
  
  // Close the pop up window
  HideKGHelpControl();
  
  //controlToInsert3.style.float = "left";
  
    
  if(m_globalFullDocked == true)
  {
    // auto expand the splitter
    // split view 50/50
		DoExpandMapViewPane("split");
    //window.setTimeout('AdjustFullyDockedControlSize()', 50);
  }
  
  window.setTimeout('AdjustFullyDockedControlSize()', 50);
  window.setTimeout('HelpFrameDivResize()', 100);
    // make sure scroll to the right position
  window.setTimeout('SetupHelpFrameKnowdeTextViewDivs()',500);
*/
  
}

function AdjustFullyDockedControlSize()
{
  ///debugger;
   /* var tabbedControlDiv = document.getElementById("KGTabbedWindowsControl1");
    var controlToInsert = document.getElementById("DockedHelpWindow"); 
    var controlToInsert2 = document.getElementById("DockedHelpWindowOptions");
    var controlToInsert3 = document.getElementById("DockedHelpWindowContainer");

  if(m_globalFullDocked  == true)
  {
    hkLastChild(tabbedControlDiv).style.width = "0px";
    hkLastChild(tabbedControlDiv).style.height = "0px";
    if (window.ActiveXObject)
    {
      // can't set to invisable, the images in the grid still showing and will then overlay with the docked div
    }
    else
      hkLastChild(tabbedControlDiv).style.display = "none";
    
    
    controlToInsert3.style.width = document.getElementById("SplitterArrowDown").parentNode.parentNode.clientWidth - 10 + 'px';
    
    if(window.ActiveXObject && (document.getElementById("SplitterArrowDown").parentNode.parentNode.style.pixelHeight && document.getElementById("SplitterArrowDown").parentNode.parentNode.style.pixelHeight != ''))
      controlToInsert3.style.height = document.getElementById("SplitterArrowDown").parentNode.parentNode.style.pixelHeight - 5; //lastChild.firstChild
    else if(document.getElementById("SplitterArrowDown").parentNode.parentNode.offsetHeight && document.getElementById("SplitterArrowDown").parentNode.parentNode.offsetHeight != '')
      controlToInsert3.style.height = document.getElementById("SplitterArrowDown").parentNode.parentNode.offsetHeight - 5;
    else
      controlToInsert3.style.height = "100%";
      
    controlToInsert.style.width = controlToInsert3.style.width;
    
    if(controlToInsert3.style.height != "100%")
      controlToInsert.style.height = (controlToInsert3.style.height.replace('px','') - controlToInsert2.style.height.replace('px','') - 15) + 'px';
    else
      controlToInsert.style.height = "100%";
      
    document.getElementById("SplitterArrowDown").parentNode.parentNode.style.overflow = "hidden";
    
  }else
  {
    // make sure the div float to the left
    //controlToInsert3.style.float = "left";

  }
  
  if(navigator.appName == "Opera")
  {
    var dockedText = document.getElementById("DockedHelpWindow");
      
    // copy in the new text
    dockedText.contentWindow.document.write("<head><base target='_blank'><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body class='PersonalisedScrollBar' style='overflow:scroll;' onscroll='parent.HelpFrameScrollTimeOut(\"DockedHelpWindow\")'>");
    dockedText.contentWindow.document.write(helpText);
    dockedText.contentWindow.document.write("</body>");

  }*/
}


function UnDockKGHelpControl(_helpBoxID)
{  
  m_bHelpFrameLoadSiblingKnowde = false;
  
  // now close the docked window and reset any css which has been changed
  CloseDockedKGHelpControl(_helpBoxID, "undock");
  
  //HideOrShowTextViewOptionDiv(false);
  HelpLinkClicked(true);
  
  // change image and onclick handler
  document.getElementById("SiteOverlays_KGHelpControl1_MaximiseToPageButton").className = "MaximiseButtonImage";
  document.getElementById("SiteOverlays_KGHelpControl1_MaximiseToPageButton").onclick = function(){MaximiseKGHelpControl('KGHelpControlID1', 'SiteOverlays_KGHelpControl1_MaximiseToPageButton')};  
}



function CloseDockedKGHelpControl(_helpBoxID, _undock, _tabbedWindow)
{  
  /*m_bHelpFrameLoadSiblingKnowde = false;
  
  var d = document.getElementById('DockedHelpWindowContainer');
  
  //debugger;
  // check if the indexed docs window is 'closed' if it is then drop the splitter
  if(globalHideIndexedDocs == true)
  {
    SplitterControl('down');
  }

  // remove the docked item from the page
  if(d != null)
  {
    purge(d);
    d.parentNode.removeChild(d);
  }

  // reset the old css values
  var controlToInsertTo = document.getElementById("KGTabbedWindowsControl1");
  controlToInsertTo.style.width = "100%";
  hkLastChild(controlToInsertTo).style.width = "100%";
  hkLastChild(controlToInsertTo).style.height = "100%";
  document.getElementById("SplitterArrowDown").parentNode.parentNode.style.overflow = "auto";
  
  document.getElementById("KGTabbedWindowsControl1_IndexedDocDiv").style.overflow = "auto";
  hkFirstChild(hkLastChild(document.getElementById("SplitterArrowDown").parentNode)).style.height = "100%";

  if(m_globalFullDocked == true)
  {
    m_globalFullDocked = false;
    
    if(hkLastChild(controlToInsertTo).style.display == "none")
      hkLastChild(controlToInsertTo).style.display = "";
    
    if(_tabbedWindow == null || _tabbedWindow != true)
      DoExpandMapViewPane("fully"); // close the bottom pane
  }
  
  var currentKG = document.getElementById(currentlySelectedKG)
			  
  if (currentKG != null)
  {
    if(_undock == "undock")
    {
			currentKG.innerHTML = "Now showing the Knowledge Gene<sup>&#174;</sup> and document";
		}
    else
    {
			if(globalSplitterSetting == "single")
			{
				currentKG.innerHTML = "Click here to show the Knowledge Gene";
				currentKG.href = "javascript:function temp(){ SwitchPaneView('map');return;" + currentKG.href.replace('javascript:','') + "} temp();";
			}
			else
			{
				currentKG.innerHTML = "Now showing the Knowledge Gene<sup>&#174;</sup>, click here to view the document";	
      }
    }
  }*/
}

function ClearHelpFrame(_clearSelectedValues)
{
  
  var HelpFrame = document.getElementById("HelpFrame");
  if (HelpFrame.src != null && HelpFrame.src != "")
  {
    var parent = HelpFrame.parentNode;
    
    var newHelpFrame = document.createElement('iframe');
    newHelpFrame.id = "HelpFrame";
    newHelpFrame.className = "helpIFrame";
    newHelpFrame.frameBorder = 0;
      
    purge(HelpFrame);  
    parent.removeChild(HelpFrame);
    InsertAdjacentElement(parent,"beforeend", newHelpFrame);
  }
  else
  {
    // Make sure we clear the contents of the document window
    HelpFrame.contentWindow.document.write("");
    HelpFrame.contentWindow.document.close();
  }
  
  // clear member variables
    //debugger;
  
  /*m_FrameLoadedKnowdeIdList = new Array();
  m_FrameLoadedKnowdeIdString = '';
  m_FrameUnLoadedKnowdeIdString = '';

  // knowde and client knowde list
  m_FrameKnowdeIdsArray = new Array();
  m_FrameKnowdeClientIdsArray = new Array();

  m_FrameDivIDArray = new Array();
  m_FrameDivPathArray = new Array();
  m_FrameDivHeightArray = new Array();
  m_FrameKnowdePathString = '';
  
  if(_clearSelectedValues == null || _clearSelectedValues == true)
  {
    m_strFrameSelectedKGID = '';
    m_strFrameSelectedKnowdeID = '';
    m_strFrameSelectedKnowdeDBID = '';
    m_strFrameSelectedKnowdeContext = '';
    m_strFrameCentreKnowdeContext = '';
    m_bHelpFrameLoadSiblingKnowde = false;
  }
  
  m_helpFrameScrollTimeOut = null;*/
}

//pass through the session stuff...
function OpenHelpControl_wrapped(_hideDockButton, _imgDockInPageID)
{
  var docButton = document.getElementById(_imgDockInPageID);
  if (_hideDockButton)
  {
    docButton.style.display = "none";
    globalHideDockButton = true;
  }
  else
  {
    docButton.style.display = "";
    globalHideDockButton = false;
  }
  
  // make sure the docked window is close then the help control popup
  if(document.getElementById('DockedHelpWindowContainer') != null)
    CloseDockedKGHelpControl('HelpFrame');
  
  ShowKGHelpControl();
}

function CloseHelpControl()
{
	if(document.getElementById("GreyDiv") != null)
	{
	    purge(document.getElementById("GreyDiv"));
		document.getElementById("Form1").removeChild(document.getElementById("GreyDiv"));
		document.getElementById("m_cookieDiv").className = "m_cookieDivHidden";
		document.getElementById("miniGlobe").className = "miniGlobe";
	}
  globalShowingWebDoc = false;
  var MapHelpBox = document.getElementById("KGHelpControlID1");
  
  // reset the tooltip
  MapHelpBox.title = "Associated Text";
  // hide textview view option div
  //HideOrShowTextViewOptionDiv(false);
  
  // reset the view mode
  //SwitchTextViewViewMode("Single");
  //globalLastTickerAction = "";
  
  ClearHelpFrame()
  SetHelpStateCookie();
  HideKGHelpControl();
  
  //debugger;
  //if (window.KGTextViewEditingToolbar_ChangeEditbarMode && m_bTextViewWritable == true)
    //KGTextViewEditingToolbar_ChangeEditbarMode("TextViewReset");

  // show the preview button if in edit mode
  /*if(m_bEditable == true)
  {
    KGButtonToolbar_hideOrShowPreviewFullTVButton(true);
    if(m_bTextViewWritable == true && EditFrameContentWindowExists())
    {
      SaveCurrentlyEditingTextView(false);
  
      m_EditFrameDiv = document.getElementById('TextViewEditFrameDiv');

      if(m_EditFrameDiv != null)
        m_EditFrameDiv.innerHTML = "";
        
      m_bTextViewWritable = false;
    }else
    {
      // clear text view auto save timeout
      if(m_autoSaveTimeOut != null)
        clearTimeout(m_autoSaveTimeOut);
      
      // update the application control if it's open
      if (m_applicationControlOpen)
        ApplicationContextChanged(returnKnowdeID(_parentKnowdeDiv), Active_KGID)
    }
  }else
    KGButtonToolbar_hideOrShowPreviewFullTVButton(false);
  */
  

}

function CookieCheckBox(e)
{
  e = e || window.event;
  var targ = e.target || e.srcElement;
	if(targ.checked)
	{
		//set the persistent cookie
		WM_setCookie('initHelp','hide', m_helpCookieExpiration);
	}
	else
	{
		//delete the persistent cookie
		WM_killCookie('initHelp');
	}
}

/*function HandleHelpFrameLoadAll(_knowdeSequenceInfo, _loadedContentList)
{
  //debugger;
  
  if(m_bHelpFrameLoadSiblingKnowde == false)
  {
    m_FrameLoadedKnowdeIdList = new Array();
    m_FrameLoadedKnowdeIdString = '';
  
    m_FrameKnowdeIdsArray = new Array();
    m_FrameKnowdeClientIdsArray = new Array();
    
    m_FrameKnowdePathString = '';
    
    var frameDivHtml = '';
    
    // loop through all the knowdes m_strSelectedKnowdeID is the currently selecte knowde
    // knowdes above and below will be loaded in top and bottom iframes
    // don't use split incase the knowde title contains character that is used as our seperator
    var foundCurrentKnowde = 0;
    var kidx = _knowdeSequenceInfo.indexOf('(kid=');
    while(kidx >= 0)
    {
      var kidx2 = _knowdeSequenceInfo.indexOf('|ckid=', kidx+1);
      if(kidx2 > kidx)
      {
        var knowdeId = _knowdeSequenceInfo.substr(kidx+5, kidx2-(kidx+5));
        var kidx3 = _knowdeSequenceInfo.indexOf('|path=', kidx2+1);
        if(kidx3 > kidx2)
        {
          var clientKnowdeId = _knowdeSequenceInfo.substr(kidx2+6, kidx3-(kidx2+6));
          
          // store the knowde and client id mapping
          m_FrameKnowdeIdsArray.push(knowdeId);
          m_FrameKnowdeClientIdsArray.push(clientKnowdeId);
          
          var kidx4 = _knowdeSequenceInfo.indexOf('|title=', kidx3+1);
          if(kidx4 > kidx3)
          {
            var pathContext = _knowdeSequenceInfo.substr(kidx3+6, kidx4-(kidx3+6));
            kidx = _knowdeSequenceInfo.indexOf(')(kid=', kidx4+1);
            var knowdeTitle = '';
            if(kidx > kidx4)
            {
              knowdeTitle = _knowdeSequenceInfo.substr(kidx4+7, kidx-(kidx4+7));
              kidx = kidx + 1; // because we are searching for )( instead of just (
            }else if(kidx == -1)
            {
              knowdeTitle = _knowdeSequenceInfo.substr(kidx4+7, _knowdeSequenceInfo.length-1-(kidx4+7));
            }
            
            // now create div and load to the content
            var frame = m_HelpFrame;
             
             if(frame != null)
             {
               var loaded = 0;
               var sidx = _loadedContentList.indexOf('<HKTextView' + clientKnowdeId + '>');
               var sidx2 = _loadedContentList.indexOf('</HKTextView>', sidx+1);
               var content = '';
               if(sidx != -1 && sidx2 != -1)
               {
                  loaded = 1;
                  content = _loadedContentList.substr(sidx+11+clientKnowdeId.length+1,sidx2-(sidx+11+clientKnowdeId.length+1));
                  var kid = clientKnowdeId;
                 
                  m_FrameLoadedKnowdeIdList.push(kid);
                  m_FrameLoadedKnowdeIdString += kid + ','
                 
                  var bidx = content.toLowerCase().indexOf('<body');
                  var bidx2 = content.indexOf('>');
                  var bidx3 = content.toLowerCase().indexOf('</body>');
                  if(bidx != -1 && bidx2 > bidx && bidx3 > bidx2)
                    content = content.substr(bidx2+1, bidx3-(bidx2+1));
        
                  if(content == '')
                  {
                    content = GetDefaultTextViewContentWithTitle(clientKnowdeId, knowdeTitle, 1, m_noTextViewFoundContent);
                  }else
                  {
                    content = TrimTickerSpans(content);
                    if (content.indexOf(m_textViewTickerSelectionHighlightColor) > -1)
                      content = ReturnUnhighlightedTickerText(content);
                      
                    // check whether it has an existing title, if not, add the title manually
                    if(CheckTextViewHasTitle(clientKnowdeId, knowdeTitle, content) == false)
                      content = WrapTextViewContentWithTitle(clientKnowdeId, knowdeTitle, content);
                  }
                                    
               }else
               {
                 loaded = 0;
                 // text view is not loaded yet
                 content = GetDefaultTextViewContentWithTitle(clientKnowdeId, knowdeTitle, 1, m_notLoadedText);
                 m_FrameUnLoadedKnowdeIdString += clientKnowdeId + ','
               }
               
              if((m_strFrameSelectedKnowdeID == knowdeId || m_strFrameSelectedKnowdeID == clientKnowdeId)
              && m_strFrameSelectedKnowdeContext == '')
              {
                  m_strFrameSelectedKnowdeContext = pathContext;
              }
               
               //for scrolling position detection debug only//
               //content = pathContext + '<br>' + content; 
              
               m_FrameKnowdePathString += pathContext + ',';
               
                    var divHtml = "<div id='" + pathContext + "' kid='" + clientKnowdeId + "' title='" + knowdeTitle + "' isLoaded='" + loaded + "' width='100%'>";
                    //if (content.indexOf(m_textViewTickerSelectionHighlightColor) > -1)
                      //content = ReturnUnhighlightedTickerText(content);
                    
                    // directly add content can't deal with not proper formatted HTML
                    // like  missing ticker span close tag etc and then cause iframe's innerHTML 
                    // to be auto corrected later on by added a </span> in the end 
                    // so causing problem because childNodes is not right anymore
                    //divHtml += content; 
                    var tempDiv = document.createElement("div");
                    tempDiv.innerHTML = content; // the content will be auto corrected and guanrantee the ifram only contains divs as first level child nodes
                    divHtml += tempDiv.innerHTML; 
                    divHtml += "</div>";
                      
                    frameDivHtml += divHtml;
                 
             }
            
          }
        }
      }
    }// end while
    
    var MapHelpBox = document.getElementById("KGHelpControlID1");
    m_HelpFrame.contentWindow.document.write("<html><head><base target='_blank'><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body class='PersonalisedScrollBar' style='overflow:scroll;' onscroll='parent.HelpFrameScrollTimeOut(\"HelpFrame\")'>");
    m_HelpFrame.contentWindow.document.write(frameDivHtml);
    m_HelpFrame.contentWindow.document.write("</body></html>");
     
  } // end if
  else
  {
    
    // need to find out where the knowde is
    var knowdeFrame = '';
      
    // patial load text views
    if(_loadedContentList && _loadedContentList != ''
      && m_HelpFrame != null)
    {
       // loop through each textview content
        var sidx = _loadedContentList.indexOf('<HKTextView');
        var sidx2 = _loadedContentList.indexOf('>', sidx);
        var sidx3 = _loadedContentList.indexOf('</HKTextView>', sidx2);
        while(sidx != -1 && sidx2 != -1 && sidx3 != -1)
        {
          var content = _loadedContentList.substr(sidx2+1, sidx3-(sidx2+1));
          var kid = _loadedContentList.substr(sidx+11,sidx2-(sidx+11));
          
          if((m_FrameLoadedKnowdeIdString.indexOf(kid+',') != 0)
          && (m_FrameLoadedKnowdeIdString.indexOf(','+kid+',') == -1))
          {
            m_FrameLoadedKnowdeIdList.push(kid);
            m_FrameLoadedKnowdeIdString += kid + ',';
            
            // remove from unloaded list
            if(m_FrameUnLoadedKnowdeIdString.indexOf(kid+',') == 0)
              m_FrameUnLoadedKnowdeIdString = m_FrameUnLoadedKnowdeIdString.substring(kid.length+1);
            else
              m_FrameUnLoadedKnowdeIdString = m_FrameUnLoadedKnowdeIdString.replace(','+kid+',', ',');
              
            // load all the unloaded textviews for this knowde to the given content
            var bidx = content.toLowerCase().indexOf('<body');
            var bidx2 = content.indexOf('>');
            var bidx3 = content.toLowerCase().indexOf('</body>');
            if(bidx != -1 && bidx2 > bidx && bidx3 > bidx2)
               content = content.substr(bidx2+1, bidx3-(bidx2+1));
               
            var method = function(el){if(el.getAttribute('kid') == kid) return true; return false;};
            //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,m_HelpFrame.contentWindow.document.body);   
            var frameDivs = YAHOO.util.Dom.getChildrenBy(m_HelpFrame.contentWindow.document.body,method);   
            for(var iCounter = 0; iCounter < frameDivs.length; iCounter++)
            {
                  var childDiv = frameDivs[iCounter];
                  
                  if(content == '')
                      content = childDiv.innerHTML.replace(m_notLoadedText, m_noTextViewFoundContent);
                  else
                  {
                    content = TrimTickerSpans(content);
                    if (content.indexOf(m_textViewTickerSelectionHighlightColor) > -1)
                      content = ReturnUnhighlightedTickerText(content);
                      
                    //for scrolling position detection debug only//
                    //content = childDiv.id + '<br>' + content; 
                    
                    // check whether it has an existing title, if not, add the title manually
                    var ckid = childDiv.getAttribute('kid');
                    var ktitle = childDiv.getAttribute('title');
                    if(CheckTextViewHasTitle(ckid, ktitle, content) == false)
                      content = WrapTextViewContentWithTitle(ckid, ktitle, content);
                  }
                  

                  if(childDiv != null && childDiv.getAttribute('kid') == kid && (childDiv.getAttribute('isLoaded') == 0 || childDiv.getAttribute('isLoaded') == '0'))
                  {
                    childDiv.innerHTML = content;
                    childDiv.setAttribute('isLoaded', 1);
                  }
             }      

            
          }
          
                         
            _loadedContentList = _loadedContentList.substr(sidx3+13);
            sidx = _loadedContentList.indexOf('<HKTextView');
            sidx2 = _loadedContentList.indexOf('>', sidx);
            sidx3 = _loadedContentList.indexOf('</HKTextView>', sidx2);
          
        }    // end while
      
    }
  }
  
    // Copy the text view to the docked window if it exists
    var dockedText = document.getElementById("DockedHelpWindow");
    
    if (dockedText != null)
    {
      dockedText.contentWindow.document.open();
      dockedText.contentWindow.document.write("");
      dockedText.contentWindow.document.close();

      dockedText.contentWindow.document.write("<html><head><base target='_blank'><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body class='PersonalisedScrollBar' style='overflow:scroll;' onscroll='parent.HelpFrameScrollTimeOut(\"DockedHelpWindow\")'>");
      dockedText.contentWindow.document.write(m_HelpFrame.contentWindow.document.body.innerHTML);
      dockedText.contentWindow.document.write("</body></html>");
    }

  
  window.setTimeout("SetupHelpFrameKnowdeTextViewDivs()",200);
  window.setTimeout("helpText = m_HelpFrame.contentWindow.document.body.innerHTML;", 300);
}*/

/*function HandleNewWindowTextViewLoadAll(_knowdeSequenceInfo, _loadedContentList, _selectedKnowdeContext)
{
  var newWindowFrame =  m_newTextViewWindow.document.getElementById('NewWindowHelpFrame');
      
    // patial load text views
    if(_loadedContentList && _loadedContentList != ''
      && newWindowFrame != null)
    {
       // loop through each textview content
        var sidx = _loadedContentList.indexOf('<HKTextView');
        var sidx2 = _loadedContentList.indexOf('>', sidx);
        var sidx3 = _loadedContentList.indexOf('</HKTextView>', sidx2);
        while(sidx != -1 && sidx2 != -1 && sidx3 != -1)
        {
          var content = _loadedContentList.substr(sidx2+1, sidx3-(sidx2+1));
          var kid = _loadedContentList.substr(sidx+11,sidx2-(sidx+11));
          
                          
            // load all the unloaded textviews for this knowde to the given content
            var bidx = content.toLowerCase().indexOf('<body');
            var bidx2 = content.indexOf('>');
            var bidx3 = content.toLowerCase().indexOf('</body>');
            if(bidx != -1 && bidx2 > bidx && bidx3 > bidx2)
               content = content.substr(bidx2+1, bidx3-(bidx2+1));
            // Yahoo getElementsBy too slow in IE
            var method = function(el){if(el.getAttribute('kid') == kid) return true; return false;};
            //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,newWindowFrame.contentWindow.document.body);   
            var frameDivs = YAHOO.util.Dom.getChildrenBy(newWindowFrame.contentWindow.document.body,method);   

            for(var iCounter = 0; iCounter < frameDivs.length; iCounter++)
            //for(var iCounter = 0; iCounter < newWindowFrame.contentWindow.document.body.childNodes.length; iCounter++)
            {
               //if(newWindowFrame.contentWindow.document.body.childNodes[iCounter].getAttribute('kid') == kid)
               //{   
                  //var childDiv = newWindowFrame.contentWindow.document.body.childNodes[iCounter]; 
                  var childDiv = frameDivs[iCounter];
                  
                  if(content == '')
                      content = childDiv.innerHTML.replace(m_notLoadedText, m_noTextViewFoundContent);
                  else
                  {
                    content = TrimTickerSpans(content);
                    if (content.indexOf(m_textViewTickerSelectionHighlightColor) > -1)
                      content = ReturnUnhighlightedTickerText(content);
                      
                    //for scrolling position detection debug only//
                    //content = childDiv.id + '<br>' + content; 
                    
                    // check whether it has an existing title, if not, add the title manually
                    var ckid = childDiv.getAttribute('kid');
                    var ktitle = childDiv.getAttribute('title');
                    if(CheckTextViewHasTitle(ckid, ktitle, content) == false)
                      content = WrapTextViewContentWithTitle(ckid, ktitle, content);

                  }
                  
                  if(childDiv != null && childDiv.getAttribute('kid') == kid && (childDiv.getAttribute('isLoaded') == 0 || childDiv.getAttribute('isLoaded') == '0'))
                  {
                    childDiv.innerHTML = content;
                    childDiv.setAttribute('isLoaded',1);
                  }
                //}
             }      
                         
            _loadedContentList = _loadedContentList.substr(sidx3+13);
            sidx = _loadedContentList.indexOf('<HKTextView');
            sidx2 = _loadedContentList.indexOf('>', sidx);
            sidx3 = _loadedContentList.indexOf('</HKTextView>', sidx2);257
          
        }    // end while
        
        // scroll to the right place
        if(_selectedKnowdeContext != null && _selectedKnowdeContext != '')
        {
            var method = function(el){if(el.id == _selectedKnowdeContext) return true; return false;};
            //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,newWindowFrame.contentWindow.document.body);   
            var frameDivs = YAHOO.util.Dom.getChildrenBy(newWindowFrame.contentWindow.document.body,method);   
            if(frameDivs.length > 0)
            {
              newWindowFrame.contentWindow.document.body.scrollTop  = frameDivs[0].offsetTop - 10;
            }
        }
      
    }
    
    // hide loading div
    var loadingDiv = m_newTextViewWindow.document.getElementById('NewWindowTextViewLoadingDiv');
    if(loadingDiv != null)
        loadingDiv.style.display = 'none';
}*/

/*function SetupHelpFrameKnowdeTextViewDivs()
{
  //debugger;
  m_HelpFrame = document.getElementById("HelpFrame");
  var adiv = null;
  m_DockedHelpFrame = document.getElementById("DockedHelpWindow");
  var dockedadiv = null;
  
  if(m_HelpFrame != null)
    adiv = m_HelpFrame.contentWindow.document.body;
  if(m_DockedHelpFrame != null)
    dockedadiv = m_DockedHelpFrame.contentWindow.document.body;

  m_FrameDivIDArray = new Array();
  m_FrameDivPathArray = new Array();
  m_FrameDivHeightArray = new Array();
  // m_FrameKnowdePathString  = '';

  var pos = 0;
  if(m_HelpFrame != null && adiv != null)
  {
     if(m_strFrameSelectedKnowdeContext == '' && m_strFrameSelectedKnowdeID != '')
     {
        var method = function(el){if(el.getAttribute('kid') == m_strFrameSelectedKnowdeID) return true; return false;};
        //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,adiv);  
        var frameDivs = YAHOO.util.Dom.getChildrenBy(adiv,method);   
        if(frameDivs.length > 0)
          m_strFrameSelectedKnowdeContext = frameDivs[0].id;
     }
                
        if(m_strFrameCentreKnowdeContext != '')
        {
          var method = function(el){if(el.id == m_strFrameCentreKnowdeContext) return true; return false;};
          //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,adiv);  
          var frameDivs = YAHOO.util.Dom.getChildrenBy(adiv,method);   
          if(frameDivs.length > 0)
          {
            // make sure scroll to this position
            m_bHelpFrameManualScroll = true;
            
            var scrollTopValue = frameDivs[0].offsetTop - m_HelpFrame.offsetHeight/2;
            //scrollTopValue = scrollTopValue - m_frameScrollTopOffSet;
            if(scrollTopValue < 0)
              scrollTopValue = 0;
            adiv.scrollTop  = scrollTopValue;
          }
          // for docked frame
          if(dockedadiv != null)
          {
            //frameDivs = YAHOO.util.Dom.getElementsBy(method,null,dockedadiv);  
            frameDivs = YAHOO.util.Dom.getChildrenBy(dockedadiv,method);   
            if(frameDivs.length > 0)
            {
              // make sure scroll to this position
              m_bHelpFrameManualScroll = true;
              
              var scrollTopValue = frameDivs[0].offsetTop - m_DockedHelpFrame.offsetHeight/2;
              //scrollTopValue = scrollTopValue - m_frameScrollTopOffSet;
              if(scrollTopValue < 0)
                scrollTopValue = 0;
              dockedadiv.scrollTop  = scrollTopValue;
            }
          }
        }
        
        if(m_strFrameSelectedKnowdeContext != '')
        { 
          if(m_previousHighLightedPath != '')
          {
              // unhighlight
            var method = function(el){if(el.id == m_previousHighLightedPath) return true; return false;};
            //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,adiv);  
            var frameDivs = YAHOO.util.Dom.getChildrenBy(adiv,method);   
            if(frameDivs.length > 0)
            {
              //frameDivs[0].style.backgroundColor = 'white';
              frameDivs[0].style.borderLeft = 'none';
              frameDivs[0].style.paddingLeft = '0px';
              frameDivs[0].style.marginLeft = '0px';
            }
            // for docked frame
            if(dockedadiv != null)
            {
              //frameDivs = YAHOO.util.Dom.getElementsBy(method,null,dockedadiv);  
              frameDivs = YAHOO.util.Dom.getChildrenBy(dockedadiv,method);   

              if(frameDivs.length > 0)
              {
                //frameDivs[0].style.backgroundColor = 'white';
                frameDivs[0].style.borderLeft = 'none';
                frameDivs[0].style.paddingLeft = '0px';
                frameDivs[0].style.marginLeft = '0px';
              }
            }
          }
          
          // highlight
          var method = function(el){if(el.id == m_strFrameSelectedKnowdeContext) return true; return false;};
          //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,adiv);  
          var frameDivs = YAHOO.util.Dom.getChildrenBy(adiv,method);   
          if(frameDivs.length > 0)
          {
            if(m_strFrameCentreKnowdeContext == '')
            {
              // make sure scroll to this position
              // m_bHelpFrameManualScroll = true;
              var scrollTopValue = frameDivs[0].offsetTop - (m_frameScrollTopOffSet + 20);
              if(scrollTopValue < 0)
                scrollTopValue = 0;
              m_helpFrameScrollMoreOnTopTimeOut = window.setTimeout("ScrollMoreFromTop('HelpFrame'," + scrollTopValue + ", 0)", m_helpFrameScrollDelay);
              //adiv.scrollTop  = scrollTopValue;
            }
            
            // now get rid of the empty <P> tags in the end which makes the next div overlay a bit with the current div
            var content = frameDivs[0].innerHTML;
            content = content.replace(/(<p\/>|<p><\/p>|<p \/>|<p><br \/><\/p>|<p><br\/><\/p>)+$/i,'');//remove trailing empty paragraph
            content = content.replace(/(<p\/>|<p><\/p>|<p \/>|<p><br \/><\/p>|<p><br\/><\/p>)<\/div>+$/i,'</div>');//remove trailing empty paragraph
            frameDivs[0].innerHTML = content;

            //frameDivs[0].style.backgroundColor = m_helpFrameHighlightColor;
            frameDivs[0].style.borderLeft = m_helpFrameHighlightBorderLeftStyle;
            frameDivs[0].style.paddingLeft = m_helpFrameHighlightBorderLeftPadding + 'px';
            frameDivs[0].style.marginLeft = '-' + m_helpFrameHighlightBorderLeftPadding + 'px';
            
           m_previousHighLightedPath = frameDivs[0].id;
         }
          
         // for docked frame
        if(dockedadiv != null)
        {
          //frameDivs = YAHOO.util.Dom.getElementsBy(method,null,dockedadiv);  
          frameDivs = YAHOO.util.Dom.getChildrenBy(dockedadiv,method);   
          if(frameDivs.length > 0)
          {
            if(m_strFrameCentreKnowdeContext == '')
            {
              // make sure scroll to this position
              // m_bHelpFrameManualScroll = true;
              var scrollTopValue = frameDivs[0].offsetTop - m_frameScrollTopOffSet;
              if(scrollTopValue < 0)
                scrollTopValue = 0;
                
              m_dockedFrameScrollMoreOnTopTimeOut = window.setTimeout("ScrollMoreFromTop('DockedFrame'," + scrollTopValue + ", 0)", m_helpFrameScrollDelay);
              //dockedadiv.scrollTop  = scrollTopValue;
            }
            
            // now get rid of the empty <P> tags in the end which makes the next div overlay a bit with the current div
            var content = frameDivs[0].innerHTML;
            content = content.replace(/(<p\/>|<p><\/p>|<p \/>|<p><br \/><\/p>|<p><br\/><\/p>)+$/i,'');//remove trailing empty paragraph
            content = content.replace(/(<p\/>|<p><\/p>|<p \/>|<p><br \/><\/p>|<p><br\/><\/p>)<\/div>+$/i,'</div>');//remove trailing empty paragraph
            frameDivs[0].innerHTML = content;
            
            //frameDivs[0].style.backgroundColor = m_helpFrameHighlightColor;
            frameDivs[0].style.borderLeft = m_helpFrameHighlightBorderLeftStyle;
            frameDivs[0].style.paddingLeft = m_helpFrameHighlightBorderLeftPadding + 'px';
            frameDivs[0].style.marginLeft = '-' + m_helpFrameHighlightBorderLeftPadding + 'px';
          }
        }
 
     }
    
  }
  
}*/

/*function ScrollMoreFromTop(_target, _scrollTop, _amount)
{
  //debugger;
  var div = null;
  m_HelpFrame = document.getElementById("HelpFrame");
  var adiv = null;
  m_DockedHelpFrame = document.getElementById("DockedHelpWindow");
  var dockedadiv = null;
  
  if(m_HelpFrame != null)
    adiv = m_HelpFrame.contentWindow.document.body;
  if(m_DockedHelpFrame != null)
    dockedadiv = m_DockedHelpFrame.contentWindow.document.body;

  if(_target == 'HelpFrame')
  {
    clearTimeout(m_helpFrameScrollMoreOnTopTimeOut);
    m_helpFrameScrollMoreOnTopTimeOut = null;
    div = adiv;
  } else if(_target == 'DockedFrame')
  {
    clearTimeout(m_dockedFrameScrollMoreOnTopTimeOut);
    m_dockedFrameScrollMoreOnTopTimeOut = null;
    div = dockedadiv;
  }
  //debugger;
  if(div != null)
  {
    //alert(_scrollTop + '|' + _amount + '|' + div.scrollTop);

    if(_scrollTop < 0)
      _scrollTop = 0;
      
    if(_amount <= 0)
    {
      // calculate scroll amount
      var diff = Math.abs(_scrollTop - div.scrollTop);
      if(diff == 0)
        return;
      else if(diff < 100)
      {
        _amount = Math.ceil(diff/2); // minum 2 times
      }
      else if(diff <= 500)
        _amount = 50;
      else
      {
        _amount = Math.ceil(diff/10); // maximum do it 10 times
      }
      if(_amount <= 0)
        _amount = 10;
    }
    
      var scrollTo = div.scrollTop;
      if(div.scrollTop > _scrollTop)
      {
        scrollTo -=  _amount;
        if(scrollTo < _scrollTop)
          scrollTo = _scrollTop;
      }else if(div.scrollTop < _scrollTop)
      {
        scrollTo += _amount;
        if(scrollTo > _scrollTop)
          scrollTo = _scrollTop;
      }
      // now scroll to the position
      m_bHelpFrameManualScroll = true;
      div.scrollTop = scrollTo;
      // if we have scroll to the desire location, and also haven't reach the end 
      if(div.scrollTop != _scrollTop && div.scrollTop == scrollTo)
      {
        if(_target == 'HelpFrame')
        {
          m_helpFrameScrollMoreOnTopTimeOut = window.setTimeout("ScrollMoreFromTop('HelpFrame'," + _scrollTop + "," + _amount + ")", m_helpFrameScrollDelay);
        }else if(_target == 'DockedFrame')
        {
          m_dockedFrameScrollMoreOnTopTimeOut = window.setTimeout("ScrollMoreFromTop('DockedFrame'," + _scrollTop + "," + _amount + ")", m_helpFrameScrollDelay);
        }
      }
  }    
}*/

/*function ChangeSelectedHelpFrameKnowde(_selectedKnowdeID, _selectedKnowdePath)
{
  if(m_strFrameSelectedKnowdeID != _selectedKnowdeID)
  {
    if(_selectedKnowdePath == null)
      _selectedKnowdePath = '';
    m_strFrameSelectedKnowdeContext = _selectedKnowdePath;
    m_strFrameSelectedKnowdeID = _selectedKnowdeID;
    return true;
  }
  else
    return false;
}*/


/*function GetHelpWindowCallBackArgs(_kgId)
{
  m_HelpFrame = document.getElementById("HelpFrame");
  var kgid = Active_KGID;
  if(_kgId != null && _kgId > 0)
    kgid = _kgId;
  var args = "|KGId=" + kgid + "|ViewMode=" + m_currentTextViewViewMode;
  
  var loadamount = m_HelpFrame.offsetHeight/40/2;
    if(m_textViewPreLoadAmount > loadamount)
      loadamount = m_textViewPreLoadAmount;
  args += "|PreLoadAmount=" + loadamount;
  
  if(m_bHelpFrameLoadSiblingKnowde == true)
  {
    args += "|LoadSiblingKnowde=true";
    var toLoadDivs = '';
    var knowdeContext = m_strFrameSelectedKnowdeContext;
    
    toLoadDivs = GetPreLoadDivsForHelpFrameSelectedKnowde(m_tickerKnowdeID, knowdeContext, loadamount);       
    
    args += '|KnowdeId=' + m_tickerKnowdeID + '|KnowdePathContext=' + knowdeContext + '|KnowdeIdList=' + toLoadDivs;;
    
    if(toLoadDivs == '')
      args += "|KnowdeLoaded=true";
    else
      args += "|KnowdeLoaded=false";
  }else
  {
    // assume each text view has minimum 40px height
    args += "|KnowdeLoaded=false";
  }
  
  return args;
}*/


/*function FindSelectedHelpFrameKnowdePathContext(_knowdeID)
{
  //debugger;
  var pathContext = '';
  
  if(_knowdeID != null && m_strFrameSelectedKnowdeDBID != '')
  {
    var knowdeID = _knowdeID;
    if(knowdeID < 0)
    {
      // find the knowdeID  instead
      for(var ki = 0; ki < m_FrameKnowdeClientIdsArray.length; ki++)
      {
        if(m_FrameKnowdeClientIdsArray[ki] == knowdeID)
        {
          knowdeID = m_FrameKnowdeIdsArray[ki];
          break;
        }
      }
    }
    
    if(knowdeID > 0 && knowdeID != m_strFrameSelectedKnowdeDBID)
    {
      // basic logic to find possible knowde context and locate the correct text view if knowde is reused
      // might need to be improved later on
      var pathStr = '';
      // in text view assocations:
      // new selected knowde is walked after the previous selected knowde
      var re = new RegExp('(\\[' + m_strFrameSelectedKnowdeDBID + '\\]([^,]+)\\['+knowdeID+'\\])', 'gi');
      // new selected knowde is walked before the previous selected knowde
      var re2 = new RegExp('(\\[' + knowdeID + '\\]([^,]+)\\['+m_strFrameSelectedKnowdeDBID+'\\])', 'gi');
      var matchResult = re.exec(m_FrameKnowdePathString);
      pathStr = m_FrameKnowdePathString;
      if(matchResult == null)
      {
        matchResult = re2.exec(m_FrameKnowdePathString);
      }
      
      if(matchResult != null)
      {
        var foundContext = '';
        var foundIdx = matchResult.index;
        if(foundIdx >= 0)
        {
          var endIdx = pathStr.indexOf(',',foundIdx);
          if(endIdx > 0)
          {
            var pathStr2 = pathStr.substr(0, endIdx);
            var startIdx = pathStr2.lastIndexOf(',');
            if(startIdx == -1)
              foundContext = pathStr2;
            else
              foundContext = pathStr2.substr(startIdx+1);
              
            if(foundContext != '')
            {
              var kidx = foundContext.indexOf('['+knowdeID+']');
              if(kidx != -1)
              {
                foundContext = foundContext.substr(0, kidx + knowdeID.length + 2);
                if(pathStr.indexOf(foundContext + ',') == 0 || pathStr.indexOf(',' + foundContext + ',') != -1)
                  pathContext = foundContext;
              }
            }
          }
        }
      }
    }else if(knowdeID > 0 && knowdeID == m_strFrameSelectedKnowdeDBID)
    {
      pathContext = m_strFrameSelectedKnowdeContext;
    }
    // end if knowdeID > 0
    
  }
  return pathContext;
}*/

/*function GetPreLoadDivsForHelpFrameSelectedKnowde(_knowdeId, _knowdePath, _loadAmount)
{
  // when a knowde is selected in the mapview, find out what knowde text views need to be loaded around it
  var toLoadDivs = '';
  _loadAmount = Math.round(_loadAmount);
  
  if(_knowdePath == '')
  {
      // get the first occurrance of the knowde as default 
      var adiv = m_HelpFrame.contentWindow.document.body;
      
      var method = function(el){if(el.getAttribute('kid') == _knowdeId) return true; return false;};
      //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,adiv); 
      var frameDivs = YAHOO.util.Dom.getChildrenBy(adiv,method);
         
      if(frameDivs.length > 0)
         _knowdePath = frameDivs[0].id;
  }
    
  if(m_FrameLoadedKnowdeIdString.indexOf(_knowdeId + ',') != 0 &&  m_FrameLoadedKnowdeIdString.indexOf(',' + _knowdeId + ',') == -1)
    toLoadDivs = _knowdeId + ',';
    
  if(_knowdePath != '')
  {
    if(_knowdeId == m_strFrameSelectedKnowdeID)
      m_strFrameSelectedKnowdeContext = _knowdePath;
      
    // unique context found, now need to find out knowdes around the given knowde path
    var pathArray = m_HelpFrame.contentWindow.document.body.childNodes;
    
    var idx = -1;
    for(var icount = 0; icount < pathArray.length; icount++)
    {
      var childDiv = pathArray[icount];
      if(childDiv.id == _knowdePath)
      {
        idx = icount;
        break;
      }
    }
    if(idx >= 0)
    {
      var startIdx = idx - _loadAmount;
      var endIdx = idx + _loadAmount;
      if(startIdx < 0)
        endIdx -= startIdx;
      if(endIdx >= pathArray.length)
        startIdx -= (pathArray.length-1);
      if(startIdx < 0)
        startIdx = 0;
      if(endIdx >= pathArray.length)
        endIdx = pathArray.length - 1;
        
      for(var icount = startIdx; icount <= endIdx; icount++)
      {
        if(pathArray[icount])
        {
          if(m_FrameLoadedKnowdeIdString.indexOf(pathArray[icount].getAttribute('kid') + ',') != 0 &&  m_FrameLoadedKnowdeIdString.indexOf(',' + pathArray[icount].getAttribute('kid') + ',') == -1)
            toLoadDivs += pathArray[icount].getAttribute('kid') + ',';
        }
      }
    }
    
  }
  
  
  return toLoadDivs;
}*/

function HelpFrameDivResize(_frameID)
{
  if(globalShowingWebDoc == false)
  {
    if(navigator.userAgent.indexOf('Safari') != -1)
    {
      var hc = document.getElementById('KGHelpControlID1');
      var row = document.getElementById('HelpControlContent');
      if(hc != null && row != null)
      {
        row.style.height = (hc.style.height.replace('px', '') - 45) + 'px'; //row.parentNode.clientHeight + 'px';
        row.style.width = (hc.style.width.replace('px', '') - 10) + 'px';//row.parentNode.clientWidth + 'px';
      }
    }
      
    /*m_textViewSpanResizeTimeOut = setTimeout('HandleTextViewSpanResize()', 1000); 
   
    if(_frameID == null)
      m_helpFrameScrollTimeOut = setTimeout('HandleHelpFrameScroll()', 1000);
    else
      m_helpFrameScrollTimeOut = setTimeout('HandleHelpFrameScroll("' + _frameID + '")', 1000);*/
  }
}

/*function  SwitchTextViewViewMode_Wrapped(_modeSwitchBtnID, _newMode)
{
  var modeSwitchBtn = document.getElementById(_modeSwitchBtnID);
  var dockedModeSwitchBtn = document.getElementById('DockedTextViewModeSwitch');
  if(_newMode == null)
  {
    if(m_currentTextViewViewMode == "Single")
    {
      // to full text view mode
      m_textViewViewModeChanged = true;
      m_currentTextViewViewMode = "Full";
      m_bHelpFrameLoadSiblingKnowde = false;
      // load full text view
      var currentKnowdeID = m_strFrameSelectedKnowdeID;
      SetSessionProperty('TickerKnowde', currentKnowdeID);
      m_tickerKnowdeID = currentKnowdeID;
      DisplayHintMessage("TextForSpecifiedKnowde"); 
      
      if(modeSwitchBtn != null)
      {
        modeSwitchBtn.className = "ToSingleTextView"; 
      }
      if(dockedModeSwitchBtn != null)
      {
        dockedModeSwitchBtn.className = "ToSingleTextView"; 
      }
    }else if(m_currentTextViewViewMode == "Full")
    {
      // to single text view mode
      //m_textViewViewModeChanged = true;
      m_currentTextViewViewMode = "Single";
      m_bHelpFrameLoadSiblingKnowde = false;
      
      // get the existing seletected knowd div
      var divHtml = '';
      var currentframe = document.getElementById("HelpFrame");
      if(currentframe != null)
      {
        var method = function(el){if(el.getAttribute('kid') == m_strFrameSelectedKnowdeID) return true; return false;};
        var frameDivs = YAHOO.util.Dom.getChildrenBy(currentframe.contentWindow.document.body,method);   
        if(frameDivs.length > 0)
        {
          var childDiv = frameDivs[0];
          divHtml = childDiv.innerHTML;
        }
      }

      // clear frame
      ClearHelpFrame(false);
      
      // set variables like we actually done a callback done
      m_strFrameViewMode = "Single";
      // m_strFrameSelectedKGID, m_strFrameSelectedKnowdeDBID, m_strFrameSelectedKnowdeID remain unchanged
      m_strFrameSelectedKnowdeContext = "";
      m_strFrameCentreKnowdeContext = "";
      
      // load single text view
      if(currentframe != null)
      {
          currentframe.contentWindow.document.write("<html><head><base target='_blank'><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body class='PersonalisedScrollBar' style='overflow:scroll;'>");
          currentframe.contentWindow.document.write(divHtml);
          currentframe.contentWindow.document.write("</body></html>");
      }
      
      helpText = divHtml;
      
      // docked window
      //var dockedDivHtml = '';
      var dockedText = document.getElementById("DockedHelpWindow");
      if (dockedText != null)
      {
       
          dockedText.contentWindow.document.open();
          dockedText.contentWindow.document.write("");
          dockedText.contentWindow.document.close();

          dockedText.contentWindow.document.write("<html><head><base target='_blank'><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body class='PersonalisedScrollBar' style='overflow:scroll;'>");
          dockedText.contentWindow.document.write(helpText);
          dockedText.contentWindow.document.write("</body></html>");
      }
          
      
      if(modeSwitchBtn != null)
      {
        modeSwitchBtn.className = "ToFullTextView"; 
      }
      if(dockedModeSwitchBtn != null)
      {
        dockedModeSwitchBtn.className = "ToFullTextView"; 
      }
    }
  }else
  {
    if(_newMode == "Full")
    {
      // to full text view mode
      m_currentTextViewViewMode = "Full";
      
      if(modeSwitchBtn != null)
      {
        modeSwitchBtn.className = "ToSingleTextView"; 
      }
      if(dockedModeSwitchBtn != null)
      {
        dockedModeSwitchBtn.className = "ToSingleTextView"; 
      }
    }else if(_newMode == "Single")
    {
      // to single text view mode
      m_currentTextViewViewMode = "Single";
      
      if(modeSwitchBtn != null)
      {
        modeSwitchBtn.className = "ToFullTextView"; 
      }
      if(dockedModeSwitchBtn != null)
      {
        dockedModeSwitchBtn.className = "ToFullTextView"; 
      }
    }
  }
}*/

/*function HideOrShowTextViewOptionDiv_Wrapped(_optionDivID, _showOption)
{
//debugger;
  var optionDiv = document.getElementById(_optionDivID);
  var dockedOptionDiv = document.getElementById('DockedHelpWindowTVOptions');
  m_HelpFrame = document.getElementById("HelpFrame");
  if(_showOption != null && _showOption == true)
  {
    if(optionDiv != null)
      optionDiv.style.display = 'block';
    
    if(dockedOptionDiv != null)
      dockedOptionDiv.style.display = 'block';
      
//    if(m_HelpFrame != null)
//      m_HelpFrame.style.height = '95%';

  }
  else
  {
    if(optionDiv != null)
      optionDiv.style.display = 'none';
      
    if(dockedOptionDiv != null)
      dockedOptionDiv.style.display = 'none';
      
//    if(m_HelpFrame != null)
//      m_HelpFrame.style.height = '100%';
  }
  
  //
  // ULTRA IMPORTANT: Showing the option div will resize the iframe.  When this happens, text corruption occurs
  // The below code will refresh the IFrame content.
  //if(!globalShowingWebDoc && document.frames)
     //setTimeout('document.frames[\'HelpFrame\'].location.reload(true)', 1000); 
}*/

/*function HideOrShowHelpControlLoadingDiv_Wrapped(_divId, _show, _message)
{
  if(m_helpFrameLoadingDivTimeOut != null)
  {
    clearTimeout(m_helpFrameLoadingDivTimeOut);
    m_helpFrameLoadingDivTimeOut = null;
  }
  
   var div = null; 
   
   if(_divId != null && _divId != '')
      div = document.getElementById(_divId);
   if(_message == null)
    _message = 'Loading...';
    
   if(_show != null && _show == true && m_helpFrameCallbackStatus != 'trigger')
   {
    // callback done has finished before the trigger time out to show the loading div, 
    // so don't need to show it anymore
    return;
   }
    
   if (div != null)
   {
    if(_show != null && _show == true && div.style.display != 'block')
    {
      var top = 60;
      var left = 172;
      
     // calculate the position based on the textView region
      var parentDiv = div.parentNode;
      
      //if(parentDiv.clientHeight != null && parentDiv.clientHeight != '' && parentDiv.clientHeight > 60)
        //top = 60;
          
      if(parentDiv.clientWidth != null && parentDiv.clientWidth != '' && parentDiv.clientWidth > 0)
        left = parentDiv.clientWidth/2 - 60;
        
      if(left <= 0)
        left = 0;
  
      div.innerHTML = "<img src='Images/LoadingBar.gif' width='21px' height='21px'/>&nbsp;" + _message;
      div.style.top = top + 'px';
      div.style.left = left + 'px';
      div.style.display = 'block';
    }else if(div.style.display != 'none')
    {
      div.style.display = 'none';
      div.innerHTML = '';
      div.style.top = '0px';
      div.style.left = '0px';
    }
   }
   
   // if docked window exists
   var docked = document.getElementById("DockedHelpWindowContainer")
   var dockedText = document.getElementById("DockedHelpWindow");
   if (dockedText != null)
   {
     var dockedLoadingDiv = document.getElementById('DockedHelpWindowLoadingDiv');
     if(dockedLoadingDiv != null)
     {
      if(_show != null && _show == true && dockedLoadingDiv.style.display != 'block')
      {
        var top = 60;
        var left = 50;
        
       // calculate the position based on the textView region
        var parentDiv = div.parentNode;
        
        if(parentDiv.clientWidth != null && parentDiv.clientWidth != '' && parentDiv.clientWidth > 0)
          left = parentDiv.clientWidth/2 - 60;
          
        if(left <= 0)
          left = 0;
    
        dockedLoadingDiv.innerHTML = "<img src='Images/LoadingBar.gif' width='21px' height='21px'/>&nbsp;" + _message;
        dockedLoadingDiv.style.top = top + 'px';
        dockedLoadingDiv.style.left = left + 'px';
        dockedLoadingDiv.style.display = 'block';
      }else if(dockedLoadingDiv.style.display != 'none')
      {
        dockedLoadingDiv.style.display = 'none';
        dockedLoadingDiv.innerHTML = '';
        dockedLoadingDiv.style.top = '0px';
        dockedLoadingDiv.style.left = '0px';
      }
     }
   }

}*/

/*function PreviewFullTextView()
{
  // hide the button
  KGButtonToolbar_hideOrShowPreviewFullTVButton(false);
  
  // set the view mode to full document
  SwitchTextViewViewMode("Full");

  DisplayHintMessage('TextView', '', 'true', Active_KGID);
    
  var MapHelpBox = document.getElementById("KGHelpControlID1");
  if(MapHelpBox != null)
    MapHelpBox.title = "Associated Text";  
}


function HelpFrameScrollTimeOut(_frameID)
{
  if(m_helpFrameScrollTimeOut != null)
  {
      clearTimeout(m_helpFrameScrollTimeOut);
      m_helpFrameScrollTimeOut =  null;
  }
  if(m_bHelpFrameManualScroll == true)
  {
    m_bHelpFrameManualScroll = false;
    return;
  }
  // if in full text view mode and has unloaded textviews, then trigger partial loading
  if(m_FrameUnLoadedKnowdeIdString != '' && globalShowingWebDoc == false && m_strFrameViewMode == "Full")
  {
    if(_frameID == null)
      m_helpFrameScrollTimeOut = setTimeout('HandleHelpFrameScroll()', 2000);
    else
      m_helpFrameScrollTimeOut = setTimeout('HandleHelpFrameScroll("' + _frameID + '")', 2000);
  }
}*/

/*function HandleHelpFrameScroll(_frameID)
{
  if(globalShowingWebDoc == true) //not text view
    return;
    
  //debugger;
  
  if(m_helpFrameScrollTimeOut != null)
  {
      clearTimeout(m_helpFrameScrollTimeOut);
      m_helpFrameScrollTimeOut =  null;
  }
  
    
  //debugger;
  var frameType = '';
  m_HelpFrame = document.getElementById("HelpFrame");
  var helpFrameDiv = null;
  m_DockedHelpFrame = document.getElementById("DockedHelpWindow");
  var dockedFrameDiv = null;
  
  // get frame info and decide which frame to do the partial loading
  var helpFrameWidth = -1;
  var dockedFrameWidth = -1;
  if(m_HelpFrame != null)
  {
    helpFrameDiv = m_HelpFrame.contentWindow.document.body;
    helpFrameWidth = m_HelpFrame.offsetWidth;;
  }
  if(m_DockedHelpFrame != null)
  {
    dockedFrameDiv = m_DockedHelpFrame.contentWindow.document.body;
    dockedFrameWidth = m_DockedHelpFrame.offsetWidth;
  }
  
  var frameDiv = null;
  var frame = null;
  if(_frameID != null && _frameID != '')
    frame = document.getElementById(_frameID);
    
  if(frame == null)
  {
    if(dockedFrameDiv != null && dockedFrameWidth != -1)
    {
      frameType = 'Docked';
      frameDiv = dockedFrameDiv;
      frame = m_DockedHelpFrame;
    }else if(helpFrameDiv != null && helpFrameWidth != -1)
    {
      frameType = 'Popup';
      frameDiv = helpFrameDiv;
      frame = m_HelpFrame;  
    }
  }else
  {
    frameDiv = frame.contentWindow.document.body;
  }
    
  if(frameDiv != null)
  {
    // clear the knowde hover scroll timeout because user now manually scrolling
    clearTimeout(m_helpFrameScrollMoreOnTopTimeOut);
    clearTimeout(m_dockedFrameScrollMoreOnTopTimeOut);

    var scrollTop = frameDiv.scrollTop;
    var visibleStartPosition = scrollTop;
    var visibleEndPosition = scrollTop + frame.offsetHeight;
    var centrePosition = visibleStartPosition + frame.offsetHeight/2;
    
    // also preload stuff that fall into 100px ouside the visible range
    if(visibleStartPosition - 60 <= 0)
      visibleStartPosition = 0
    else
      visibleStartPosition -= 60;
    
    if(visibleEndPosition + 60 >= frameDiv.scrollHeight + 30)
      visibleEndPosition = frameDiv.scrollHeight + 30
    else
      visibleEndPosition += 60;
        
    // check which divs are in visible area
    var visibleDivs = '';
    var toLoadDivs = '';
    var centreID = '';
    var centrePath = '';
      // might need to load top frame contents
      var pos = 0;
            
      
      for(var dividx = 0; dividx < frame.contentWindow.document.body.childNodes.length; dividx++)
      {
        var childDiv = frame.contentWindow.document.body.childNodes[dividx];
        
        if((childDiv.offsetHeight + childDiv.offsetTop >= visibleStartPosition && childDiv.offsetTop <= visibleEndPosition))
        {
          visibleDivs += childDiv.getAttribute('kid') + ',';
          if(childDiv.offsetTop <= centrePosition && childDiv.offsetTop + childDiv.offsetHeight >= centrePosition)
          {
            centreID = childDiv.getAttribute('kid');
            centrePath = childDiv.id;
          }else if(childDiv.offsetTop > centrePosition && centreID == '')
          {
            // the middle point fall into the gap between two divs, sometimes there is a 19px gap between
            centreID = childDiv.getAttribute('kid');
            centrePath = childDiv.id;
          }
          // check whether need to load this div
          if((m_FrameUnLoadedKnowdeIdString.indexOf(childDiv.getAttribute('kid')+',') == 0)
          || (m_FrameUnLoadedKnowdeIdString.indexOf(','+childDiv.getAttribute('kid')+',') != -1))
          {
            toLoadDivs += childDiv.getAttribute('kid') + ',';
          }
        }else if(centreID != '')
          break;
      }

    //alert(centreID + '|' + centrePath + '#' + visibleDivs);
    // store the centre knowde path context
    m_strFrameCentreKnowdeContext = centrePath;
    //alert('Center: ' + centrePath);
        
    if(toLoadDivs != '')
    {
      if(centreID == '' || centrePath == '')
      {
        alert('Invalid centre ID and Path.');
        //debugger;
      }
      else
      {
        m_bHelpFrameLoadSiblingKnowde = true;
        // trigger callback to partial load
        var args = "|KGId=" + m_strFrameSelectedKGID + '|KnowdeId=' + m_strFrameSelectedKnowdeID + '|KnowdePathContext=' + m_strFrameSelectedKnowdeContext + '|KnowdeTitle=|CentreKnowdePathContext=' + centrePath + '|KnowdeIdList=' + toLoadDivs;
        args += "|LoadSiblingKnowde=true";
        args += "|KnowdeLoaded=false";
        args += "|LoadTrigger=Scrolling";
        args += "|ViewMode=Full";
        
        if(m_helpFrameScrollTimeOut != null) // been scroll again
        {
            //clearTimeout(m_helpFrameScrollTimeOut);
            // m_helpFrameScrollTimeOut =  null;
        }else
          KGHelpControl_CallbackTrigger('TextView', args); //, globalHelpTopicParams); //We're no longer using the xml help
      }
    }
    
  }
}*/

/*function SwitchHelpControlMode(_editable)
{
  //debugger;
   
  // open in new window button
  var openWinBtn = document.getElementById("SiteOverlays_KGHelpControl1_OpenInNewWindowButton")
		
  if(_editable != null && _editable == true && globalShowingWebDoc == false)
  {
    // text view edit mode
    var row = document.getElementById('HelpControlContent');
    if(row != null && row.parentNode != null)
    {
      row.parentNode.style.display = 'none';
    }
    var rowt = document.getElementById('TextViewControlContent');
    if(rowt != null && rowt.parentNode != null)
    {
      rowt.parentNode.style.display = 'block';
      rowt.parentNode.style.height = '100%';
      rowt.style.display = 'block';
      rowt.style.height = '99%';
      
      if(navigator.userAgent.indexOf('Safari') != -1)
      {
        // need to assign fix height and width
        rowt.style.height = rowt.parentNode.clientHeight - 2 + 'px';
      }
    }
    
    if(openWinBtn != null)
		  openWinBtn.style.display = "none";
  }
  else
  {
    var rowt = document.getElementById('TextViewControlContent');
    if(rowt != null && rowt.parentNode != null)
    {
      rowt.parentNode.style.display = 'none';
    }
    var row = document.getElementById('HelpControlContent');
    if(row != null && row.parentNode != null)
    {
      row.parentNode.style.display = 'block';
      row.parentNode.style.height = '100%';
      row.style.display = 'block';
      row.style.height = '99%';
      
      if(navigator.userAgent.indexOf('Safari') != -1)
      {
        row.style.height = (row.parentNode.clientHeight - 10) + 'px';
        row.style.width = (row.parentNode.clientWidth - 10) + 'px';
      }
    }
    
    if(openWinBtn != null)
		  openWinBtn.style.display = "";

    
  }
}*/



// JScript File
function Application_UpdateAllForKnowde(_knowdeID)

{ 
  var keys = 'SelectedKGID|MapViewDisplayMode';
	var values = _knowdeID + '|KGMapView';
  SetSessionProperty(keys, values, true);

  // Set the session and refresh in KGServer
  //SetSessionProperty('SelectedKGID', _knowdeID);
  //SetSessionProperty('MapViewDisplayMode', 'KGMapView');
  MapViewControl1_CallbackTrigger();
  //KGTabbedWindowsControl_CallbackTrigger('KnowdeSelected');

} 




// JScript File
var m_newTextVersionControl; // the newTextVersionControl overlay object

function KGNewTextVersionControl_CallbackDone(_args, _context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  if (_args.indexOf("Exception") == -1)
  {
    // 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 + ')');
    
    switch (retMessage.Action)
    {
      case "CreateNewVersion":
        //update m_textViewDocVersion with ID for new Version
        m_textViewDocVersion = retMessage.DocVersionID;
        setTimeout("LoadTextView()",20); //needs a timeout to avoid an infinite loop caused by AJAX problems 
        if (!retMessage.Existing)
        {
          //add to the docVersion Drop down list and set selected
          m_buttonToolbar_docVersionSelect.AddOption(retMessage.Name, retMessage.DocVersionID, m_buttonToolbar_docVersionSelect.newOption);
          var newVersion = eval("[{\"verID\":"+retMessage.DocVersionID+",\"name\":\""+retMessage.Name+"\"}]");
          if (m_KGDocVersionArray != null)
            m_KGDocVersionArray = m_KGDocVersionArray.concat(newVersion);
          else
            m_KGDocVersionArray = newVersion;
          // if this is the first non default text versions, we now need to add the delete option
          if (m_buttonToolbar_docVersionSelect.deleteOption == null)
            m_buttonToolbar_docVersionSelect.AddDeleteOption()
        }
        
        m_newTextVersionControl.Cancel();
        break;
    }
  }
  else
  {
    alert(_args);
  }
}

function KGNewTextVersionControl_CallbackError(_args, _context)
{
  alert(_args);
}

function KGNewTextVersionControl_CallbackTrigger_Wrapped(_args, _callbackScript)
{
  var args;

  // Construct the callback arguments
  if(_args != null)
  { 
    args = _args;
    
    if(args.length > 0)
    {
      // trigger the callback
      eval(_callbackScript);
    }
  }
}

// KGNewTextVersionControl class
function KGNewTextVersionControl()
{
  if (!window.KGNewTextVersionControl_GetTextBox)
    return false;

  this.TextBox = KGNewTextVersionControl_GetTextBox();
  
  this.Open = function()
  {
    if (window.ShowKGNewTextVersionControl)
      ShowKGNewTextVersionControl();
  };
  
  this.Cancel = function()
  {
    // select the current docVersion in the m_buttonToolbar_docVersionSelect
    var optionID = m_buttonToolbar_docVersionSelect.CreateOptionId(m_textViewDocVersion);
    document.getElementById(optionID).selected = true;
    
    // close the NewTextVersionControl
    this.Close();
  };
  
  this.Close = function()
  {
    // clear the textBox
    this.TextBox.value = "";
    if (window.HideKGNewTextVersionControl)
      HideKGNewTextVersionControl();
    
    // enable the drop down list
    m_buttonToolbar_docVersionSelect.select.disabled = false;
  };
  
  this.AddNewTextVersion = function()
  {
    if (this.TextBox != null)
    {
      // TODO: save current Text View version
      SaveTextView();
      
      // get the input text
      var newTextVersionName = this.TextBox.value;
      // callback to this control
      var args = 'Action=CreateNewVersion';
      args += '|Name=' + newTextVersionName;
      args += '|KGID=' + m_buttonToolbar_docVersionSelect.KGID;
      KGNewTextVersionControl_CallbackTrigger(args);
    }
  };
  
  return true;
}

function KGNewTextVersionControl_GetTextBox_Wrapped(_textBoxId)
{
  var textBox = document.getElementById(_textBoxId);
  return textBox;
}


var m_deleteTextVersionControl; // the deleteTextVersionControl overlay object

function KGDeleteTextVersionControl_CallbackDone(_args, _context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  if (_args.indexOf("Exception") == -1)
  {
    // 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 + ')');
    
    switch (retMessage.Action)
    {
      case "DeleteVersions":
        
        for (versionIndex in retMessage.DeletedVersions)
        {
          m_buttonToolbar_docVersionSelect.Remove(retMessage.DeletedVersions[versionIndex]);
          // remove any entries with this verID from the m_KGDocVersionArray
          for(var k=m_KGDocVersionArray.length-1; k >=0 ; k--)
          {
            if(m_KGDocVersionArray[k].verID == retMessage.DeletedVersions[versionIndex])
              m_KGDocVersionArray.splice(k,1);
            if (m_textViewDocVersion == retMessage.DeletedVersions[versionIndex])
              m_textViewDocVersion = null;
          }
          
          // remove any entries with this verID from the m_KnowdeDocVersionArray
          for(var k=m_KnowdeDocVersionArray.length-1; k >=0 ; k--)
          {
            if(m_KnowdeDocVersionArray[k].verID == retMessage.DeletedVersions[versionIndex])
              m_KnowdeDocVersionArray.splice(k,1);
          }
        }
        
        // if there are no more versions, remove the delete option
        if (m_KGDocVersionArray == null || m_KGDocVersionArray.length <= 0)
          m_buttonToolbar_docVersionSelect.Remove("delete");
        m_deleteTextVersionControl.Cancel();
        break;
    }
  }
  else
  {
    alert(_args);
  }
}

function KGDeleteTextVersionControl_CallbackError(_args, _context)
{
  alert(_args);
}

function KGDeleteTextVersionControl_CallbackTrigger_Wrapped(_args, _callbackScript)
{
  var args;

  // Construct the callback arguments
  if(_args != null)
  { 
    args = _args;
    
    if(args.length > 0)
    {
      // trigger the callback
      eval(_callbackScript);
    }
  }
}

// KGDeleteTextVersionControl class
function KGDeleteTextVersionControl()
{
  if (!window.KGDeleteTextVersionControl_GetVersionsBox)
    return false;
  
  this.VersionsBox = KGDeleteTextVersionControl_GetVersionsBox();
  
  this.Open = function()
  {
    if (window.ShowKGDeleteTextVersionControl)
    {
      this.Populate(m_KGDocVersionArray)
      ShowKGDeleteTextVersionControl();
    }
  };
  
  this.Cancel = function()
  {
    // select the current docVersion in the m_buttonToolbar_docVersionSelect
    var optionID = m_buttonToolbar_docVersionSelect.CreateOptionId(m_textViewDocVersion);
    document.getElementById(optionID).selected = true;
    
    // close the DeleteTextVersionControl
    this.Close();
  };
  
  this.Close = function()
  {
    if (window.HideKGDeleteTextVersionControl)
      HideKGDeleteTextVersionControl();
    
    // enable the drop down list
    m_buttonToolbar_docVersionSelect.select.disabled = false;
  };
  
  this.DeleteTextVersions = function()
  {
    if (this.VersionsBox != null)
    {      
      // TODO: get the selected versions
      var selectedValues = this.SelectedValues()
      
      if (selectedValues.length > 0)
      {
        var values = selectedValues[0];
        
        for (var index=1; index < selectedValues.length; index++)
        {
          values += ',' + selectedValues[index];
        }
        
        // callback to this control
        var args = 'Action=DeleteVersions';
        args += '|Versions=' + values;
        args += '|KGID=' + m_buttonToolbar_docVersionSelect.KGID;
        KGDeleteTextVersionControl_CallbackTrigger(args);
      }
      else
      {
        alert('No Selected Text Versions')
      }
    }
  };
  
  this.Initialise = function()
  {
    // clear all entries in the droplist
    while (this.VersionsBox.length > 0)
    {
      this.VersionsBox.remove(this.VersionsBox.length-1);
    }
  };
  
  // generates an element id for an option in the list
  this.CreateOptionId = function(_value)
  {
    if (_value == null)
      _value = "default";
    
    return this.VersionsBox.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.VersionsBox.add(docVersion, _before); // standards compliant
      }
      catch(ex)
      {
        this.VersionsBox.add(docVersion, _before.index); // IE only
      }
    }
    else
    {
      try
      {
        this.VersionsBox.add(docVersion, null); // standards compliant
      }
      catch(ex)
      {
        this.VersionsBox.add(docVersion); // IE only
      }
    }
    
    return docVersion;
  };
  
  // adds each entry in the _docVersions array to the listbox
  this.Populate = function(_docVersions)
  {
    // clear the list box
    this.Initialise();    
    
    if (_docVersions != null)
    {
      // loop through _docVersions array
      for (var arrayIndex=0; arrayIndex < _docVersions.length; arrayIndex++)
      {
        this.AddOption(_docVersions[arrayIndex].name, _docVersions[arrayIndex].verID);
      }
    }
  };
  
  this.SelectedValues = function ()
  {
    var selectedValues = new Array();
    
    for (var index=0; index < this.VersionsBox.options.length; index++)
    {
      if (this.VersionsBox.options[index].selected)
      {
        selectedValues.push(this.VersionsBox.options[index].value);
      }
    }
    
    return selectedValues;
  };
  
  return true;
}

function KGDeleteTextVersionControl_GetVersionsBox_Wrapped(_versionsBoxId)
{
  var versionBox = document.getElementById(_versionsBoxId);
  return versionBox;
}
// CommunitySpace.js

/*
JS File containing functions relating to the Communityspace web control
*/

// Button event handler for creating a sub level private space
function CommunitySpace_CreateSubLevel_Wrapped(_cbreference, _textBoxID)
{
  //debugger;
  try
  {
    var txtBox = document.getElementById(_textBoxID);
    
    if(txtBox != null && checkForInvalid(txtBox) == true)
    {
      var args = 'Action=AddSubLevelCS|Text=' + txtBox.value;
      eval(_cbreference);      
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

// Button event handler for creating a top level private space
function CommunitySpace_CreateTopLevel_Wrapped(_cbreference, _textBoxID)
{
  //debugger;
  try
  {
    var txtBox = document.getElementById(_textBoxID);
    
    if(txtBox != null && checkForInvalid(txtBox) == true)
    {
      var args = 'Action=AddTopLevelCS|Text=' + txtBox.value;
      eval(_cbreference);
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function CommunitySpace_CallbackDone_Wrapped(args, context, _contentTable)
{
	//debugger;
  try
  {
    // Check for a session time out before completing the callback
    if (CheckSessionTimeout())
      return;
    
    var contentTable = document.getElementById(_contentTable);
		if(contentTable != null)
		{
			SetOuterHtml(contentTable,args);  
    }   
    
    if(args.indexOf('successfully') > -1)
    {
      setTimeout("PostbackReload()", 50);
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function CommunitySpace_ProcessCallBackError_Wrapped(args, context, clientId)
{
  //debugger;
  try
  {


  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function checkForInvalid(obj) 
{
  //debugger;
  try
  {
    if( obj.value.length < 1 || obj.value.length > 50)
    {
		  alert("Please enter a valid Community Space Name.")
		  obj.focus();
		  obj.select();
		  return false;
	  }
	  
	  return true;
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function PostbackReload() 
{
  //debugger;
  try
  {
    var currentLocation = window.location.href;
    var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
    window.location = hostURL + 'ConfigureCommunitySpace.aspx';
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

// CallbackDone
function KGProfileVisibilityControl_CallbackDone(args, context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
}

// CallbackError Handling
function KGProfileVisibilityControl_CallbackError(args, context)
{
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    //debugger;
    alert(args);
  }
}




function KGProfileVisibilityControl_ToggleVisible_Wrapped(_imageClientID, _section, _cbreference, e)
{
  try
  {
    var image = document.getElementById(_imageClientID);
    
    if(image != null)
    {
      var args = 'Action=ToggleVisible|SectionID=' + _section;
      
      if(image.className.indexOf("VisibilityControlHide") > -1)
      {
        args += '|Visibility=false';
        //image.src = 'Images/ProfileShow.png';
        image.className = 'VisibilityControlShow';
      }
      else
      {
        args += '|Visibility=true';
        //image.src = 'Images/ProfileHide.png';
        image.className = 'VisibilityControlHide';
      }
      eval(_cbreference);      
    }
    CancelBubble(e);
  }
  catch (ex) 
  {
    alert("An exception occurred in the script. Error name: " + ex.name + ". Error message: " + ex.message); 
    debugger;
  } 
}

function viewPublicProfile()
{
  var args = "Action=Load|ViewPublic=true";
  Pfl_KGMemberControl_CallbackTrigger(args);
}

function backToPrivateProfile()
{
  var args = "Action=Load|ViewPublic=false";
  Pfl_KGMemberControl_CallbackTrigger(args);
}

var TextViewHowContext = new Array();
var TextViewWhyContext = new Array();

var m_SavingDiv = null;

var m_EditFrameDiv = null;
var m_KnowdeIdList = new Array();
var m_KnowdeIdString = '';
var m_FrameContentList = '';

var m_EditFrame = null;
var m_UploadWindow = null;
var m_bTextViewWritable = new Boolean(false);
var m_bTextViewWritableModeChanged = new Boolean(false);
var m_strSelectedKGID = '';
var m_strSelectedKnowdeID = '';
var m_strPreviousSelectedKnowdeID = '';
var m_bLoadSiblingKnowde = new Boolean(false);
var m_frameHeightMargin = 30;
var m_editFrameHeightMargin = 20;

var m_textViewHighlightColor = '#FFFFFF'; //EFF0C2 F2F3CF;F3F4D7;FBFBEE;FFFFFF; FBFBEE; EAF4F7
var m_textViewTickerSelectionHighlightColor = '#bbe0e3'; // As per KGTickerControl.css
var m_noTextViewFoundContent = "<img src='images/clickedit.png'>";
var m_noTextViewFoundAddYourOwn = "<img src='images/clickedit_owntext.png'>";
var m_notLoadedText = "Loading, please wait...";
var m_clickToWriteText = "";//"<img src='images/clickedittext.png' onmouseover='bubbleMouseOver(event,\"Load TextView\")' onmouseout='bubbleMouseOut(event)'>";
var m_bShowClickEditHint = 0;
var m_textViewChanged = 0;

// auto save when editing
var m_autoSaveTimeOut = null;
// in seconds
var m_autoSaveInactivePeriod = 4; 
var m_autoSaveInterval = 15; 
var m_lastAutoSaveTime = null;

var m_butTVSave; // the save button
var m_WritableButtons; // span containing all the buttons for when the text view is writable

//var m_LoadingMessage = "<div id='TextViewLoadingDiv' class='SavingMessage'><img src='Images/LoadingBar.gif'>Loading...</div>";
var m_LoadingMessage = "<table id='TextViewLoadingDiv' width=\"100%\" class='border: solid 1px Gray; font-size:xx-small; width: 120px;'><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>";

var m_Content = new String();

var m_bAutoSwitchEditMode = 0;
var m_bAutoEnterEditMode = 0;

var m_textViewPreLoadAmount = 3;

var m_changeTabbedControlAfterSaving = null;

var m_textViewMode = "KNOWDEDOC";
var m_textViewDocVersion = null;

// flag to indicate whether the what text is in edit mode
var m_bWhatTextWritable = false;

/////////////////
// Processes the message that comes back from all the AJAX calls made to the Text View control
function TextView_CallbackDone(_args, _context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  m_bAutoSwitchEditMode = 0;
  m_bAutoEnterEditMode = 0;
  // if the string "Exception:" occurs or it is zero length then something has gone wrong
  if(_args.length == 0 || _args.indexOf("Exception:") >= 0)
    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
  if(_args.indexOf("{", 0) == 0)
  {
    var idx = _args.indexOf('|');
    var returnMessage = _args;
    var content = '';
    if(idx > -1)
    {
      returnMessage = _args.substr(0,idx);
      content = _args.substr(idx+1);
    }
    
    var retMessage = eval( '(' + returnMessage + ')'); 
 
    if(retMessage.OK == true)
    {
      switch(retMessage.Action)
      {
        case "Save":
          if (m_textViewMode == "KNOWDEDOC")
            HandleTextViewSaveComplete(retMessage, content);
          else if (m_textViewMode == "HKGROUPDOC")
            ShowOrHideSavingDiv(0,null,0,0);
          break; 
        case "Load":
          if(m_bTextViewWritable == false)
          {
            var m_EditFrameDiv = document.getElementById('TextViewEditFrameDiv');
            // set the global var
            m_textViewMode = retMessage.TextViewMode;
            if (m_textViewMode == "KNOWDEDOC")
            {
              m_EditFrameDiv.innerHTML = "<div class='EditMessage' align=center><img src='Images/ClickEdit.png'></div>";
            }
            else if (m_textViewMode == "HKGROUPDOC")
            {
              var values = _args.split('|');
              var content = values[1];
              
              if (!content)
                content = "";
              
              // clear the iframe div
              m_EditFrameDiv.innerHTML = "";
              // load the iframe
              HandleHKGroupDocLoad(content);
              SetTextViewToolbarWritable();
            }
          }
          break;
        case "AutoSave":
          if (m_textViewMode == "KNOWDEDOC")
            HandleTextViewSaveComplete(retMessage, content);
          else if (m_textViewMode == "HKGROUPDOC")
            ShowOrHideSavingDiv(0,null,0,0);
          break; 
      }
    }else
    {
      if(retMessage.Action == 'Save' || retMessage.Action == 'AutoSave')
      {
        HandleTextViewSaveFailure(retMessage);
        alert("Failed to save text view."); 
      }
    }
  }
  else
  {
    var values = _args.split('|');
    // set selected knowde id
    var ids = values[0].split('@');
    // get old kgId
    var oldKGID = m_strSelectedKGID;
    // set kgId
    m_strSelectedKGID = ids[0];
    // use client Id for the moment
    m_strSelectedKnowdeID = ids[2];
    
    if(oldKGID != m_strSelectedKGID)
    {
      // kg changed
      ClearTextViewValues();
    }
    
    if(m_bTextViewWritable == true)
      m_bAutoEnterEditMode = 1;
    else
    {
      if(m_bEditable == true || m_bWhatTextWritable == true)
      {
        // trigger textview editing
        m_bAutoSwitchEditMode = 1;
        // clear auto save status
        SetAutoSaveButtonStatus(-1);
      }
    }
    
    m_EditFrameDiv = document.getElementById('TextViewEditFrameDiv');

    if(m_EditFrameDiv != null)
    {
      // load all textviews
      HandleTextViewLoadAll(values[1]);
    }
    
  }
  
}

function AutoEnterEditMode()
{
  //SetupKnowdeTextViewDisableDivs();
  SetTextViewToolbarWritable();
  //setTimeout('LoadEditFrameContent()',10);
}

function ClearTextViewValues()
{
  //debugger;
  m_bLoadSiblingKnowde = false;
}

function ResetTextView()
{
  //debugger;
  m_bLoadSiblingKnowde = false;
  m_bTextViewWritable = false;

  m_KnowdeIdList = new Array();
  m_KnowdeIdString = '';
  m_FrameContentList = '';
  
  m_autoSaveTimeOut = null;
}

function AdjustEditFrameSize()
{
  if (m_EditFrame.contentWindow.document.body != null)
  {
    m_EditFrame.style.height = m_EditFrame.contentWindow.document.body.scrollHeight + m_editFrameHeightMargin + 'px';
    if(m_EditFrame.contentWindow.document.body.scrollWidth <= m_EditFrame.parentNode.clientWidth)
       m_EditFrame.style.width = m_EditFrame.parentNode.clientWidth + 'px';
    else
       m_EditFrame.style.width = m_EditFrame.contentWindow.document.body.scrollWidth + 'px';
  }
}

function HandleTextViewLoadAll(_contentList)
{
  m_EditFrameDiv = document.getElementById('TextViewEditFrameDiv');
  
  if(m_bLoadSiblingKnowde == false)
  {
    m_KnowdeIdList = new Array();
    m_KnowdeIdString = '';
    m_FrameContentList = _contentList;
  //}
    // creat iframes
    var sidx = _contentList.indexOf('<HKTextView');
    var sidx2 = _contentList.indexOf('>', sidx);
    var sidx3 = _contentList.indexOf('</HKTextView>', sidx2);
    while(sidx != -1 && sidx2 != -1 && sidx3 != -1)
    {
      var content = _contentList.substr(sidx2+1, sidx3-(sidx2+1));
      var kid = _contentList.substr(sidx+11,sidx2-(sidx+11));
      var bWriteFrame = 0;
      
      //if(m_bLoadSiblingKnowde == false)
      //{
        m_KnowdeIdList.push(kid);
        m_KnowdeIdString += kid + ','
        
        var frame = document.createElement("iframe");
        frame.setAttribute("id", "TextViewEditFrame-k" + kid);
        frame.setAttribute("frameborder", "0");
        //frame.setAttribute("style", "width: 100%; height: 100%;");
        //frame.setAttribute("height", "97%");
        frame.setAttribute("scrolling", "no");
        //frame.setAttribute("height", "auto");

        InsertAdjacentElement(m_EditFrameDiv,"beforeEnd", frame);
        
        if (frame.addEventListener) 
        {
          frame.contentWindow.addEventListener('focus', TextViewControl_onFocus_Timer, false);
          frame.contentWindow.addEventListener('click', TextViewControl_onFocus_Timer, false);
        } else if (frame.attachEvent) {
          frame.attachEvent('onfocus', TextViewControl_onFocus);
        }    
        
        bWriteFrame = 1;
      /*}else if(kid == m_strPreviousSelectedKnowdeID)
      {
        var frame = document.getElementById("TextViewEditFrame-k" + kid);
        if(frame != null && frame.contentWindow.document != null 
        && frame.contentWindow.document.designMode.toLowerCase() == "off" && m_bTextViewWritable)
        {
          bWriteFrame = 1;
        }
      }*/
          
      var bidx = content.toLowerCase().indexOf('<body');
      var bidx2 = content.indexOf('>');
      var bidx3 = content.toLowerCase().indexOf('</body>');
      if(bidx != -1 && bidx2 > bidx && bidx3 > bidx2)
        content = content.substr(bidx2+1, bidx3-(bidx2+1));
        
      if(content == '')
      {
        content = m_noTextViewFoundContent;
      }
      
      var divHtml = "<div id='k" + kid + "' width='100%' style='position: relative;'><div id='k" + kid + "-active' width='100%' style='top:0px;left:0px;'>";
      if (content.indexOf(m_textViewTickerSelectionHighlightColor) > -1)
        content = ReturnUnhighlightedTickerText(content);
      divHtml += content;
      divHtml += "</div></div>";

     // if(bWriteFrame == 1)
      //{
        frame.contentWindow.document.open();
        frame.contentWindow.document.write("<html><head><base target='_blank'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body style='border: 0px;'>"); //class='PersonalisedScrollBar' 
        frame.contentWindow.document.write(divHtml);
        frame.contentWindow.document.write("</body></html>");
        frame.contentWindow.document.close();
        
        //if(m_bLoadSiblingKnowde == false)
        //{
          // don't show it yet, can't set to invisible because it will cause the div inside won't have offset height 
          frame.style.height = '0px';
        //}
     //}
      
      _contentList = _contentList.substr(sidx3+13);
      sidx = _contentList.indexOf('<HKTextView');
      sidx2 = _contentList.indexOf('>', sidx);
      sidx3 = _contentList.indexOf('</HKTextView>', sidx2);
    }
  }
  
  window.setTimeout("SetupKnowdeTextViewDivs(" + m_bAutoSwitchEditMode + "," + m_bAutoEnterEditMode + ")",15);
    
  m_bAutoSwitchEditMode = 0;
  m_bAutoEnterEditMode = 0;
        
}

function HandleHKGroupDocLoad(_content)
{
//debugger;
  m_EditFrameDiv = document.getElementById('TextViewEditFrameDiv');
  
  var content = _content;
  var bWriteFrame = 0;
  
  var frame = document.createElement("iframe");
  frame.setAttribute("id", "TextViewEditFrame");
  frame.setAttribute("frameborder", "0");
  frame.setAttribute("width", "100%");
  frame.setAttribute("scrolling", "no");
  //frame.setAttribute("height", "auto");
  
  InsertAdjacentElement(m_EditFrameDiv,"beforeEnd", frame);
  
  if (frame.addEventListener)
  {
    frame.contentWindow.addEventListener('focus', TextViewControl_onFocus_Timer, false);
    frame.contentWindow.addEventListener('click', TextViewControl_onFocus_Timer, false);
  }
  else if (frame.attachEvent)
  {
    frame.attachEvent('onfocus', TextViewControl_onFocus);
  }    
  
  bWriteFrame = 1;
  
  var bidx = content.toLowerCase().indexOf('<body');
  var bidx2 = content.indexOf('>');
  var bidx3 = content.toLowerCase().indexOf('</body>');
  if(bidx != -1 && bidx2 > bidx && bidx3 > bidx2)
    content = content.substr(bidx2+1, bidx3-(bidx2+1));
  
  var divHtml = "<div width='100%' style='position: relative;'>" + content + "</div>";
  
  frame.contentWindow.document.open();
  frame.contentWindow.document.write("<html><head><base target='_blank'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body style='border: 0px;'>"); //class='PersonalisedScrollBar' 
  frame.contentWindow.document.write(divHtml);
  frame.contentWindow.document.write("</body></html>");
  frame.contentWindow.document.close();
  
  //frame.style.height = '0px';
  
  m_bAutoSwitchEditMode = 0;
  m_bAutoEnterEditMode = 0;        
}

function SetupKnowdeTextViewDivs(_autoSwitchEditMode, _autoEnterEditMode)
{
  m_EditFrameDiv = document.getElementById('TextViewEditFrameDiv');

  var loadingDiv = document.getElementById('TextViewLoadingDiv');
  if(loadingDiv != null)
  {
    purge(loadingDiv);
    loadingDiv.parentNode.removeChild(loadingDiv);
  }

  for(var k = 0; k < m_KnowdeIdList.length; k++)
  {
    var id = m_KnowdeIdList[k];
    SetupKnowdeTextViewDiv(id);
  }
  
  if(_autoSwitchEditMode != null && _autoSwitchEditMode == 1 && (m_bEditable == true || m_bWhatTextWritable == true) && m_bTextViewWritable != true)
    SwitchTextViewEditing(); //window.setTimeout("SwitchTextViewEditing()",1);
  else if(_autoEnterEditMode != null && _autoEnterEditMode == 1 && m_bTextViewWritable == true)
    AutoEnterEditMode(); //window.setTimeout("AutoEnterEditMode()",1);
}

function SetupKnowdeTextViewDiv(_id)
{
//debugger;
  var editFrame = document.getElementById("TextViewEditFrame-k"+_id);
  if(editFrame != null)
  {
    //editFrame.style.height = '97%';
    //editFrame.style.width = '100%';
    // commented out for now as it's not working if put the textview control in overlay control
    var div = editFrame.contentWindow.document.getElementById('k'+_id);
    var adiv = editFrame.contentWindow.document.getElementById('k' + _id + '-active');
    var gdiv = editFrame.contentWindow.document.getElementById('k' + _id + '-disable');

    if(div != null)
    {
       if(adiv != null)
       {
          editFrame.style.height = adiv.offsetHeight + m_frameHeightMargin + 'px'; 
       }
       else
       {
        editFrame.style.height = div.offsetHeight + m_frameHeightMargin + 'px'; 
       }
    }else if(editFrame.contentWindow.document != null && editFrame.contentWindow.document.body != null
            && editFrame.contentWindow.document.body.scrollHeight > 0)
    {
      if(editFrame.contentWindow.document.designMode.toLowerCase() == 'on')
      {
        editFrame.style.height = editFrame.contentWindow.document.body.scrollHeight + m_frameHeightMargin + m_editFrameHeightMargin + 'px';
        //debugger;
        if(editFrame.contentWindow.document.body.scrollWidth <= editFrame.parentNode.clientWidth)
          editFrame.style.width = editFrame.parentNode.clientWidth + 'px';
        else
          editFrame.style.width = editFrame.contentWindow.document.body.scrollWidth + 'px';
      }
      else
        editFrame.style.height = editFrame.contentWindow.document.body.scrollHeight + m_frameHeightMargin + 'px';
    }
    // resize gray out div if exists
    if(gdiv != null)
    {
      if(editFrame.style.height != '' && editFrame.style.width != '')
      {
        gdiv.style.height = editFrame.style.height;
        gdiv.style.width = editFrame.style.width;
      }
    }
    //div.style.display = 'block';
    // highlight selected knowde textview if in read only mode
    if(div != null && _id == m_strSelectedKnowdeID)
    {
      if(m_bTextViewWritable == false)
        div.style.backgroundColor = m_textViewHighlightColor;
        
      // auto scroll to the position
      if(m_EditFrameDiv == null)
        m_EditFrameDiv = document.getElementById('TextViewEditFrameDiv');
      if(m_EditFrameDiv != null && editFrame.offsetTop >= 0)
        m_EditFrameDiv.scrollTop  = editFrame.offsetTop;

    }else if(div != null && m_bTextViewWritable == false)
    {
      div.style.backgroundColor = ''; 
    }
  }
}

function TextViewDivResize()
{
  m_EditFrameDiv = document.getElementById("TextViewEditFrameDiv");
  if(m_EditFrameDiv != null && m_KnowdeIdList !=  null && m_KnowdeIdList.length > 0)
    SetupKnowdeTextViewDivs();
}

function SetupKnowdeTextViewDisableDivs()
{
  if(m_KnowdeIdList != null && m_KnowdeIdList.length > 0)
  {
    for(var k = 0; k < m_KnowdeIdList.length; k++)
    {
      var id = m_KnowdeIdList[k];
      SetupKnowdeTextViewDisableDiv(id);
    }
  }
}

function SetupKnowdeTextViewDisableDiv(_id)
{
  var editFrame = document.getElementById("TextViewEditFrame-k"+_id);
  if(editFrame != null)
  {
    var div = editFrame.contentWindow.document.getElementById('k'+_id);
    var adiv = editFrame.contentWindow.document.getElementById('k' + _id + '-active');
    var gdiv = editFrame.contentWindow.document.getElementById('k' + _id + '-disable');

    if(m_bTextViewWritable == true)
    {
      // edit mode, create greyout div for read only knowdes' textviews
      if( _id != m_strSelectedKnowdeID)
      {
        if(div != null && adiv != null && gdiv == null)
        { 
          // create greyout layer
          gdiv = editFrame.contentWindow.document.createElement("div");
          gdiv.setAttribute("id",'k' + _id+"-disable");
          gdiv.style.width = adiv.offsetWidth; // editFrame.clientWidth; // div.offsetWidth + 'px';
          gdiv.style.height = adiv.offsetHeight; //editFrame.clientHeight; // div.offsetHeight + 'px';
          gdiv.style.position = "absolute";
          gdiv.style.padding = "0px 0px 0px 0px";
          gdiv.style.top = "0px";
          gdiv.style.left = "0px";
          gdiv.style.background = 'white';
          gdiv.style.opacity = .70;
          gdiv.style.filter = 'alpha (opacity=70)';
          
          InsertAdjacentElement(adiv,"afterEnd", gdiv);
        }else
        {
          //debugger;
        }
      }
    }else
    {
      // read only mode, clear greyout div
      if(div != null && adiv != null && gdiv != null)
      {
        purge(gdiv);
        div.removeChild(gdiv);
      }
    }
    
  }
}

function GetDefaultTextViewContentWithTitle(_knowdeID, _title, _withImg, _image)
{
  //debugger;
  // get current knowde text
  var defaultContent = '';
  var kndText = _title;
  if(kndText == null || kndText == '')
  {
    var kndObj = document.getElementById(Active_KGID + KGIDPrefixSeperator + "knowde" + _knowdeID);
    if(kndObj != null)
       kndText = kndObj.getAttribute('verb') + " " + kndObj.getAttribute('noun');
    else
    {
      // what or whatIs
      if(globalLastHighlightedWhat != null)
      {
        kndText = GetInnerText(globalLastHighlightedWhat);
        var verbText = QueryVerbElement(CurrentWhatRootKnowde);
        if(typeof(verbText) == "object" && verbText != null)
          kndText =  GetInnerText(verbText) + " " + kndText;
      }
    }
  }
  if(_withImg == 1 && (_image == null || _image.length <= 0))
    _image = m_clickToWriteText;
    
  if(kndText != '')
  {
     defaultContent = "<h3 id='knowdeTitle'>" + kndText + "</h3>";
     defaultContent += "<div style='MARGIN-LEFT: 10px;'><p>"
     if(_withImg == null || _withImg == 1)
      defaultContent += _image;
     defaultContent += "</p></div>";
   }else
    defaultContent = _image;
    
  return defaultContent;
}

function WrapTextViewContentWithTitle(_knowdeID, _title, _content)
{
  // some text view format will causing the textview common object return the body tag as well
  if(_content.toLowerCase().indexOf('<body') != -1)
  {
    var btag1 = _content.toLowerCase().indexOf('<body');
    if(btag1 == 0)
    {
      var btag2 = _content.toLowerCase().indexOf('>', 0);
      if(btag2 > 0)
      {
        // get rid of body start tag
        _content = _content.substring(btag2+1);
        // get rid of body end tag
        var btag3 = _content.toLowerCase().indexOf('</body>');
        if(btag3 > 0)
          _content = _content.substring(0, btag3) + _content.substring(btag3+7);
      }
      
    }
  }

  var defaultContent = _content;
  var kndText = _title;
  if(kndText != '' && _content != null)
  {
     var lc = _content.toLowerCase().replace(/^(<br\/>|<br \/>|<p\/>|<p><\/p>|<p \/>|<p><br \/><\/p>|<p><br\/><\/p>)+/i,'');
     var sidx = lc.indexOf('<h3');
     var cidx = lc.indexOf('/>',sidx);
     var cidx2 = lc.indexOf('>',sidx);
     var cidx3 = lc.indexOf('</h3>',sidx);
     if(sidx == 0 && cidx3 != -1 && cidx2 != -1 && cidx3 >= cidx2+1 && (cidx == -1 || cidx > cidx3)
       && lc.substring(sidx, cidx2).indexOf('knowdetitle') != -1)
     {
        // if the title tag already exists and is empty
        var title = lc.substring(cidx2+1, cidx3);
        var count = 0;
        title = title.replace(' ','');
        title = title.replace('&nbsp;','');
        for(var ci=0; ci<title.length; ci++ )
        {
          if(title.charCodeAt(ci) == 160)
          {
            // get rid of charcode 160 white space
          }else
          {
            count++;
            break;
          }
        }
        if(count <= 0)
        {
          // put the knowde title in
          var titleTag = lc.substring(sidx, cidx3+5);
          var s1 = _content.toLowerCase().indexOf(titleTag);
          defaultContent = _content.substring(0, s1) + "<h3 id='knowdeTitle'>" + kndText + "</h3>" + _content.substring(s1 + titleTag.length);
        }
     }
     else
     {
       // add the title in
       defaultContent = "<h3 id='knowdeTitle'>" + kndText + "</h3>";
       defaultContent += "<div style='MARGIN-LEFT: 10px;'><p>"
       defaultContent += _content;
       defaultContent += "</p></div>";
     }
  }
    
  return defaultContent;
  
  
}

function CheckTextViewHasTitle(_knowdeID, _title, _content)
{
  var hasTitle = true;
  var lc = _content.toLowerCase().replace(/^(<br\/>|<br \/>|<p\/>|<p><\/p>|<p \/>|<p><br \/><\/p>|<p><br\/><\/p>)+/i,'');
  // some text view format will causing the textview common object return the body tag as well
  if(lc.indexOf('<body') != -1)
  {
    var btag1 = lc.indexOf('<body');
    if(btag1 == 0)
    {
      var btag2 = lc.indexOf('>', 0);
      if(btag2 > 0)
        lc = lc.substring(btag2+1);
    }
    else
    {
      return true; // not sure how to deal with this format yet, so return true by default
    }
  }
  
  if(lc.indexOf('<h1') == 0 || lc.indexOf('<h2') == 0 || lc.indexOf('<h3') == 0)
  {
    var cidx = lc.indexOf('/>',0);
    var cidx2 = lc.indexOf('>',0);
    var cidx3 = lc.indexOf('</',0);
    // if the tag is not empty
    if(cidx3 != -1 && cidx2 != -1 && cidx3 > cidx2+1 && (cidx == -1 || cidx > cidx3))
    {
       var title = lc.substring(cidx2+1, cidx3);
        var count = 0;
        title = title.replace(' ','');
        title = title.replace('&nbsp;','');
        for(var ci=0; ci<title.length; ci++ )
        {
          if(title.charCodeAt(ci) == 160)
          {
            // get rid of charcode 160 white space
          }else
          {
            count++;
            break;
          }
        }
      if(count <= 0)
      {
        hasTitle = false;
      }
    }
    else
    {
      hasTitle = false;
    }
  }
  else
  {
    hasTitle = false;
  }
    
  return hasTitle;

}

function GetCurrentKnowdeTextForTextView(_knowdeID)
{
  var kndText = '';
  var kndObj = document.getElementById(Active_KGID + KGIDPrefixSeperator + "knowde" + _knowdeID);
  if(kndObj != null)
     kndText = GetInnerText(QueryVerbElement(kndObj)) + " " + GetInnerText(QueryNounElement(kndObj));   
  else
  {
    // what or whatIs
    kndObj = document.getElementById(Active_KGID + KGIDPrefixSeperator + "what" + _knowdeID);
    if(kndObj == null)
      kndObj = document.getElementById(Active_KGID + KGIDPrefixSeperator + "whatis" + _knowdeID);
      
    if(kndObj != null)
    {
      kndText = GetInnerText(kndObj);
      var verbText = QueryVerbElement(CurrentWhatRootKnowde);
      if(typeof(verbText) == "object" && verbText != null)
        kndText =  GetInnerText(verbText) + " " + kndText;
    }
  }
  
  return kndText;
}

function GetDefaultTextViewContent(_knowdeID, _withImg)
{
  // get current knowde text
  var defaultContent = '';
  var kndText = GetCurrentKnowdeTextForTextView(_knowdeID);

  if(kndText != '')
  {
     defaultContent = "<h3 id='knowdeTitle'>" + kndText + "</h3>";
     defaultContent += "<div style='MARGIN-LEFT: 10px;'><p>"
     if(_withImg == null || _withImg == 1)
      defaultContent += m_clickToWriteText;
     defaultContent += "&nbsp;</p></div>"; // need the space here for firefox otherwise can focus on the paragraph
   }else
    defaultContent = m_clickToWriteText;
    
  return defaultContent;
}

function UpdateTextViewKnowdeTitle(_oldTitle, _newTitle)
{
  //debugger;
  m_EditFrame = document.getElementById("TextViewEditFrame-k"+m_strSelectedKnowdeID);
  if(m_EditFrame != null && m_EditFrame.contentWindow && m_EditFrame.contentWindow.document != null)
  {
    var titleHeading = m_EditFrame.contentWindow.document.getElementById('knowdeTitle');
    if(titleHeading == null)
      return;
    // only auto update the title if it's the default one which is the knowde text
    var tvKndTitle = GetInnerText(titleHeading).toLowerCase();
    var oldTitle = _oldTitle.toLowerCase();
    tvKndTitle = tvKndTitle.replace('\u00A0','<@HKSpace@>');
    tvKndTitle = tvKndTitle.replace(' ','<@HKSpace@>');
    oldTitle = oldTitle.replace('\u00A0','<@HKSpace@>');
    oldTitle = oldTitle.replace(' ','<@HKSpace@>');
    if(tvKndTitle == oldTitle)
    {
      SetInnerText(titleHeading,_newTitle);
      if(m_bShowClickEditHint == 0)
        TriggerAutoSave();
    }
  }
}

////////////////////////
// Inserts the supplied content into the text view
// _content: The contents of the <body> element to load
function HandleTextViewLoad(_content, _knowdeID)
{
//debugger;
  var frame = document.getElementById("TextViewEditFrame-k" + _knowdeID);
  if(frame != null && frame.contentWindow.document != null)
  {      
    if(_content == '')
    {
      if(m_bTextViewWritable == true)
      {
        _content = GetDefaultTextViewContent(_knowdeID);
      }
      else 
        _content = m_noTextViewFoundContent;
    }

    if(m_bTextViewWritable == true)
    {
      var divHtml = _content;
    }else
    {
      var divHtml = "<div id='k" + _knowdeID + "' width='100%' style='position: relative;'><div id='k" + _knowdeID + "-active' width='100%'>";
      divHtml += _content;
      divHtml += "</div></div>";
    }

    frame.contentWindow.document.write("<html><head><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body style='border: 0px;'>"); //class='PersonalisedScrollBar' 
    frame.contentWindow.document.write(divHtml);
    frame.contentWindow.document.write("</body></html>");
  }
  
  //window.setTimeout("SetupKnowdeTextViewDiv('" + m_strSelectedKnowdeID + "')",10);

}

////////////////////////////////
// Handles the saving failure message sent back after a save AJAX call is made
function HandleTextViewSaveFailure(message)
{
   if(m_butTVSave != null)
  {          
    m_butTVSave.src = "Images/KGButtonToolbar/FailedSaveTextView.png";
    m_butTVSave.title = "Fail to Save the Document";
    //TextViewButtonOut(m_butTVSave)
  }
  
  ShowOrHideSavingDiv(0,null,0,0);
  
  if(m_changeTabbedControlAfterSaving != null && m_changeTabbedControlAfterSaving != '')
  {
    m_changeTabbedControlAfterSaving = null;
  }
}

////////////////////////////////
// Handles the saving complete message sent back after a save AJAX call is made
function HandleTextViewSaveComplete(message, content)
{
  
  //debugger;
  
  // don't change edit mode if switching between sibling knowdes
  if(m_bLoadSiblingKnowde == false)
  {
    m_bTextViewWritable = false;
    m_bTextViewWritableModeChanged = true;
  }
  // we need to set a timeout because if we don't the AJAX calls get themselves in a muddle and crashes
  globalTextViewPageLoaded = true;
  if(message.Repopulate == true && (message.Action != 'AutoSave' || m_bLoadSiblingKnowde == true))
  {        
      HandleTextViewLoad(content, message.KnowdeID);

      // need to turn off design mode  
      var frame = document.getElementById("TextViewEditFrame-k" + message.KnowdeID);
      if(frame != null && frame.contentWindow.document.designMode.toLowerCase() != "off")
        frame.contentWindow.document.designMode = "off";
      // make sure the grey out div is applied.
      // Because the handleLoadAllKnowdes callback could be finished quicker than the SaveComplete callback when switching knowdes in edit mode
      setTimeout('SetupKnowdeTextViewDisableDiv(\'' + message.KnowdeID + '\')',10);
      setTimeout("SetupKnowdeTextViewDiv('" + message.KnowdeID + "')",20);
  }else if(message.Repopulate == false && m_bTextViewWritable == true)
  {
    if(m_butTVSave != null)
    {
      m_butTVSave.src = "Images/KGButtonToolbar/StopWritingTextView.png";
      m_butTVSave.title = "Save and Stop Writing Document";
    }
    
    if(EditFrameContentWindowExists() && m_EditFrame.contentWindow.document.body.innerHTML == '')
      m_EditFrame.contentWindow.document.body.innerHTML = GetDefaultTextViewContent(message.KnowdeID);   

    if(message.Action == 'AutoSave')
    {
      var clTime = new Date();
      var clUtc = clTime.getTime() + (clTime.getTimezoneOffset() * 60000 );
      // reset timmer
      m_lastAutoSaveTime = clUtc;
    }
  }

  
  if(message.Action != 'AutoSave')
  {
    setTimeout("SetUpTextView()", 100);
  }
  m_Content = "";

  ShowOrHideSavingDiv(0,null,0,0);

  /*if(m_changeTabbedControlAfterSaving != null && m_changeTabbedControlAfterSaving != '')
  {
    // auto change tab
    setTimeout("KGTabbedWindowsControl_SelectTabById('" + m_changeTabbedControlAfterSaving + "')", 20);
    m_changeTabbedControlAfterSaving = null;
  }*/
}

////////////////////////////
// Method that handles any error in the AJAX callbacks
function TextView_CallbackError(args, context)
{
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    alert('There has been an error in callback.');
  }
}

/////////////////
// Sets up the text view ready for use
function SetUpTextView()
{  
  if (globalTextViewPageLoaded == null || globalTextViewPageLoaded == false)
    return;  
    //debugger;
  m_EditFrameDiv = document.getElementById("TextViewEditFrameDiv");

  if (m_EditFrameDiv != null)
  {
    m_butTVSave = null;//KGButtonToolbar_getWriteTextViewButton(); //document.getElementById("buttonTVSave");
    m_WritableButtons = document.getElementById("TVWriteableButtons");
    
    if(m_bTextViewWritable == true)
    {
      DisplayTextViewInTab('TextViewEdit', '');
      SetTextViewToolbarWritable();
    }
    else
    {
      if(!m_bEditable)
        DisplayTextViewInTab('TextViewReadOnly', '');
      SetTextViewToolbarReadOnly();
    }
    
     //setTimeout("ResizeTextView()",300);
  }
}

/*function ResizeTextView()
{
	m_EditFrameDiv = document.getElementById("TextViewEditFrameDiv");
  if (m_EditFrameDiv != null)
  {
		m_butTVSave = KGButtonToolbar_getWriteTextViewButton();//document.getElementById("buttonTVSave");
		if(m_bTextViewWritable == true || m_butTVSave != null)
		{
			m_EditFrameDiv = document.getElementById("TextViewEditFrameDiv");
			m_toolBar = document.getElementById("TextViewToolbar");
			var toolBarHeight = 10;
			if(m_toolBar != null)
			  toolBarHeight += m_toolBar.clientHeight;
			var paneBottom = document.getElementById("Splitter1_pane_1_1");
			if (paneBottom.clientHeight - toolbarHeight > 0)			
			  m_EditFrame.style.height = paneBottom.clientHeight - toolbarHeight + "px";
			else
			  m_EditFrame.style.height = 0;
		}
	}
}*/

// Sets up the toolbar so that is displays the editing functionality
function SetTextViewToolbarWritable()
{
  //debugger;
  //TurnOffOldEditFrame();
  m_EditFrameDiv = document.getElementById('TextViewEditFrameDiv');
  // don't auto save if user move the mouse out of the area, 
  // instead, auto save if user move the mouse to the category bar and the head area so if they navigate out of the editing mode
  // they won't lost the changes
  /*if(m_EditFrameDiv != null)
  {
    if (m_EditFrameDiv.addEventListener)
    {
      m_EditFrameDiv.addEventListener('mouseout', TextViewControl_onMouseOut,false);
    }
    else
    {
      m_EditFrameDiv.attachEvent("onmouseout",   TextViewControl_onMouseOut);
    }
  }*/
  if (m_textViewMode == "KNOWDEDOC")
    m_EditFrame = document.getElementById("TextViewEditFrame-k"+m_strSelectedKnowdeID);
  else if (m_textViewMode == "HKGROUPDOC")
    m_EditFrame = document.getElementById("TextViewEditFrame");
  
  if(m_EditFrame != null)
  {
    if(m_EditFrame.contentWindow.document.designMode.toLowerCase() != "on")
      m_EditFrame.contentWindow.document.designMode = "on";

    if (m_textViewMode == "KNOWDEDOC")
    {
     if(m_EditFrame.contentWindow.document.body != null)
        m_EditFrame.style.height = m_EditFrame.contentWindow.document.body.scrollHeight + m_editFrameHeightMargin + 'px';
     else
        m_EditFrame.style.height = parseInt(m_EditFrame.style.height.replace('px','')) + m_editFrameHeightMargin + 'px';
    }
    else if (m_textViewMode == "HKGROUPDOC")
    {
      setTimeout("AdjustEditFrameSize()", 1);
    }
    var rte = m_EditFrame.contentWindow.document;
    if (rte.addEventListener)
    {
      rte.addEventListener('keyup', TextViewControl_KeyPress,false);
      rte.addEventListener('mouseup', TextViewControl_onMouseUp,false);
      rte.addEventListener('focus', TextViewControl_onFocus_Timer,false); //for Opera
      rte.addEventListener('click', TextViewControl_onFocus_Timer,false); //for Safari
      // when press enter, enter single line break instead of create new paragraph
      //rte.addEventListener('keydown', TextViewControl_KeyDown, false); 
    }
    else
    {
      rte.attachEvent('onkeyup', function (){TextViewControl_KeyPress()});
      rte.attachEvent('onmouseup', function (){TextViewControl_onMouseUp()});
      // when press enter, enter single line break instead of create new paragraph
      //rte.attachEvent('onkeydown', TextViewControl_KeyDown);
    }
    
    if(m_butTVSave != null)
    {
      m_butTVSave.src = "Images/KGButtonToolbar/StopWritingTextView.png";
      m_butTVSave.title = "Save and Stop Writing Document";
    }
    
    if(m_WritableButtons != null)
      m_WritableButtons.style.display = "inline";
    
    if(m_bTextViewWritable == false)
      m_bTextViewWritableModeChanged = true;
      
    m_bTextViewWritable = true;
    
    var button = document.getElementById("KGButtonToolbar_ShowTicker");
    if (button)
      button.className = "ButtonToolbar_TextButtonDivInactive";
    // need to set it to active if the active frame's inner html has ticker tags set
    
    if (m_textViewMode == "KNOWDEDOC")
    {
      SetupKnowdeTextViewDisableDivs();
      setTimeout('LoadEditFrameContent()',10);
    }
    
    // update the button toolbar
    if(m_bTextViewWritableModeChanged == true)
    {
      //setTimeout("KGButtonToolbar_StartTextViewEditing()", 20);
    }
      
    m_bTextViewWritableModeChanged = false;
  }
}

var textViewFocusTimer;
//make sure the function is only called once because now it has to be attached to a few events
function TextViewControl_onFocus_Timer()
{
  clearTimeout(textViewFocusTimer);
  textViewFocusTimer = setTimeout(TextViewControl_onFocus,10);
}

function LoadEditFrameContent()
{
  //debugger;
  var editFrame = document.getElementById("TextViewEditFrame-k" + m_strSelectedKnowdeID);
  if(editFrame == null)
  {
    // hasn't loaded yet, wait a while
    setTimeout('LoadEditFrameContent()',10);
    return;
  }
  
  var div = editFrame.contentWindow.document.getElementById('k' + m_strSelectedKnowdeID);
  var adiv = editFrame.contentWindow.document.getElementById('k' + m_strSelectedKnowdeID + '-active');
  if(editFrame.contentWindow.document.designMode.toLowerCase() == 'on')
  {
    if(editFrame.contentWindow.document.body == null)
    {
      // haven't loaded yet, wait a while
      setTimeout('LoadEditFrameContent()',10);
      return;
    }
    
    if(div != null && adiv != null)
    {
      if(adiv.innerHTML.toLowerCase().indexOf('images/clickedit.png') == -1)
      {
        var content = adiv.innerHTML;
        var kndText = GetCurrentKnowdeTextForTextView(m_strSelectedKnowdeID);
        if(kndText != '')
        {
          if(CheckTextViewHasTitle(m_strSelectedKnowdeID, kndText, content) == false)
             content = WrapTextViewContentWithTitle(m_strSelectedKnowdeID, kndText, content);
        }
        editFrame.contentWindow.document.body.innerHTML = content; 
        //editFrame.contentWindow.document.body.focus();
      }
      else
      {
        var tvc = GetDefaultTextViewContent(m_strSelectedKnowdeID);

        if (navigator.appName == "Microsoft Internet Explorer")
        {
          editFrame.contentWindow.document.body.innerHTML = tvc;
        }
        else
        {
          editFrame.contentWindow.document.body.innerHTML = tvc.replace('&nbsp;','<br />');
        }
        // auto focus 
        placeCursorAtEnd(editFrame.contentWindow.document.body);
        //editFrame.contentWindow.document.body.focus();
        //m_bShowClickEditHint = 1;
      }
      
      // fixes bug where the textview iframe doesnt resize when editing the same knowde for a second time
      TextViewDivResize()
      //editFrame.contentWindow.focus();
      
    }
    m_textViewChanged = 0;
 }

}

function placeCursorAtStart(el) 
{
  if (el.setSelectionRange) 
  {
    el.setSelectionRange(0, 0);
  } 
  else if (el.createTextRange) 
  {
    var range = el.createTextRange();
    range.collapse(true);
    range.moveEnd('character', 0);
    range.moveStart('character', 0);
    range.select();
  }
}


function placeCursorAtEnd(el) 
{
  var len = el.innerHTML.length;
  if (el.setSelectionRange) 
  {
    el.setSelectionRange(len, len);
  } 
  else if (el.createTextRange) 
  {
    var range = el.createTextRange();
    range.collapse(true);
    range.moveEnd('character', len);
    range.moveStart('character', len);
    range.select();
  }
}


///////////////////////
// sets the toolbar to be the saving version
function SetTextViewToolbarSaving()
{
  if(m_butTVSave != null)
  {          
    m_butTVSave.src = "Images/KGButtonToolbar/SavingTextView.png";
    m_butTVSave.title = "Saving Document...";
    //TextViewButtonOut(m_butTVSave)
  }
  
  if(m_WritableButtons != null)
    m_WritableButtons.style.display = "none";
    
  ShowOrHideSavingDiv(1, null, 0, 0);
}

///////////////////////
// Sets up the toolbar so that is is read-only
function SetTextViewToolbarReadOnly()
{
  //TurnOffOldEditFrame();
  
  m_EditFrame = document.getElementById("TextViewEditFrame-k"+m_strSelectedKnowdeID);
  if(m_EditFrame != null && m_EditFrame.contentWindow.document.designMode.toLowerCase() != "off"){
    m_EditFrame.contentWindow.document.designMode = "off";
  }
  
  if(m_butTVSave != null)
  {          
    m_butTVSave.src = "Images/KGButtonToolbar/WriteTextView.png";
    m_butTVSave.title = "Start Writing Document";
  }
  
  if(m_WritableButtons != null)
    m_WritableButtons.style.display = "none";
  
  if(m_bTextViewWritable == true)
    m_bTextViewWritableModeChanged = true;

  m_bTextViewWritable = false;
  
  SetupKnowdeTextViewDisableDivs();
  
  // update the button toolbar
  if(m_bTextViewWritableModeChanged == true)
  {  
    //setTimeout("SetupKnowdeTextViewDivs()",10);
    setTimeout("SetupKnowdeTextViewDiv('" + m_strSelectedKnowdeID + "')",10);
    //setTimeout("KGButtonToolbar_StopTextViewEditing()", 20);
  }
    
  m_bTextViewWritableModeChanged = false;
}

function TurnOffOldEditFrame()
{
 var oldEditFrame = null;
 if(m_strPreviousSelectedKnowdeID != '')
  oldEditFrame = document.getElementById("TextViewEditFrame-k"+m_strPreviousSelectedKnowdeID);
 if(oldEditFrame != null && m_strPreviousSelectedKnowdeID != m_strSelectedKnowdeID
    && oldEditFrame.contentWindow.document != null && oldEditFrame.contentWindow.document.designMode.toLowerCase() == "on")
     oldEditFrame.contentWindow.document.designMode = "off"

}

function ChangeSelectedTextView(_selectedKnowdeID)
{
  m_strPreviousSelectedKnowdeID = m_strSelectedKnowdeID;
  m_strSelectedKnowdeID = _selectedKnowdeID;
  
  if(m_strPreviousSelectedKnowdeID == m_strSelectedKnowdeID)
    return false;
  else
    return true;
}

function SwitchTextViewEditing()
{
//debugger;
  if(m_autoSaveTimeOut !=  null)
    clearTimeout(m_autoSaveTimeOut);
  m_bLoadSiblingKnowde = false;
  SaveTextView();
}

/////////////////////
// Kicks off the loading of the text view
function LoadTextView()
{
  //debugger;
  m_EditFrameDiv = document.getElementById('TextViewEditFrameDiv');
    
  // only show loading image if it's a full reload
  if(m_EditFrameDiv != null && m_bLoadSiblingKnowde == false)
    m_EditFrameDiv.innerHTML = m_LoadingMessage;
  
  if(m_bLoadSiblingKnowde == false)
    SetUpTextView();
    
  var args = "Action=Load";
  if(m_bLoadSiblingKnowde == true)
    args += "|LoadSiblingKnowde=true";
    
  // if the docVersion is not null add it to the callback args
  if (m_textViewDocVersion != null)
    args += "|DocumentVersion=" + m_textViewDocVersion;
  
  KGTextViewEditingToolbar_ChangeEditbarMode("TextViewReset");
  
  TextView_CallbackTrigger(args);
}

function AutoSaveTextView()
{
  if(m_EditFrame != null && m_bTextViewWritable)
  {
    //debugger;
    // check whether reach interval
    var clTime = new Date();
    var clUtc = clTime.getTime() + (clTime.getTimezoneOffset() * 60000 );
    if((clUtc - m_lastAutoSaveTime)/1000 < m_autoSaveInterval)
    {
      // not reach the interval yet
      m_autoSaveTimeOut =  setTimeout('AutoSaveTextView()', m_autoSaveInterval * 1000 - (clUtc - m_lastAutoSaveTime) + 1000);
      return;
    }
    
    // reset timmer
    m_lastAutoSaveTime = clUtc;
    
    var div = m_EditFrame.contentWindow.document.getElementById('k' + m_strSelectedKnowdeID);
    var adiv = m_EditFrame.contentWindow.document.getElementById('k' + m_strSelectedKnowdeID + '-active');
    var content = '';
        
    if(adiv != null)
      content = adiv.innerHTML;
    else if(div != null)
      content = div.innerHTML;
    else
      content = m_EditFrame.contentWindow.document.body.innerHTML;
        
    //debugger;
    if(content.length > 0)
    {
      m_bLoadSiblingKnowde = true;
      if (m_textViewMode == "KNOWDEDOC")
      {
        SaveTextView('Action=AutoSave|Repopulate=false|KGId=' + m_strSelectedKGID + '|KnowdeId=' + m_strSelectedKnowdeID + '|Changed=true');
      }
      else if (m_textViewMode == "HKGROUPDOC")
        SaveHKGroupTextView('Action=AutoSave');
    }
  }
  else
  {
    if(m_autoSaveTimeOut != null)
      clearTimeout(m_autoSaveTimeOut);
  }
}

///////////////
// Saves the text view to the server
function SaveTextView(_args)
{
  //debugger;
  // The text view may not be writable, if this is the case then just make it all writable and return
  if(m_bTextViewWritable == false)
  {
    m_bTextViewWritableModeChanged = true;
    DisplayTextViewInTab('TextViewEdit', '');
    SetTextViewToolbarWritable(); 
    return;
  }
  
  if(TextviewKeypressTimeout != null)
    clearTimeout(TextviewKeypressTimeout);
  
   //m_EditFrame.contentWindow.document.contentEditable = "false";

  // grab the document text
  //var text = m_EditFrame.contentWindow.document.body.innerHTML;
  var div = m_EditFrame.contentWindow.document.getElementById('k' + m_strSelectedKnowdeID);
  var adiv = m_EditFrame.contentWindow.document.getElementById('k' + m_strSelectedKnowdeID + '-active');
  
  if(m_EditFrame.contentWindow.document.body.innerHTML.toLowerCase().indexOf('images/clickedit') != -1)
    m_EditFrame.contentWindow.document.body.innerHTML = '';   

  if(adiv != null)
    m_Content = adiv.innerHTML;
  else if(div != null)
    m_Content = div.innerHTML;
  else
    m_Content = m_EditFrame.contentWindow.document.body.innerHTML;
         
  SetTextViewToolbarSaving();
  
//debugger;
  var requiredSaving = 1;
  var textVersionEdited = 0;
  if(_args != null && _args.indexOf('AutoSave') != -1)
  {
     if(m_autoSaveTimeOut != null)
        clearTimeout(m_autoSaveTimeOut);
    
     requiredSaving = m_textViewChanged; //no changes made since last save
     
    if(m_textViewChanged == 1 && m_textViewMode == "KNOWDEDOC") // text version text changed
      textVersionEdited = 1;
  }
  m_textViewChanged = 0;
   
  // get rid of tailing two line breaks that added in edit mode
  //if(m_Content.substr(m_Content.length - 10, 10) == '<br/><br/>')
    //m_Content = m_Content.substr(m_Content.length - 10, 10);

  // display the saving icon
  //m_EditFrame.contentWindow.document.body.innerHTML = "<div class='SavingMessage'><img src='Images/LoadingBar.gif'>&nbsp;Please wait while we save your changes...</div>";
  
  if(requiredSaving == 1)
  {
    // make the ajax call
    // default action
    var args = "Action=Save|KGId=" + m_strSelectedKGID + "|KnowdeId=" + m_strSelectedKnowdeID + "|";
    // if pass in specific action, use them instead
    if(_args != null && _args.length > 0)
      args = _args + "|";
    
    if(textVersionEdited == 1) // text version text changed
    {
       m_KnowdeDocVersionArray = m_buttonToolbar_docVersionSelect.Edited(m_KnowdeDocVersionArray);
       if(args.indexOf('|Changed=') == -1)
        args += 'Changed=true|';
    }

    args += "Contents=" + m_Content;
    
    // if the docVersion is not null add it to the callback args
    if (m_textViewDocVersion != null)
      args += "|DocumentVersion=" + m_textViewDocVersion;
          
    TextView_CallbackTrigger(args); 
    
  }else
  {
    // don't callback, just refresh the content
    var returnMessage = '{"KGID":"0","KnowdeID":"0","Action":"AutoSave","OK":true,"Repopulate":true}';
    var message =  eval( '(' + returnMessage + ')'); 
    var args = _args.split('|');
    for(var argidx=0; argidx < args.length; argidx++)
    {
      var idvalue = args[argidx].split('=');
      if(idvalue[0] == 'KGId')
        message.KGID = idvalue[1];
      if(idvalue[0] == 'KnowdeId')
        message.KnowdeID = idvalue[1];
      if(idvalue[0] == 'Repopulate' && idvalue[1].toLowerCase() == 'false')
        message.Repopulate = false;
        
    }
    HandleTextViewSaveComplete(message, m_Content);
  }
}

///////////////
// Saves the text view to the server
function SaveHKGroupTextView(_args)
{
  //if(m_EditFrame.contentWindow.document.body.innerHTML.toLowerCase().indexOf('images/clickedit') != -1)
    //m_EditFrame.contentWindow.document.body.innerHTML = '';   
  
  m_Content = m_EditFrame.contentWindow.document.body.innerHTML;
  
  SetTextViewToolbarSaving();
  
  var requiredSaving = 1;
  
  if(m_autoSaveTimeOut != null)
      clearTimeout(m_autoSaveTimeOut);
      
  if(_args != null && _args.indexOf('AutoSave') != -1)
  {
    requiredSaving = m_textViewChanged; //no changes made since last save
  }
  m_textViewChanged = 0;
  
  // get rid of tailing two line breaks that added in edit mode
  //if(m_Content.substr(m_Content.length - 10, 10) == '<br/><br/>')
    //m_Content = m_Content.substr(m_Content.length - 10, 10);

  // display the saving icon
  //m_EditFrame.contentWindow.document.body.innerHTML = "<div class='SavingMessage'><img src='Images/LoadingBar.gif'>&nbsp;Please wait while we save your changes...</div>";
  
  if(requiredSaving == 1)
  {
    // make the ajax call
    // default action
    var args = "Action=Save|";
    // if pass in specific action, use them instead
    if(_args != null && _args.length > 0)
      args = _args + "|";

    args += "Contents=" + m_Content;
      
    TextView_CallbackTrigger(args); 
  }
  else
  {
    // don't callback, just refresh the content
    var returnMessage = '{"Action":"AutoSave","OK":true,"Repopulate":true}';
    var message =  eval( '(' + returnMessage + ')'); 
    var args = _args.split('|');
    for(var argidx=0; argidx < args.length; argidx++)
    {
      var idvalue = args[argidx].split('=');
      if(idvalue[0] == 'Repopulate' && idvalue[1].toLowerCase() == 'false')
        message.Repopulate = false;
    }
    //HandleTextViewSaveComplete(message, m_Content);
  }
}

/////////////////////////////
// Inserts a link into the text view doument using the built in functionality
function TextViewInsertLink()
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    // we are manually creating the link - so that we can force it to open in a new browser window.
    var url = prompt("Please enter the URL you want to insert.", "http://");
    // need to refocus because if user's browser block the script and user allow it, the focus will lost
    m_EditFrame.contentWindow.focus();
    if(url != null && url != "")
    {
      InsertHtmlToIframe("<a href='" + url + "' target='_blank'>" + url + "</a>");
      //if (m_textViewMode == 'HKGROUPDOC')
        m_EditFrame.style.height = m_EditFrame.contentWindow.document.body.scrollHeight + m_editFrameHeightMargin + 'px';
      // ensure focus is in the text.
      m_EditFrame.contentWindow.focus();
      TriggerAutoSave();
    }
  }
}

//////////////////////////
// Kicks off the Insert image functionality by opening the upload window
function TextViewInsertImage()
{
//debugger;
  if(m_UploadWindow)
  {
    m_UploadWindow.close();
    if (window.KGTextViewEditingToolbar_UpdateUndoRedoBtns)
      // update the undoredo buttons
      KGTextViewEditingToolbar_UpdateUndoRedoBtns();
  }
    
  //m_UploadWindow = document.parentWindow.showModalDialog("TextViewUpload.aspx", null ,"dialogHeight:200px; dialogWidth:400px; status:No; center:Yes; scroll:No; help:No;");
  if (document.defaultView)
    m_UploadWindow = document.defaultView.open("TextViewUpload.aspx", "Upload" ,"height=200,width=400,status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=no,titlebar=no");
  else if (document.parentWindow)
    m_UploadWindow = document.parentWindow.open("TextViewUpload.aspx", "Upload" ,"height=200,width=400,status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=no,titlebar=no");
}

//////////////////////////
// Kicks off the insert file functionality by opening the upload window
function TextViewInsertFile()
{
  if(m_UploadWindow)
  {
    m_UploadWindow.close();
    if (window.KGTextViewEditingToolbar_UpdateUndoRedoBtns)
      // update the undoredo buttons
      KGTextViewEditingToolbar_UpdateUndoRedoBtns();
  }
  
  if (document.defaultView)
    m_UploadWindow = document.defaultView.open("TextViewFileUpload.aspx", "Upload" ,"height=200,width=400,status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=no,titlebar=no");
  else if (document.parentWindow)
    m_UploadWindow = document.parentWindow.open("TextViewFileUpload.aspx", "Upload" ,"height=200,width=400,status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=no,titlebar=no");
}


/////////////////////
// Completes the image upload process and inserts the given url at the current location
// _url: The full url of the image to be inserted
function CompleteImageUpload(_url)
{
  //debugger;
  // if the upload window is active then close it
  if(m_UploadWindow)
    m_UploadWindow.close();
 
  //TS: Bug 2868 fix - ensure focus is in the text.
  m_EditFrame.contentWindow.focus();
  
  // insert the image into the document
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    m_EditFrame.contentWindow.document.execCommand("InsertImage", false, _url);
    TriggerAutoSave();
    setTimeout("AdjustEditFrameSize()", 400);
  }
}

/////////////////////
// Completes the file upload process and inserts the given url at the current location
// _url: The full url of the file to be inserted
function CompleteFileUpload(_url)
{
  // if the upload window is active then close it
  if(m_UploadWindow)
    m_UploadWindow.close();
  
  // insert the file into the document
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    var dotIndex = _url.lastIndexOf(".");
    if(dotIndex <=0 )
      return;
    
    var extension = _url.substr(dotIndex, (_url.length - dotIndex));
    var imgUrl = "Images/FileTypes/Unknown.png";
  
      // if the file is of a known type then use that image instead
    switch(extension)
    {
        // MS word
        case ".doc":
        case ".docx":
          imgUrl = "Images/FileTypes/Word.png";
          break;
        // MS Excel
        case ".xls":
        case ".xlsx":
          imgUrl = "Images/FileTypes/Excel.png";
          break;
         // MS Powerpoint
        case ".ppt":
        case ".pps":
        case ".pptx":
          imgUrl = "Images/FileTypes/PowerPoint.png";
          break;
         // Adobe PDF
        case ".pdf":
          imgUrl = "Images/FileTypes/PDF.png";
          break;
        // Plain Text
        case ".txt":
          imgUrl = "Images/FileTypes/Text.png";
          break;
        // MS Visio
        case ".vsd":
          imgUrl = "Images/FileTypes/Visio.png";
          break;
        // All image formats
        case ".png":
        case ".gif":
        case ".jpg":
        case ".jpeg":
        case ".jpe":
        case ".bmp":
        case ".psd":
        case ".psp":
        case ".raw":
        case ".tif":
        case ".tiff":
          imgUrl = "Images/FileTypes/Image.png";
          break;
        // All Compressed formats
        case ".zip":
        case ".arj":
        case ".cab":
        case ".gz":
        case ".rar":
        case ".tar":
        case ".zoo":
          imgUrl = "Images/FileTypes/Zip.png";
          break;
    }

    // insert the correct html into the document. instead of doing this using execCommand we have to insterst it using a range
    
    // first make sure the selection corresponds to the text view window (it doesn't if you haven't clicked it yet)
    m_EditFrame.contentWindow.focus(); 
    InsertHtmlToIframe("<a href='" + _url + "' target='_blank'><img border='0' src='" + imgUrl + "'/>&nbsp;Link</a>");
    TriggerAutoSave();
    
    setTimeout("AdjustEditFrameSize()", 400);
  }
}

function GetRangeObject(selectionObject) {
	if (selectionObject.getRangeAt)
		return selectionObject.getRangeAt(0);
	else { // Safari!
		var range = document.createRange();
		range.setStart(selectionObject.anchorNode,selectionObject.anchorOffset);
		range.setEnd(selectionObject.focusNode,selectionObject.focusOffset);
		return range;
	}
}

function InsertHtmlToIframe(_newHtml)
{
  var range;
  if (m_EditFrame.contentWindow.getSelection)   // make the range be in the iframe explicitly for ff
    range = GetRangeObject(m_EditFrame.contentWindow.getSelection());
  else if (document.selection) //already focussed on the iframe
    range = document.selection.createRange();

  range.collapse(false); // collapse makes the start and end position of the range the same place

  if (range.pasteHTML)
    range.pasteHTML(_newHtml);
  else
  {
    var newEl = m_EditFrame.contentWindow.document.createElement('div');
    newEl.innerHTML = _newHtml;
    range.insertNode(newEl.firstChild);
  }
}   

//////////////////////////
// Called when the mouse floats over a toolbar button, making it highlighted
// _button: the button floated over
function TextViewButtonOver(_button)
{
  _button.className = "TextViewToolbarButtonOver";
}

//////////////////////////
// Called when the mouse floats out of toolbar button, removing the highlight
// _button: the button floated over
function TextViewButtonOut(_button)
{
  _button.className = "TextViewToolbarButton";
}

////////////////////
// Calls the built in Ordered List functionality
function TextViewOList()
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    m_EditFrame.contentWindow.document.execCommand('InsertOrderedList', false, null);
    
    TriggerAutoSave();
    
    //TS: Bug 3810 fix - ensure focus is in the text.
    m_EditFrame.contentWindow.focus();
  }
}

////////////////////
// Calls the built in Unordered List functionality
function TextViewUList()
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    m_EditFrame.contentWindow.document.execCommand('InsertUnorderedList', false, null);
    
    TriggerAutoSave();
    
    //TS: Bug 3810 fix - ensure focus is in the text.
    m_EditFrame.contentWindow.focus();
  }
}

////////////////////
// Calls the built in bold functionality
function TextViewBold()
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    m_EditFrame.contentWindow.document.execCommand("Bold", false, null);
    
    TriggerAutoSave();
    
    //TS: Bug 3810 fix - ensure focus is in the text.
    m_EditFrame.contentWindow.focus();
  }
}

////////////////////
// Calls the built in italic functionality
function TextViewItalic()
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    m_EditFrame.contentWindow.document.execCommand("Italic", false, null);
    
    TriggerAutoSave();
    
    //TS: Bug 3810 fix - ensure focus is in the text.
    m_EditFrame.contentWindow.focus();
  }
}

////////////////////
// Calls the built in underline functionality
function TextViewUnderline()
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    m_EditFrame.contentWindow.document.execCommand("Underline", false, null);
    
    TriggerAutoSave();
    
    //TS: Bug 3810 fix - ensure focus is in the text.
    m_EditFrame.contentWindow.focus();
  }
}

////////////////////
// Calls the built in increase indent functionality
function TextViewIncIndent()
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    m_EditFrame.contentWindow.document.execCommand("Indent", false, null);
    //if (m_textViewMode == 'HKGROUPDOC')
      m_EditFrame.style.height = m_EditFrame.contentWindow.document.body.scrollHeight + m_editFrameHeightMargin + 'px';
    
    TriggerAutoSave();
    
    //TS: Bug 3810 fix - ensure focus is in the text.
    m_EditFrame.contentWindow.focus();
 }
}

////////////////////
// Calls the built in decrease indent functionality
function TextViewDecIndent()
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    m_EditFrame.contentWindow.document.execCommand("Outdent", false, null);
    //if (m_textViewMode == 'HKGROUPDOC')
      m_EditFrame.style.height = m_EditFrame.contentWindow.document.body.scrollHeight + m_editFrameHeightMargin + 'px';
    
    TriggerAutoSave();
    
    //TS: Bug 3810 fix - ensure focus is in the text.
    m_EditFrame.contentWindow.focus();
  }
}

////////////////////
// Called when the style drop list in the toolbar has it's selectiopn changed
function TextViewStyleChanges(_styleDropList)
{
  formatBlock(_styleDropList.value);
}

////////////////////
// Formats the current element with the supplied tag
// _tag: the html element to use fot the formatting
function formatBlock(_tag)
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    m_EditFrame.contentWindow.document.execCommand("formatblock", false, "<" + _tag + ">");
    //if (m_textViewMode == 'HKGROUPDOC')
     m_EditFrame.style.height = m_EditFrame.contentWindow.document.body.scrollHeight + m_editFrameHeightMargin + 'px';
   
    TriggerAutoSave(); 
  }
}

////////////////
// Calls the built in cut functionality
function TextViewCut()
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on"  && navigator.appName == "Microsoft Internet Explorer")
  {
    m_EditFrame.contentWindow.document.execCommand("Cut", false, null);
    //if (m_textViewMode == 'HKGROUPDOC')
      m_EditFrame.style.height = m_EditFrame.contentWindow.document.body.scrollHeight + m_editFrameHeightMargin + 'px';
    
    TriggerAutoSave();
    return true;
  }
  else
  {
    return false;
  }
}

////////////////
// Calls the built in copy functionality
function TextViewCopy()
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on" && navigator.appName == "Microsoft Internet Explorer")
  {
    m_EditFrame.contentWindow.document.execCommand("Copy", false, null);
    return true;
  }
  else
    return false;
}

////////////////
// Calls the built in paste functionality
function TextViewPaste()
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on" && navigator.appName == "Microsoft Internet Explorer")
  {
    m_EditFrame.contentWindow.document.execCommand("Paste", false, null);
    //if (m_textViewMode == 'HKGROUPDOC')
      m_EditFrame.style.height = m_EditFrame.contentWindow.document.body.scrollHeight + m_editFrameHeightMargin + 'px';
    
    TriggerAutoSave();
    return true;
  }
  else
    return false;
}

////////////////
// Calls the built in undo functionality
function TextViewUndo()
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    m_EditFrame.contentWindow.document.execCommand("Undo", false, null);
    //if (m_textViewMode == 'HKGROUPDOC')
      m_EditFrame.style.height = m_EditFrame.contentWindow.document.body.scrollHeight + m_editFrameHeightMargin + 'px';
  
    TriggerAutoSave();
  }
}

////////////////
// Calls the built in redo functionality
function TextViewRedo()
{
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    m_EditFrame.contentWindow.document.execCommand("Redo", false, null);
    //if (m_textViewMode == 'HKGROUPDOC')
      m_EditFrame.style.height = m_EditFrame.contentWindow.document.body.scrollHeight + m_editFrameHeightMargin + 'px';
    
    TriggerAutoSave();
  }
}


var tickerSpanStartTag = '<span id="ticker" style="background-color:transparent;">';
var tickerSpanEndTag = '</span>';
var tickerSelection;
var tickerSelection0;
var tickerSelection1;
var tickerSelection2;

var tickerSelectionText;
var tickerSelectionTextArray = new Array();

var tickerSelectionPattern;
var tickerSelectionPatternArray = new Array();

function removeHTMLTags(_input){
		var strInputCode = _input;
		/* 
			This line is optional, it replaces escaped brackets with real ones, 
			i.e. &lt; is replaced with < and &gt; is replaced with >
		*/	
		/*strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
			return (p1 == "lt")? "<" : ">";
		});*/
		var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
		return strTagStrippedText;
}

function removeLineBreaks(_input, _replaceText)
{
    if(_replaceText == null)
      _replaceText = '';
    var input = _input;
    var lineBreakIdx = input.indexOf('\u000A');
    while(lineBreakIdx > 0)
    {
      input = input.substr(0, lineBreakIdx-1) + _replaceText + input.substr(lineBreakIdx+1);
      lineBreakIdx = input.indexOf('\u000A');
    }
    input = input.replace(new RegExp("\\r\\n","m"),_replaceText);
    input = input.replace(new RegExp("\\r","m"),_replaceText);
    input = input.replace(new RegExp("\\n","m"),_replaceText);
    
    return input;
}

// This has to be done in a separate function, as otherwise clicking the button removes the selection
function copySelection()
{
  tickerSelectionTextArray = new Array();
  
  if (m_EditFrame.contentWindow.getSelection) // non-IE
  {
  	var rng = GetRangeObject(m_EditFrame.contentWindow.getSelection());
  	tickerSelectionText = rng.toString();
  	var clonedSelection = rng.cloneContents();
    var newEl = document.createElement('div');
    newEl.appendChild(clonedSelection);
    tickerSelection = newEl.innerHTML;
  }
  else if (m_EditFrame.contentWindow.document.selection) // IE
  {
	  var rng = m_EditFrame.contentWindow.document.selection.createRange();
	  tickerSelectionText = rng.text;
	  tickerSelection = rng.htmlText;
	}
	    
  if(tickerSelection != null)
  {
    // trim out ticker spans in the original selection text
    var sel = TrimTickerSpans(tickerSelection);
    tickerSelection0 = sel;
    var rnIdx = -1;
    // trim leading and tailing tags
    /*rnIdx = sel.indexOf('\u000A');
    while(rnIdx >= 0)
    {
      sel = sel.substr(0, rnIdx-1) + '[@HK_LineBreak@]' + sel.substr(rnIdx);
      rnIdx = sel.indexOf('\u000A', rnIdx+1+16);
    }
    rnIdx = sel.indexOf('</');
    while(rnIdx >= 0)
    {
      sel = sel.substr(0, rnIdx-1) + '[@HK_LineBreak@]' + sel.substr(rnIdx);
      rnIdx = sel.indexOf('</', rnIdx+2+16);
    }*/
    rnIdx = sel.indexOf('<');
    while(rnIdx >= 0)
    {
      sel = sel.substr(0, rnIdx) + '[@HK_LineBreak@]' + sel.substr(rnIdx);
      rnIdx = sel.indexOf('<', rnIdx+1+16);
    }
    
    tickerSelectionTextArray = sel.split("[@HK_LineBreak@]");
    if(tickerSelectionTextArray.length > 0)
    {
      tickerSelection0 = '';
      tickerSelectionPattern = '';
      for(var ti = 0; ti < tickerSelectionTextArray.length; ti++)
      {
        tickerSelectionTextArray[ti] = removeHTMLTags(tickerSelectionTextArray[ti]);
        var actualText = removeLineBreaks(tickerSelectionTextArray[ti]);
        if(actualText.length > 0)
          break;
      }
      for(var ti2 = tickerSelectionTextArray.length-1; ti2 >= 0; ti2--)
      {
        var trimedText = removeHTMLTags(tickerSelectionTextArray[ti2]);
        var actualText = removeLineBreaks(trimedText);
        if(actualText.length > 0)
          break;
        else
          tickerSelectionTextArray[ti2] = trimedText;
      }
      //tickerSelectionPatternArray = new Array(tickerSelectionTextArray.length);
      for(var ti3 = 0; ti3 < tickerSelectionTextArray.length; ti3++)
      {
        var actualText = removeLineBreaks(tickerSelectionTextArray[ti3]);
        if(actualText.length > 0){
          tickerSelection0 = tickerSelection0 + tickerSelectionTextArray[ti3];
          //var pattenText = removeLineBreaks(tickerSelectionTextArray[ti3], ').*(');
          //if(tickerSelectionPattern.length > 0)
            //tickerSelectionPattern = tickerSelectionPattern + '.*';
          //tickerSelectionPattern = tickerSelectionPattern + '(' + pattenText.replace(' )',')').replace('( ','(') + ')';
          //tickerSelectionPatternArray[ti3] = pattenText.replace(' )',')').replace('( ','(');
        }//else
          //tickerSelectionPatternArray[ti3] = '';
      }
      //if(tickerSelectionPattern.length > 0)
      //{
        //tickerSelectionPattern = '(' + tickerSelectionPattern + ')';
      //}
    }

    
    // the html text could be multiline format, so filter the line breaks
    //tickerSelection1 = tickerSelection.replace(new RegExp("\\u000A","m"),''); // not working, tickerSelection.replace(/u000A/m,'');  or tickerSelection.replace(/\u000A/m,''); not working as well
    tickerSelection1 = tickerSelection0;
    var lineBreakIdx = tickerSelection1.indexOf('\u000A');
    while(lineBreakIdx > 0)
    {
      tickerSelection1 = tickerSelection1.substr(0, lineBreakIdx-1) + tickerSelection1.substr(lineBreakIdx+1);
      lineBreakIdx = tickerSelection1.indexOf('\u000A');
    }
    // filter out \r\n as well
    tickerSelection2 = tickerSelection1.replace(new RegExp("\\r\\n","m"),'');
    tickerSelection2 = tickerSelection2.replace(new RegExp("\\r","m"),'');
    tickerSelection2 = tickerSelection2.replace(new RegExp("\\n","m"),'');
  }
}

function TrimTickerSpans(_contents)
{
    //debugger;
    var contents = _contents;
    
    var tickerPos = -1; //contents.search(/(ticker)/i);//contents.toLowerCase().indexOf('ticker', 0);
    var tickerPosRe = new RegExp('(ticker)', 'gi');
    var tickerPosMatch = tickerPosRe.exec(contents);
    if(tickerPosMatch != null)
      tickerPos = tickerPosMatch.index;
    while(tickerPos > 0)
    {
      // check whether it's a span tag
      var tagStr = '';
      var wIdx = tickerPos -1;
      while(wIdx >= 0)
      {
        var wchar = contents.substr(wIdx, 1);
        if(wchar == '<' || wchar == '>')
        {
          tagStr = wchar + tagStr;
          if(wchar == '<')
            tagStartPosition = wIdx;
          break;
        }
        else if(wchar != '"' && wchar != "'" && wchar != '\u000A' && wchar != '\r' && wchar != '\n')
        {
          tagStr = wchar + tagStr;
        }
        wIdx--;
      }
      // trim out ticker span if exists
      if(tagStr.toLowerCase().indexOf('<span') == 0 && tagStr.toLowerCase().indexOf('id=') + 2 == tagStr.length -1 && tagStartPosition >= 0)
      {
        var text = contents.substring(tagStartPosition);
        var textStartPosition = text.search(/>/) + tagStartPosition + 1;
        var endPosition = -1;
        // Check position of next span tag
        var text2 = text.substr(textStartPosition - tagStartPosition);
        var re = new RegExp('(<span([^>]*)>)', 'gi');
        var re2 = new RegExp('(<\/span>)', 'gi');
        var matchResult = re.exec(text2);
        var matchResult2 = re2.exec(text2);
        while(matchResult != null && matchResult2 != null)
        {
          if(matchResult[0].indexOf('/>') != -1)
            matchResult = re.exec(text2); // skip this close tag
          else
          {
            if(matchResult.index < matchResult2.index) // there is embeded span tag
            {
              matchResult = re.exec(text2);
              matchResult2 = re2.exec(text2);
            }else
            {
              break;
            }
          }
        }
        if( matchResult2 != null)
          endPosition = matchResult2.index + textStartPosition;
        
        if(endPosition == -1)
          endPosition = text.search(/<\/span>/i) + tagStartPosition;
        
        if(endPosition == -1)
        {
          // no end tag found
          endPosition = textStartPosition-7;
        }
        var tickerText = contents.substring(textStartPosition,endPosition);

        // 2. Replace the whole tagged section with the value between the tags.
        var startText = contents.substring(0,tagStartPosition);
        var endText = contents.substring(endPosition+7);
        //if (startText != "" && endText != "") 
        contents = startText + tickerText + endText;
        
        tagStartPosition = -1;
      }
        
      //tickerPos = contents.search(/(ticker)/i); //contents.toLowerCase().indexOf('ticker', tickerPos);
      tickerPos = -1;
      tickerPosMatch = tickerPosRe.exec(contents);
      if(tickerPosMatch != null)
        tickerPos = tickerPosMatch.index;
    }
    return contents;
}

////////////////
// Puts tags round the selected text to indicate that it is to be used in the ticker
function TextViewSetTickerText() //JPC, XD updated to support cross tags selection
{ 
  // debugger; 
  // NB it will probably be necessary to look for an alternative to document.selection for Mozilla
  if(m_EditFrame.contentWindow.document.designMode.toLowerCase() == "on")
  {
    // If we're in edit mode, only the text for the current knowde is shown, so we don't have to worry about finding it.
    // Strip out any existing tags
    // 1. Find the value between the tags
    var originalContents = TrimTickerSpans(m_EditFrame.contentWindow.document.body.innerHTML);
    if(originalContents.length > 0)
      m_EditFrame.contentWindow.document.body.innerHTML = originalContents;

    var htmlUpdated = 0;
    
    var button = document.getElementById("KGButtonToolbar_ShowTicker");
    button.className = "ButtonToolbar_TextButtonDivInactive";
    
    // Put tags round the selection
    if (tickerSelection != "" && tickerSelection1 != "" && tickerSelection2 != "")
    {
      if(tickerSelection.indexOf('<') == -1 && m_EditFrame.contentWindow.document.body.innerHTML.indexOf(tickerSelection) != -1)
      {
        var newText = tickerSpanStartTag + tickerSelection + tickerSpanEndTag;
        m_EditFrame.contentWindow.document.body.innerHTML = m_EditFrame.contentWindow.document.body.innerHTML.replace(tickerSelection,newText);
        htmlUpdated = 1;
      }
      else if(tickerSelection1.indexOf('<') == -1 && m_EditFrame.contentWindow.document.body.innerHTML.indexOf(tickerSelection1) != -1)
      {
        var newText = tickerSpanStartTag + tickerSelection1 + tickerSpanEndTag;
        m_EditFrame.contentWindow.document.body.innerHTML = m_EditFrame.contentWindow.document.body.innerHTML.replace(tickerSelection1,newText);
        htmlUpdated = 1;
      }
      else if(tickerSelection2.indexOf('<') == -1 && m_EditFrame.contentWindow.document.body.innerHTML.indexOf(tickerSelection2) != -1)
      {
        var newText = tickerSpanStartTag + tickerSelection2 + tickerSpanEndTag;
        m_EditFrame.contentWindow.document.body.innerHTML = m_EditFrame.contentWindow.document.body.innerHTML.replace(tickerSelection2,newText);
        htmlUpdated = 1;
      }else if (tickerSelectionTextArray.length > 0 && tickerSelection2.length > 0)
      {
        // use regx
        tickerSelectionPatternArray = new Array(tickerSelectionTextArray.length);
        for(var ti3 = 0; ti3 < tickerSelectionTextArray.length; ti3++)
        {
          var actualText = removeHTMLTags(tickerSelectionTextArray[ti3]);
          actualTextNoLineBreaks = removeLineBreaks(actualText, '');;
          if(actualTextNoLineBreaks.length > 0){
            var pattenText = removeLineBreaks(tickerSelectionTextArray[ti3], ').*(');
            pattenText = '(' + pattenText + ')';
            tickerSelectionPatternArray[ti3] = pattenText.replace(' )',')').replace('( ','(');
          }else
            tickerSelectionPatternArray[ti3] = '';
        }
        
        var previousEndIdx = 0;
        var previousStartIdx = 0;
        var contentHtml = m_EditFrame.contentWindow.document.body.innerHTML;
        
        for(var ti4 = 0; ti4 < tickerSelectionPatternArray.length; ti4++)
        {
          if(tickerSelectionPatternArray[ti4].length > 0)
          {
            pattern = tickerSelectionPatternArray[ti4];
            var re = new RegExp(pattern, 'g');
            var matchResult = re.exec(contentHtml);
            
            while(matchResult != null)
            {
              var startIdx = matchResult.index;
              var endIdx = startIdx;
              var tickerText = '';
              var appendTickerText = 1; // currently always would be 1
              var inTags = 0;
              var startNewTickerSpan = 1;
              var endNewTickerSpan = 0;
              
              // compare selection
              var currentIdx = startIdx;
              var currentSelIdx = 0;
              var matched = 1;
              // note, regularexpression to match the whole selection is not always working due to certain line breaks and unwanted auto generated tags
              while(currentIdx < contentHtml.length && currentSelIdx < tickerSelection2.length)
              {
                var c1 = contentHtml.substr(currentIdx,1);
                var c2 = tickerSelection2.substr(currentSelIdx,1); // tickerSelection2 has no line break
                if(c1 == '\u000A' || c1 == '\r' || c1 == '\n')
                {
                  currentIdx++;
                  if(appendTickerText == 1 && inTags == 0 && startNewTickerSpan == 0 && tickerText.length > 0)
                    {
                      /* // don't include line breaks in span tag, otherwise the format could be wrong
                      if(startNewTickerSpan == 1)
                      {
                        tickerText = tickerText + tickerSpanStartTag;
                        startNewTickerSpan = 0;
                      }*/
                      tickerText = tickerText + c1;
                      endNewTickerSpan = 1;
                  }
                }
                else if(c1.toLowerCase() == c2.toLowerCase())
                {
                  currentIdx++;
                  currentSelIdx++;
                  if(c1 != '<' && c1 != '>')
                  {
                    if(appendTickerText == 1)
                    {
                      var changeSpace = 0;
                      // don't include leading white spaces in span tag, otherwise the format could be wrong
                      if(startNewTickerSpan == 1 && inTags == 0)
                      {
                        tickerText = tickerText + tickerSpanStartTag;
                        startNewTickerSpan = 0;
                        endNewTickerSpan = 1;
                        if(c1 == ' ')
                          changeSpace = 1;
                      }
                      if(changeSpace == 0)
                        tickerText = tickerText + c1;
                      else
                        tickerText = tickerText + '&nbsp;';
                    }
                  }else if(c1 == '<')
                  {
                    inTags = 1;
                    if(tickerText.length > 0 && endNewTickerSpan == 1)
                    {
                      var spaceStr = '';
                      // don't include tailing white spaces in the span tag otherwise the format could be wrong
                      for(var sIdx = tickerText.length-1; sIdx >= 0; sIdx--)
                      {
                        if(tickerText.substr(sIdx,1) != ' ')
                        {
                          // non space character
                          tickerText = tickerText.substr(0, sIdx + 1) + spaceStr + tickerSpanEndTag;
                          
                          break;
                        }else
                        {
                          spaceStr = spaceStr + '&nbsp;';
                        }
                      }
                      
                      endNewTickerSpan = 0;
                    }
                    if(appendTickerText == 1)
                    {
                      tickerText = tickerText + c1;
                    }
                  }else if(c1 == '>')
                  {
                    if(inTags == 1)
                    {
                      inTags = 0;
                      startNewTickerSpan = 1;
                    }
                    if(appendTickerText == 1)
                    {
                      tickerText = tickerText + c1;
                    }
                  }
                  
                }else
                {
                  // due to the space sometimes not come out correctly inside the ticker span, so we replace it with &nbsp; instead
                  // and the selection sometimes not contain this one
                  if(c1 == '&' && contentHtml.substr(currentIdx,6) == '&nbsp;')
                  {
                    currentIdx = currentIdx + 6;
                    if(startNewTickerSpan == 1 && inTags == 0)
                    {
                        tickerText = tickerText + tickerSpanStartTag;
                        startNewTickerSpan = 0;
                        endNewTickerSpan = 1;
                    }
                    tickerText = tickerText + '&nbsp;';
                    if(c2 == ' ') // if it's matching space, then skip as well
                      currentSelIdx++;
                  }
                  // the document.selection.CreateRange().htmlText might auto add a </SPAN> tag somewhere
                  else if(tickerSelection2.substr(currentSelIdx-2,2) == '</')
                  {
                    var closeIdx = tickerSelection2.indexOf('>', currentSelIdx);
                    if(closeIdx >= currentSelIdx)
                    {
                      currentSelIdx = closeIdx + 1;
                      currentIdx = currentIdx - 2; // already walk </ in contentHTML
                      tickerText = tickerText.substr(0,tickerText.length-2);
                    }
                    else
                    {
                      matched = 0; // not mached
                      break;
                    }
                      
                  }
                  else if(tickerSelection2.substr(currentSelIdx-1,2) == '</')
                  {
                    var closeIdx = tickerSelection2.indexOf('>', currentSelIdx);
                    if(closeIdx >= currentSelIdx)
                    {
                      currentSelIdx = closeIdx + 1;
                      currentIdx = currentIdx - 1; // already walk < in contentHTML
                      tickerText = tickerText.substr(0,tickerText.length-1);
                    }
                    else
                    {
                      matched = 0; // not mached
                      break;
                    }
                      
                  }
                  else if(tickerSelection2.substr(currentSelIdx,2) == '</')
                  {
                    var closeIdx = tickerSelection2.indexOf('>', currentSelIdx);
                    if(closeIdx >= currentSelIdx)
                    {
                      currentSelIdx = closeIdx + 1;
                    }
                    else
                    {
                      matched = 0; // not mached
                      break;
                    }
                      
                  }
                  else if(c1 == ' ' && c2 != ' ' && inTags == 0)
                  {
                    if(tickerSelection2.substr(currentSelIdx-1,1) == ' ' || tickerSelection2.substr(currentSelIdx-1,1) == '>' || tickerSelection2.substr(currentSelIdx,1) == '<')
                    {
                      currentIdx++;
                      if(startNewTickerSpan == 1 && inTags == 0)
                      {
                        tickerText = tickerText + tickerSpanStartTag;
                        startNewTickerSpan = 0;
                        endNewTickerSpan = 1;
                        if(c1 == ' ')
                          changeSpace = 1;
                      }
                      if(changeSpace == 0)
                        tickerText = tickerText + c1;
                      else
                        tickerText = tickerText + '&nbsp;';
                      
                    }else
                    {
                      matched = 0; // not mached
                      break;
                    }
                  }
                  else
                  {
                    matched = 0; // not mached
                    break;
                  }
                }
              }
              if(matched == 1 && currentIdx == contentHtml.length && currentSelIdx < tickerSelection2.length )
                matched = 0; // reach the end of the iframe html, but the search text is not reach the end yet, so no match
              if(matched == 1 && currentIdx >  startIdx)
              {
                endIdx = currentIdx;
                if(tickerText.length > 0)
                {
                  if(endNewTickerSpan == 1)
                      tickerText = tickerText + tickerSpanEndTag;// insert ticker span
                   m_EditFrame.contentWindow.document.body.innerHTML = contentHtml.substr(0,startIdx) + tickerText + contentHtml.substr(endIdx);
                   htmlUpdated = 1;
                }
                
                break;
              }
              else
                matchResult = re.exec(contentHtml); // search next
            }
            //contentHtml = contentHtml.substr(previousEndIdx+1);
            break;
          } // end if;
        }
      }
            
      // Set 'Show ticker text' to active
			if(Active_KGID == globalHelpID)
			{
				button.className = "ButtonToolbar_TextButtonDivActive";
			}
    }
    
    if(htmlUpdated == 1)
      TriggerAutoSave();
  }
}

////////////////
// Highlight the text for the current knowde that has ticker tags around it
// adapted from SetupKnowdeTextViewDiv()
function TextViewShowTickerText() //JPC
{
  //debugger;
  var editFrame = document.getElementById("TextViewEditFrame-k"+m_strSelectedKnowdeID);
  if(editFrame != null)
  {    
    var tickerSpan = null;
    // we need to create a function to test against. If the function returns true when an element 
    // is passed into it then that element is added to the array that is returned.
    var method = function(el){if(el.id == "ticker") return true; return false;};
    var results = YAHOO.util.Dom.getElementsBy(method,null,editFrame.contentWindow.document.body);
    if(results.length > 0) //A knowde can only have 1 ticker selection
    {
      var firstOne = 1;
      for(var r = 0; r < results.length; r++)
      {
        tickerSpan = results[r];
        
        if (tickerSpan != null)
        {
          tickerSpan.style.backgroundColor = m_textViewTickerSelectionHighlightColor;
          
          if(firstOne == 1)
          {
            // Set 'Show ticker text' to inactive
            var button = document.getElementById("KGButtonToolbar_ShowTicker");
            button.className = "ButtonToolbar_TextButtonDivInactive";  
          
            // auto scroll to the position
            if(m_EditFrameDiv == null)
              m_EditFrameDiv = document.getElementById('TextViewEditFrameDiv');
            if(m_EditFrameDiv != null && editFrame.offsetTop >= 0)
             m_EditFrameDiv.scrollTop  = editFrame.offsetTop;
             
             firstOne = 0;
          }
        }
      }
    }
  
    
  }
}

////////////////
// Unhighlight the text for the current knowde that has ticker tags around it
// See also ReturnUnhighlightedTickerText
function TextViewUnhighlightTickerText() //JPC
{
  var editFrame = document.getElementById("TextViewEditFrame-k"+m_strSelectedKnowdeID);
  if(editFrame != null)
  {    
    var tickerSpan = null;
    // we need to create a function to test against. If the function returns true when an element 
    // is passed into it then that element is added to the array that is returned.
    var method = function(el){if(el.id == "ticker") return true; return false;};
    var results = YAHOO.util.Dom.getElementsBy(method,null,editFrame.contentWindow.document.body);
    if(results.length == 1) //A knowde can only have 1 ticker selection
    {
      tickerSpan = results[0];
    }
  
    if (tickerSpan != null)
    {
      tickerSpan.style.backgroundColor = 'transparent';
      // Set 'Show ticker text' to active
      if(Active_KGID == globalHelpID)
			{
				var button = document.getElementById("KGButtonToolbar_ShowTicker");
				button.className = "ButtonToolbar_TextButtonDivActive";
      }
    }
  }
}

// Return unhighlighted text view text given _content
// Based on TextViewUnhighlightTickerText
function ReturnUnhighlightedTickerText(_content) 
{
  var tempEl = document.createElement("div")
  tempEl.innerHTML = _content;
  var tickerSpan = null;
  // we need to create a function to test against. If the function returns true when an element 
  // is passed into it then that element is added to the array that is returned.
  var method = function(el){if(el.id == "ticker") return true; return false;};
  var results = YAHOO.util.Dom.getElementsBy(method,null,tempEl);
  if(results.length == 1) //A knowde can only have 1 ticker selection
  {
    tickerSpan = results[0];
  }

  if (tickerSpan != null)
  {
    tickerSpan.style.backgroundColor = 'transparent';
  }
  return tempEl.innerHTML;
}


////////////////
// Adds in some standard text to the text view so it's easier to test
function TextViewDebugText()
{
  m_EditFrame.contentWindow.document.write("<h1>The quick brown fox jumps over the lazy dog.</h1> <p>The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog.  The quick brown fox jumps over the lazy dog.</p>");
}

function TextViewControl_DisplayCompass( _linkItem )
{
  // get the compass from the page
  var compass = document.getElementById( 'textviewCompass' );
  
  // only do something if the compass is a valid object
  if( typeof(compass) == "object" )
  {
    // set the children on the compass
    // TODO: are childId's actually needed?    
    var compassItem = document.getElementById("TextViewCompassWhy");
    if( compassItem != null && typeof(compass) == "object" )
    {
      compassItem.childId = _linkItem.whyChild;
      compassItem.knowdeId = _linkItem.knowdeId;  
    }
    
    var compassItem = document.getElementById("TextViewCompassHow");
    if( compassItem != null && typeof(compass) == "object" )
    {
      compassItem.childId = _linkItem.howChild;
      compassItem.knowdeId = _linkItem.knowdeId;    
    }
    
    compass.directions = _linkItem.directions;
    compass.cascadeItem = _linkItem;
    compass.hasVisibleChild = false;
    compass.visibleChild = null;
    
    // set the compass directions, making sure that there is something to set first
    // TODO: could we actually do compass.childNodes[1].childNodes[0].style.... instead? - less code and no document.getElementById?
    // How direction
    var howArrow = document.getElementById("TextViewCompassHow");
    if( typeof( howArrow ) == "object" )
    {
      if( compass.directions & 1 ) 
      {
        howArrow.childNodes[0].src = CompassHowOn.src;
        howArrow.attachEvent( "onclick", TextViewControl_displayHows );
      }
		  else
		  {
		    howArrow.childNodes[0].src = CompassHowOff.src;
		    howArrow.detachEvent( "onclick", TextViewControl_displayHows );
		  }
		}

    // Why direction
    var whyArrow = document.getElementById("TextViewCompassWhy");
    if( typeof( whyArrow ) == "object" )
    {
	    if( compass.directions & 2)
	    {
		    whyArrow.childNodes[0].src = CompassWhyOn.src;
		    whyArrow.attachEvent( "onclick", TextViewControl_displayWhys );
		  }
	    else
	    {
		    whyArrow.childNodes[0].src = CompassWhyOff.src;
		    whyArrow.detachEvent( "onclick", TextViewControl_displayWhys );
		  }
		}

    // What direction
    var whatArrow = document.getElementById("TextViewCompassWhat");
    if( typeof( whatArrow ) == "object" )
    {
	    if( compass.directions & 4)
	      whatArrow.childNodes[0].src = CompassWhatOn.src;
	    else
		    whatArrow.childNodes[0].src = CompassWhatOff.src;
		}

    // What Is Direction
    var whatisArrow = document.getElementById("TextViewCompassWhatIs");
    if( typeof( whatisArrow ) == "object" )
    {
	    if( compass.directions & 8)
		    whatisArrow.childNodes[0].src = CompassWhatIsOn.src;
	    else
		    whatisArrow.childNodes[0].src = CompassWhatIsOff.src;
		}
		
		// set the properties to get the compass displaying in the right place
    compass.style.position = "absolute";
    
    var miniCompass = document.getElementById( 'TextViewControl_miniCompass' );
    if( typeof(miniCompass) == "object" && miniCompass != null )
    {
      compass.style.left = parseInt(miniCompass.style.left) - 24;
      compass.style.top = parseInt(miniCompass.style.top) - 24;

      // if the compass has fallen off the edge of the screen then bump it back on
      if( parseInt(compass.style.left) < 0 )
        compass.style.left = '0px';    
      if( parseInt(compass.style.top) < 0 )
        compass.style.top = '0px';    
    
      compass.style.visibility = "visible";
    }
  }
  
  // at this point we want to clean the focused knowde...
  TextViewControl_CleanFocusedKnowde();
}

// this is attached to an event on the compass, we can't attach methods that use parameters
function TextViewControl_displayHows()
{
  TextViewControl_HideCompass();
  TextViewControl_displayCascade(document.getElementById('textviewCompass').cascadeItem, 1);
}

// this is attached to an event on the compass, we can't attach methods that use parameters
function TextViewControl_displayWhys()
{
  TextViewControl_HideCompass();
  TextViewControl_displayCascade(document.getElementById('textviewCompass').cascadeItem, 2);
}

// cleans the focused knowde so that everything is ready to start again
function TextViewControl_CleanFocusedKnowde()
{
  // grab the centred knowde
  var focusedKnowde = document.getElementById("TextViewControl_CentredKnowde");
  if( typeof(focusedKnowde) == "object" && focusedKnowde != null )
  {
    // as it's a valid object hide all the child cascades and reset the child id of the item..
    TextViewControl_hideCascade( focusedKnowde.visibleChild );
    focusedKnowde.childNodes[0].childId = "unknown";
  }
}

function TextViewControl_DisplayCentredKnowde( _HKLink, e )
{
	//IG - get the innertext here, rather than passing it in, so we don't have to worry about JS reserved chars
  //var _strText = GetInnerText(_HKLink);
  var strText;
  if( typeof(_HKLink.KnowdeText) == "string" && _HKLink.KnowdeText != null )
    strText = _HKLink.KnowdeText; 
  else
    strText = "Unable to find Knowde text";
    
  // make sure all our inputs are what we expect them to be
  if( typeof( _HKLink ) == "object" && _HKLink != null && typeof( strText ) == "string" && strText != null )
  {
    // grab the centred Knowde box and make sure it's valid for use
    var centredKnowde = document.getElementById( "TextViewControl_CentredKnowde" );
    if( typeof( centredKnowde ) == "object" && centredKnowde != null )
    {
      // close everything down as we are starting again
      TextViewControl_HideCompass();
      TextViewControl_hideCascade( centredKnowde );
      TextViewControl_HideMiniCompass();    
    
      // set the innertext, directions and knowde id. these are the things we need in the link on the page
      SetInnerText(centredKnowde.childNodes[0],strText);
      centredKnowde.childNodes[0].knowdeId = _HKLink.knowdeId;
      centredKnowde.childNodes[0].directions = _HKLink.directions;
      
      centredKnowde.style.position = "absolute"
      if (_HKLink.className=="TextViewSelectedHKTag")
      {
		centredKnowde.style.left = _HKLink.offsetLeft+5;
		centredKnowde.style.top = _HKLink.offsetTop+15;
	  }
	  else
	  {
		centredKnowde.style.left = e.offsetX;
		centredKnowde.style.top = e.offsetY;
	  
	  } 
      // make it visible
      centredKnowde.style.visibility = "visible";
    } 
  }
}

function TextViewControl_HideEverything()
{
  // close everything down as we are starting again
  TextViewControl_HideCompass();
  var centredKnowde = document.getElementById( "TextViewControl_CentredKnowde" );
  if( typeof( centredKnowde ) == "object" && centredKnowde != null )
    TextViewControl_hideCascade( centredKnowde );
  TextViewControl_HideMiniCompass();   
}

// gets the compass from the page and hide it if it is valid
function TextViewControl_HideCompass()
{
  var compass = document.getElementById( 'textviewCompass' );
  if( typeof(compass) == "object" && compass != null )
    compass.style.visibility = "hidden";
}

// gets the mini compass from the page and hide it if it is valid
function TextViewControl_HideMiniCompass()
{
  var compass = document.getElementById( 'TextViewControl_miniCompass' );
  if( typeof(compass) == "object" && compass != null )
    compass.style.visibility = "hidden";
}

function TextViewControl_displayCascade( _CascadeItem, _mode )
{
  // if the cascade item is not an object OR the mode is not a number THEN get out of here
  if( typeof(_CascadeItem) != "object" || typeof(_mode) != "number" || _CascadeItem == null || _mode == null )
    return;
  
  var childCascade;
  
  // if the child id is 'unknown' then we first need to load it onto the page 
  if( _CascadeItem.childId == "unknown" )
  {
    
    var KnowdeServerUrl = TextViewAshxFile + "?KnowdeId=" + _CascadeItem.knowdeId + "&Mode=" + _mode;
    
    // TextViewControl_appendCascade( _CascadeItem, _mode );    
    var xmlIsland = document.getElementById("TextViewControl_xmlIsland");
    var newHtml = GetHtmlFromAshx(KnowdeServerUrl, xmlIsland);
    /*
    // do the actual load
    var dataIsland = xmlIsland.XMLDocument;
    dataIsland.async = false;
    dataIsland.load( KnowdeServerUrl );
    
    var error = dataIsland.parseError;
    */
    
    //if( error.errorCode == 0 )
    if(newHtml != 'error')
    {
      // TODO: should all our stuff be in a document fragement...??
      // document.createDocumentFragment(); 
      // is this wrong, we need to place this inside an existing element?  
      var newCascade = document.createElement( "div" );
      //newCascade.innerHTML = xmlIsland.XMLDocument.documentElement.xml;
      newCascade.innerHTML = newHtml;
      TextViewControl = document.getElementById("TextViewControl1");
      TextViewControl.insertBefore( newCascade, document.getElementById("TextViewControl_miniCompass") );
      childCascade = newCascade.firstChild; 
      
      // place the child id into the correct place
      _CascadeItem.childId = childCascade.id;
    }
    else // there isn't any children, set this to none so we don't waste time and effort trying to download it again
      _CascadeItem.childId = "none";
  }
  else if( _CascadeItem.childId != "none" ) // if it's none then there isn't one to load or display
  {
    // grab the child id and grab the element
    childCascade = document.getElementById( _CascadeItem.childId );
  }
  
  // do we need to hide any existing cascades?
  if( _CascadeItem.parentNode.hasVisibleChild == true )
    TextViewControl_hideCascade( _CascadeItem.parentNode.visibleChild );
  
  if( childCascade != null )
  {
    // make sure that the parent element knows it has a child visible
    if( _CascadeItem.parentNode.type == "compass" )
    {
      TextViewControl_hideCascade( _CascadeItem.parentNode.parentNode.visibleChild );
      _CascadeItem.parentNode.parentNode.hasVisibleChild = true;
      _CascadeItem.parentNode.parentNode.visibleChild = childCascade;  
    }
    else
    {
      _CascadeItem.parentNode.hasVisibleChild = true;
      _CascadeItem.parentNode.visibleChild = childCascade;  
    }
    
    // we now need to position them, this depends upon the mode we are using
    switch( _mode )
    {
      case 2: // why
        // TODO: we need to move everything for whys id they go off the edge of the screen
        childCascade.style.top = _CascadeItem.offsetTop + _CascadeItem.parentNode.offsetTop;

        if(GetPixelWidth(childCascade) == 0 )
          childCascade.style.width = childCascade.currentStyle.width;
        childCascade.style.left = parseInt(_CascadeItem.parentNode.style.left) - GetPixelWidth(childCascade);
       
        // shunt the cascade to the right a bit...
        childCascade.style.left = parseInt(childCascade.style.left) + 1;
        
        // if the cascade has fallen off the edge of the screen then move everything across to fit
        if( parseInt(childCascade.style.left) < 0 )
        {
          var iOffset = parseInt(childCascade.style.left) - 10;
          TextViewControl_repositionCascades( document.getElementById( 'TextViewControl_CentredKnowde' ), iOffset );
          TextViewControl_repositionCascades( document.getElementById( 'TextViewControl_miniCompass' ), iOffset );
        }
          
        break;
      case 1: // how
        childCascade.style.top = _CascadeItem.offsetTop + _CascadeItem.parentNode.offsetTop;
        if( GetPixelWidth(_CascadeItem.parentNode) == 0 )
          _CascadeItem.parentNode.style.width = _CascadeItem.parentNode.currentStyle.width
      
        childCascade.style.left = parseInt(_CascadeItem.parentNode.style.left) + GetPixelWidth(_CascadeItem.parentNode);
        childCascade.style.left = parseInt(childCascade.style.left) - 1;
        
        
        TextViewControl.scrollLeft += ( TextViewControl.scrollWidth - TextViewControl.scrollLeft - TextViewControl.clientWidth );
        
        break;
    }
        
    // finally show the cascade and make sure we can actually see it
    childCascade.style.visibility = "visible";
    
    //childCascade.scrollIntoView();
    
  }
}

// shifts everything over to the right as you can't scroll to a minus number
function TextViewControl_repositionCascades( _Cascade, _offset )
{
  // only do this if the cascade is a real object and the offset is a number
  if( typeof(_Cascade) == "object" && typeof(_offset) == "number" && _Cascade != null && _offset != null )
  {
    if( _Cascade.hasVisibleChild )
      TextViewControl_repositionCascades( _Cascade.visibleChild, _offset );
  
    _Cascade.style.left = parseInt(_Cascade.style.left) - _offset;
  }
}

// hides the cascade and all it's children in a nice recursive way
function TextViewControl_hideCascade( _Cascade )
{
  // only attempt this if _Cascade is an object
  if( typeof(_Cascade) == "object" && _Cascade != null )
  {
    // if there are visible children then hide them aswell
    if( _Cascade.hasVisibleChild )
      TextViewControl_hideCascade( _Cascade.visibleChild );
    
    _Cascade.style.visibility = "hidden";
    _Cascade.hasVisibleChild = false;  
    _Cascade.visibleChild = null;
  }
}

// displays the mini compass
function TextViewControl_DisplayMiniCompass( _Cascade )
{
  // only attempt this if the cascade is a real object
  if( typeof( _Cascade ) == "object" && _Cascade != null )
  {
    var minicompass = document.getElementById("TextViewControl_miniCompass");
    if( typeof( minicompass ) == "object" && minicompass != null )
    {
      // set the cascade item, so that this can be passed through
      minicompass.CascadeItem = _Cascade;
        
      var centredKnowde = document.getElementById( "TextViewControl_CentredKnowde" );
      if( typeof( centredKnowde ) == "object" && centredKnowde != null )
      {
        minicompass.style.left = centredKnowde.style.left;      
        minicompass.style.left = parseInt(minicompass.style.left) - 18;
        minicompass.style.top = centredKnowde.style.top;  
        minicompass.style.top = parseInt(minicompass.style.top) + 2;    
        minicompass.style.visibility = "visible";    
      }
     
    }  
  }
}

function TextViewControl_onFocus()
{
  clearTimeout(textViewFocusTimer);
  
  // if the preview help control is open, don't allow text view editing
  /*var helpBox = document.getElementById("KGHelpControlID1");
  if(helpBox != null && helpBox.className == "OverlayPosition")
  {
    // move the focus to somewhere else 
    var focusOnObj = document.getElementById('SiteHeader_KGSearchControl1_KGSearchTextBox'); //
    focusOnObj.focus();
    focusOnObj.select();

    DisplayClosePreviewWarningBox();
    
    // focus on the button
    focusOn("closePreviewMessageButton");    
    
    return false;
  }*/
  
  // need this if share the same editing toolbar with mapview
  if (window.KGTextViewEditingToolbar_ChangeEditbarMode && m_bTextViewWritable == true)
    KGTextViewEditingToolbar_ChangeEditbarMode("TextView");
  
  if(m_bShowClickEditHint == 1)
  {
    m_EditFrame = document.getElementById("TextViewEditFrame-k"+m_strSelectedKnowdeID);
    if(m_EditFrame != null && m_EditFrame.contentWindow.document.body != null)
    {
      if(m_EditFrame.contentWindow.document.body.innerHTML.toLowerCase().indexOf('images/clickedit') != -1)
      {
        /*if((m_EditFrame.contentWindow.document.selection && m_EditFrame.contentWindow.document.selection.type == 'Control'))
        {
              //m_EditFrame.contentWindow.document.body.innerHTML = GetDefaultTextViewContent(m_strSelectedKnowdeID, 0);//'<p></p>'; 
              //var range = m_EditFrame.contentWindow.document.selection.createRange();
              //range.collapse(true);
              m_EditFrame.contentWindow.document.execCommand("Cut", false, null);
        }*/
        //else
        //{
            m_EditFrame.contentWindow.document.body.innerHTML = GetDefaultTextViewContent(m_strSelectedKnowdeID, 0);//'<p></p>'; 
        //}
        m_EditFrame.contentWindow.document.body.focus();
      }
    }
    m_bShowClickEditHint = 0;
  }
}

function TextViewControl_onMouseUp()
{
  if(window.KGTextViewEditingToolbar_UpdateStyleSelector)
    KGTextViewEditingToolbar_UpdateStyleSelector();
  if(window.KGTextViewEditingToolbar_UpdateTextFormatBtns)
    KGTextViewEditingToolbar_UpdateTextFormatBtns();
  if(window.KGTextViewEditingToolbar_UpdateCutCopyPasteBtns)
    KGTextViewEditingToolbar_UpdateCutCopyPasteBtns();
  copySelection();
  TextViewUnhighlightTickerText();
  
  
  // Set 'Set ticker text' to active
  if(m_textViewMode == 'KNOWDEDOC' && Active_KGID == globalHelpID)
  {
		var button = document.getElementById("KGButtonToolbar_SetTicker");
		button.className = "ButtonToolbar_TextButtonDivActive";  
  }
  
}

var TextviewKeypressTimeout;

function TextViewControl_KeyPress()
{
  if (m_textViewMode == 'KNOWDEDOC')
    m_EditFrame.style.height = m_EditFrame.contentWindow.document.body.scrollHeight + m_editFrameHeightMargin + 'px';
  else if (m_textViewMode == 'HKGROUPDOC')
    m_EditFrame.style.height = m_EditFrame.contentWindow.document.body.scrollHeight;
  // Sets a timeout on the call to TextViewControl_handleTextChanged.
  // If the user presses another key before this happens, the timeout is cancelled,
  // so the call is only made once the user pauses while typing.
  clearTimeout(TextviewKeypressTimeout);
  TextviewKeypressTimeout = setTimeout('TextViewControl_handleTextChanged()', 500);
  
  TriggerAutoSave();
}

function TextViewControl_KeyDown(e)
{
  //debugger;
  e = e || m_EditFrame.contentWindow.window.event;
  if (e != null && e.keyCode == 13 && !e.shiftKey) // capture the enter key
  {
    var tempTR = null;
    if(m_EditFrame.contentWindow.getSelection)
      tempTR = GetRangeObject(m_EditFrame.contentWindow.getSelection());
    else if(m_EditFrame.contentWindow.document.selection)
      tempTR = m_EditFrame.contentWindow.document.selection.createRange();
      
    if(tempTR != null && tempTR.pasteHTML) //check if an image isn't selected
    {
      //tempTR.pasteHTML("<br></br>");
      var temporary = unescape("%0A");
      m_EditFrame.contentWindow.document.execCommand('paste',"",temporary);
    }
    else if(tempTR != null)
    {
      tempTR.collapse(false);
      var temporary = unescape("%0A");
      var ele = m_EditFrame.contentWindow.document.createElement('div');
      ele.innerHTML = temporary;
      tempTR.insertNode(ele.firstChild);
    }
    return false;
  }
  else
  {
    return true;
  }
}


function TriggerAutoSave()
{
  m_textViewChanged = 1;
  
  if(m_autoSaveTimeOut != null)
    clearTimeout(m_autoSaveTimeOut);
  else
  {
    // initialize utc time
    var localTime = new Date();
    m_lastAutoSaveTime = localTime.getTime() + (localTime.getTimezoneOffset() * 60000 );
  }
  // Sets a timeout for check whether need to auto saving the textview if no key or mouse action for a while
  // AutoSave will only save the text view in the given interval, e.g. 10 seconds
  m_autoSaveTimeOut =  setTimeout('AutoSaveTextView()', m_autoSaveInactivePeriod * 1000);
  
  SetAutoSaveButtonStatus(-1);
}

function TextViewControl_handleTextChanged()
{
  // update the Style selection drop list
  if(window.KGTextViewEditingToolbar_UpdateStyleSelector)
    KGTextViewEditingToolbar_UpdateStyleSelector();
  // update text format button selections
  if(window.KGTextViewEditingToolbar_UpdateTextFormatBtns)
    KGTextViewEditingToolbar_UpdateTextFormatBtns();
  // check whether to activate the undo/redo buttons or not
  if(window.KGTextViewEditingToolbar_UpdateUndoRedoBtns)
    KGTextViewEditingToolbar_UpdateUndoRedoBtns();
  // check whether to activate the cut/copy/paste buttons or not
  if(window.KGTextViewEditingToolbar_UpdateCutCopyPasteBtns)
    KGTextViewEditingToolbar_UpdateCutCopyPasteBtns();
}

function EditFrameContentWindowExists()
{
  var exists = true;
  if (m_EditFrame == null)
    exists = false;
  else if(typeof(m_EditFrame.contentWindow) != "object")
    exists = false;
  else if(m_EditFrame.contentWindow == null)
    exists = false;

  return exists;
}

function SaveCurrentlyEditingTextView(_repopulate)
{
   // Fix for bug whereby a WHAT's text view is not saved when editing a WHAT
  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)
    if(_repopulate == false)
      saveArgs += '|Repopulate=false';
    SaveTextView(saveArgs);
    // only turn off editing mode when click non-sibling knowde
    if(m_bLoadSiblingKnowde == false)
      m_bTextViewWritable = false;
  }
  else if(m_bTextViewWritable == false)
  {
    // clear text view auto save timeout
    if(m_autoSaveTimeOut != null)
        clearTimeout(m_autoSaveTimeOut);
  }
}

function TextViewControl_onMouseOut()
{
  if(m_bTextViewWritable == true && m_textViewChanged == 1)
  {
    // user move mouse out of the editing area, trigger auto save
    // in case user navigate out by click a category or go to other link
    
    if(m_autoSaveTimeOut != null)
        clearTimeout(m_autoSaveTimeOut);
        
      var div = m_EditFrame.contentWindow.document.getElementById('k' + m_strSelectedKnowdeID);
      var adiv = m_EditFrame.contentWindow.document.getElementById('k' + m_strSelectedKnowdeID + '-active');
      var content = '';
      
      if(adiv != null)
        content = adiv.innerHTML;
      else if(div != null)
        content = div.innerHTML;
      else
        content = m_EditFrame.contentWindow.document.body.innerHTML;
        
      if(content.length > 0)
      {
        m_bLoadSiblingKnowde = true;
        SaveTextView('Action=AutoSave|Repopulate=false|KGId=' + m_strSelectedKGID + '|KnowdeId=' + m_strSelectedKnowdeID);
      }
  }
}

function SetAutoSaveButtonStatus(_status)
{
    var btn = document.getElementById('TextViewAutoSaveBtn');
    if(_status == 1)
    {
      //KGTextTabControl_HideOrShowLoadingDiv(true, 'Saving...');
      SetInnerText(btn,'Saving...');
      btn.className = 'ButtonToolbar_TextViewAutoSaveBtnRed';
    }
    else if(_status == 0)
    {
      //KGTextTabControl_HideOrShowLoadingDiv(false);
       m_EditFrameDiv = document.getElementById('TextViewEditFrameDiv');
       // only show Saved if the Saving was showing
      if(btn.className == 'ButtonToolbar_TextViewAutoSaveBtnRed')
      {
        SetInnerText(btn,'Saved');
        btn.className = 'ButtonToolbar_TextViewAutoSaveBtnOff';
      }
    }else
    {
      SetInnerText(btn,'');
      btn.className = 'ButtonToolbar_TextViewAutoSaveBtnOn';
    }
}

function ShowOrHideSavingDiv(_status, _message, _top, _left)
{
  if (m_textViewMode == "KNOWDEDOC")
  {
    if(_status == 1)
    {
      //KGTextTabControl_HideOrShowLoadingDiv(true, 'Saving...');
      SetAutoSaveButtonStatus(_status);
    }
    else
    {
      //KGTextTabControl_HideOrShowLoadingDiv(false);
      window.setTimeout('SetAutoSaveButtonStatus(0)', 1000);
    }
  }
  else if (m_textViewMode == "HKGROUPDOC")
  {
    if(_status == 1)
    {
      //ConfigureCommunitySpace_ShowOrHideHKDocBusyDiv(true, "Saving...");
      SetAutoSaveButtonStatus(_status);
    }
    else
    {
      //ConfigureCommunitySpace_ShowOrHideHKDocBusyDiv(false);
      window.setTimeout('SetAutoSaveButtonStatus(0)', 1000);
    }
  }
}

/*function TextView_RTEonkeyup()
{
  //SetupKnowdeTextViewDiv(m_strSelectedKnowdeID);
  m_EditFrame.style.height = m_EditFrame.contentWindow.document.body.scrollHeight + m_editFrameHeightMargin + 'px';
}
*/

function DisplayClosePreviewWarningBox()
{
  var browserName = navigator.userAgent;
  
  if(browserName.indexOf('Firefox') != -1)
  {
    // OK button keep losing focus so have to click twice in FF
    var messageBox = document.getElementById("ClosePreviewWindowMessageDiv");
    
    if(messageBox == null)
    {
      messageBox = document.createElement("div");
      messageBox.setAttribute("id", "ClosePreviewWindowMessageDiv");
      messageBox.style.width = "450px"
      messageBox.style.height = "80px";
      messageBox.style.position = "absolute";
      messageBox.style.zIndex = TopZIndex();
      
      // position
      messageBox.style.top = screen.availHeight/2 - 150;
		  messageBox.style.left = screen.availWidth/2 - 225;
      messageBox.innerHTML = "<div class='MessageBox' style='font-size: x-small; padding: 10px;' ><nobr>Please close the preview full document window to continue editing.</div>";
      
      var parentControlDiv = document.getElementById('Form1');
      InsertAdjacentElement(parentControlDiv,"beforeEnd", messageBox);
    }
    else
    {
      messageBox.style.zIndex = TopZIndex(); //Show on top of other items
      
      if (messageBox.style.display == 'none')
        messageBox.style.display = 'block';  
      else
      {
        var anim = new YAHOO.util.Anim('ClosePreviewWindowMessageDiv', AniFadeInMapItemAttributes, 0, YAHOO.util.Easing.easeNone);
        anim.animate(); // Make the notice visible immediately (the 0 parameter)
      }
    }
    
    setTimeout("FadeMapItemOut('ClosePreviewWindowMessageDiv')", 4000);
    
  }else
  {
    var messageBox = document.getElementById("ClosePreviewWindowMessageDiv");
    
    if(messageBox == null)
    {
      messageBox = document.createElement("div");
      messageBox.setAttribute("id", "ClosePreviewWindowMessageDiv");
      messageBox.style.width = "450px"
      messageBox.style.height = "80px";
      messageBox.style.position = "absolute";
      messageBox.style.zIndex = TopZIndex();
      
      // position
      messageBox.style.top = screen.availHeight/2 - 150;
		  messageBox.style.left = screen.availWidth/2 - 225;
      // onmouseover='focusOn(\"closePreviewMessageButton\");'
      messageBox.innerHTML = "<div class='MessageBox' style='padding: 10px;' ><table border='0' cellpadding='5' cellspacing='0'><tr><td style='font-size:x-small;'><nobr>Please close the preview full document window to continue editing.</td></tr><tr><td align='center'></nobr><button id ='closePreviewMessageButton' type='button' onclick='ClosePreviewWarningBox()' style='width: 50px;'>Ok</button></td></tr></table></div>";
      
      var parentControlDiv = document.getElementById('Form1');
      InsertAdjacentElement(parentControlDiv,"beforeEnd", messageBox);
    }
    else
    {
      messageBox.style.zIndex = TopZIndex(); //Show on top of other items
    }
  }
}

function ClosePreviewWarningBox()
{
  var messageBox = document.getElementById("ClosePreviewWindowMessageDiv");
  if(messageBox != null)
  {
   var parent = messageBox.parentNode;
   parent.removeChild(messageBox);
  }
}

function HandleTextTabResize()
{
    //m_textViewSpanResizeTimeOut = setTimeout('HandleTextViewSpanResize()', 1000); 
    /*frame = document.getElementById("TextViewEditFrameDiv");
    if(m_EditFrameDiv != null && m_KnowdeIdList !=  null && m_KnowdeIdList.length > 0)
    SetupKnowdeTextViewDivs();*/
   
    m_textFrameScrollTimeOut = setTimeout('HandleTextFrameScroll()', 1000);

}

function HandleTextViewSpanResize()
{
  if(m_textViewSpanResizeTimeOut != null)
  {
      clearTimeout(m_textViewSpanResizeTimeOut);
      m_textViewSpanResizeTimeOut =  null;
  }

  if(globalShowingWebDoc == true || m_bTextViewWritable == false || m_textViewControlSpanFixedSize != 1) //not text view
    return;
    
  //debugger;
  
  
   if(m_textViewControlSpanFixedSize == 1 && m_bTextViewWritable == true)
    {
      //debugger;
      var container = document.getElementById('TCC_moretext'); //TextViewControlContent
      var tvcontrol = document.getElementById('TextViewControl1');
      if(container != null && tvcontrol != null)
      {
        tvcontrol.style.height = (container.style.height.replace('px','') - 75) + 'px';
        if(container.style.width.indexOf('%') != -1)
          tvcontrol.style.width = '550px';
        else
          tvcontrol.style.width = (container.style.width.replace('px','')- 5) + 'px';

      }
      
    }
}

/****************************************************
 TextTabControl
 ***************************************************/
 
 var m_textFrameLoadingDivTimeOut;
 var m_textFrameCallbackStatus = 'none';
 var m_textTabFrame;
 
 var m_textFrameScrollTimeOut = null;
 var m_bTextFrameManualScroll = false;
 var m_textFrameScrollMoreOnTopTimeOut;
 var m_textFrameScrollDelay = 50; //ms
 var m_bTextFrameLoadSiblingKnowde = false;
 
 // most of these variables are now used in TextViewControl.js
var m_tickerKnowdeID = '';

// for aggregate text view partial loading
var m_FrameLoadedKnowdeIdList = new Array();
var m_FrameLoadedKnowdeIdString = '';
var m_FrameUnLoadedKnowdeIdString = '';
var m_FrameKnowdePathString = '';

// knowde and client knowde list
var m_FrameKnowdeIdsArray = new Array();
var m_FrameKnowdeClientIdsArray = new Array();

var m_FrameDivIDArray = new Array();
var m_FrameDivPathArray = new Array();
var m_FrameDivHeightArray = new Array();

var m_strFrameSelectedKGID = '';
var m_strFrameSelectedKnowdeID = '';
var m_strFrameSelectedKnowdeDBID = '';
var m_strFrameSelectedKnowdeContext = '';
var m_strFrameCentreKnowdeContext = '';
var m_strFrameViewMode = '';

var m_frameDivGapHeight = 15;
var m_frameScrollTopOffSet = 50;

var m_currentTextViewViewMode = "Single"; // Single or Full
var m_textViewViewModeChanged = false;

var Active_KnowdeID_Text = '';

var m_textViewControlSpanFixedSize = 0; // for firefox
var m_textViewSpanResizeTimeOut;

var m_textFrameHighlightColor = '#EAF4F7'; 
var m_textFrameHighlightBorderLeftStyle = '2px #A7A9E2 solid'; //8EA4DB A7A9E2
var m_textFrameHighlightBorderLeftPadding = '5';

function AutoLoadTextViewForKnowde(_action, _knowdeID)
{
  //if (m_IsEditFromNewKnowde == true) // check in handleKnowdeClick instead
    //return;
  // auto load the currently selected knowde textview
  var currentKnowdeID = objectiveID;
  if(_knowdeID != null)
    currentKnowdeID = _knowdeID;
  else 
  {
    var whatId = '';
    if(_action == 'ChangeTab')
    {
	    whatId = GetGlobalHighlightedWhatId();
    }
    if(whatId != '')
      currentKnowdeID = whatId;
    else if(globalLastSelectedKnowde != null)
      currentKnowdeID = returnKnowdeID(globalLastSelectedKnowde);
  }  
  
  if(_action != null && _action != 'StopEditing' && _action != 'StartSingleTextEditing')
  {
    KGTextTabControl_HideOrShowTextViewEditButton(false, true);
  }
  
  if (currentKnowdeID != null && currentKnowdeID != "")
  {
      if(_action != null && (_action == 'StopEditing' || _action == 'StartSingleTextEditing'))
      {
        if(_action == 'StopEditing')
          SwitchTextTabControlMode(false);
        SwitchTextViewViewMode("Single");
      }
          
      SetSessionProperty('TickerKnowde', currentKnowdeID);
      m_tickerKnowdeID = currentKnowdeID;
      if ((m_bEditable == false && _action != 'StartSingleTextEditing') 
          || (_action != 'StartEditing' && m_currentTextViewViewMode == 'Full'))
      {
          // load text view
            DisplayTextViewInTab("TextForSpecifiedKnowde", globalSplitterSetting, "true"); 
            //KGTextTabControl_HideOrShowPreviewFullTVButton(false);
            globalLastTickerAction = "TextForSpecifiedKnowde" + currentKnowdeID;
      }else // edit mode
      {
         if(_knowdeID == null && m_IsEditFromNewKnowde == true) // change tab reload when in edit new knowde mode
         {
            // don't load the text yet, make sure the option div is hidden 
            // need this for create new kg in callback or auto enter edit mode for kg that do not have any knowde yet
            SwitchTextTabControlMode(true);
            SwitchTextViewViewMode("Single");
         }
         else if(!(globalLastTickerAction && globalLastTickerAction.length > 0 && globalLastTickerAction == ("KnowdeSelected-ReloadTextView" + currentKnowdeID)))
         {
            // moved text view save to a function for easy reading of handleKnowdeClick
	          TextViewSaveFromKnowdeClick(_knowdeID);
	          
	          if(_action.indexOf('-Edit') == -1) // not what/whatIs edit
	          {
	            var actionPrefix = 'KnowdeSelected';
	            if(_action.indexOf('WhatSelected') == 0 || _action.indexOf('WhatIsSelected') == 0)
	              actionPrefix = 'KnowdeHover';
  	          
              DisplayTextViewInTab(actionPrefix + "-ReloadTextView", globalSplitterSetting, "true"); 
              //KGTextTabControl_HideOrShowPreviewFullTVButton(false);
              globalLastTickerAction = actionPrefix + "-ReloadTextView" + currentKnowdeID;
            }else
            {
               // clear textview
              /*m_EditFrameDiv = document.getElementById('TextViewEditFrameDiv');

              if(m_EditFrameDiv != null)
                m_EditFrameDiv.innerHTML = "";
              globalLastTickerAction = "";  
              m_textFrameCallbackStatus = 'none';*/
            }
         }
      }
      globalAutoLoadTextView = false;
  }
}

function TextViewSaveFromKnowdeClick(_knowdeID)
{
  // XD - seems the saving will only occur after the SetSessionProperty('PageSession_KGMapContext', sessionString) later on
  //      so the text view will be saved to the wrong map, therefore pass in extra args
  if(m_bTextViewWritable == true && m_knowdeDeleted == 0 && 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)
    var tvChanged = ChangeSelectedTextView(_knowdeID);
    m_bLoadSiblingKnowde = false;
    if(tvChanged == false)
    {
      saveArgs += '|Repopulate=false';
      // the line below need to be taken out if we change back to mutliple knowde text view again
      m_bLoadSiblingKnowde = true;
    }
    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); 
  }
  else
  {
    // clear text view auto save timeout
    if(m_autoSaveTimeOut != null)
      clearTimeout(m_autoSaveTimeOut);
        
    m_bLoadSiblingKnowde = false;
  }
}
 
function DisplayTextViewInTab(_message, _params, _openText, _kgId)
{
 
  if (!(_message == "TextView" ||  _message=="TextForSpecifiedKnowde" || _message.indexOf('ReloadTextView') != -1))
    return;//We're no longer using the xml help

  // make sure the more text tab is selected
  //if(globalVisibleTab != 'TSC_moretext')
    //ChangeTab('moretext', 'More Text');
  
  //debugger;
  globalHelpTopicKey = _message;
  
  if(_message.indexOf('ReloadTextView') != -1)
  {
    SwitchTextTabControlMode(true);
    SwitchTextViewViewMode("Single");
  }
  else
    SwitchTextTabControlMode(false);

  if(globalHelpTopicKey == "TextView" || globalHelpTopicKey == "TextForSpecifiedKnowde" || globalHelpTopicKey.indexOf("ReloadTextView") != -1)
  {
    m_bTextFrameLoadSiblingKnowde = false;
     var kgid = Active_KGID;
    if(_kgId != null && _kgId > 0)
      kgid = _kgId;
    var params = '';
    if(_message=="TextForSpecifiedKnowde" || _message == "TextView")
    {
      if(m_textViewViewModeChanged == false && m_currentTextViewViewMode == "Full" && m_strFrameSelectedKGID != '' && m_strFrameSelectedKGID == kgid )
        //&& ((m_strFrameSelectedKnowdeID != '' && m_strFrameSelectedKnowdeID == m_tickerKnowdeID) || (m_strFrameSelectedKnowdeDBID != '' && m_strFrameSelectedKnowdeDBID == m_tickerKnowdeID)))
      {
        m_bTextFrameLoadSiblingKnowde = true;
      }
      
      if(m_tickerKnowdeID != '')
      {
        var kndPathContext = FindSelectedTextFrameKnowdePathContext(m_tickerKnowdeID);
        var knowdeChanged = ChangeSelectedTextFrameKnowde(m_tickerKnowdeID, kndPathContext);  
      }
      ///debugger;
      params = GetTextViewCallBackArgs(_kgId);
    }
    
     // No point in reloading the text if its already being displayed!
     if(_message.indexOf('ReloadTextView') != -1 || (m_tickerKnowdeID != Active_KnowdeID_Text || m_currentTextViewViewMode == 'Full'))
     {
        KGTextTabControl_CallbackTrigger(_message, params); //, globalHelpTopicParams); //We're no longer using the xml help
     }
     
   }    
   
  // reset the value 
  m_textViewViewModeChanged = false;
  
}

function KGTextTabControl_CallbackTrigger_Wrapped(_key, _params, _callbackScript)
{
  // Make sure we clear the contents of the document window
  if(_key != 'NewWindowTextView' && m_bTextFrameLoadSiblingKnowde == false)
    ClearTextTabFrame(false);

  // show textview view mode option if in read mode
  // need to use set time out otherwise iframe height become 0 in Safari and Chrome
  if(m_bEditable == true || m_bWhatTextWritable == true)
  {
    window.setTimeout('KGTextTabControl_HideOrShowTextViewOptionDiv(false)',5);
    window.setTimeout('KGTextTabControl_HideOrShowPreviewFullTVButton(true)',5);
  }
  else
  {
    window.setTimeout('KGTextTabControl_HideOrShowTextViewOptionDiv(true)', 5);
    window.setTimeout('KGTextTabControl_HideOrShowPreviewFullTVButton(false)',5);
  }
  
  // hide or show the textview edit button for what text editing
  if(m_tickerKnowdeID != null && m_tickerKnowdeID != '' && GetGlobalHighlightedWhatId() == m_tickerKnowdeID
  && globalLastHighlightedWhat != null && m_IsEditFromNewWhat != true && globalLastHighlightedWhat.getAttribute('IsUserKI') == 'true'
  && AllowWhatEditOnly == 1)
    window.setTimeout('KGTextTabControl_HideOrShowTextViewEditButton(true)', 5);
  else
    window.setTimeout('KGTextTabControl_HideOrShowTextViewEditButton(false)', 5);

      
  var args;
  //debugger;
  // Construct the callback arguments
  if(_key != null)
  { 
    args = 'key=' + _key + "|params=" + _params;
    
    if(args.length > 0)
    {
      m_textFrameCallbackStatus = 'trigger';
      if(_key.indexOf('ReloadTextView') == -1)
      {
        // show loading div
        if(args.indexOf('LoadTrigger=Scrolling') == -1)//(m_bTextFrameLoadSiblingKnowde == false)
        {
          if(m_textFrameLoadingDivTimeOut != null)
          {
            clearTimeout(m_textFrameLoadingDivTimeOut);
            m_textFrameLoadingDivTimeOut = null;
          }
          KGTextTabControl_HideOrShowLoadingDiv(true, 'Loading...');
          //m_textFrameLoadingDivTimeOut = window.setTimeout("KGTextTabControl_HideOrShowLoadingDiv(true, 'Loading...')",1);
        }
      }
      // trigger the callback
      eval(_callbackScript);  
    }
  }
}

function KGTextTabControl_CallbackDone(_args, _context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  //debugger;
  m_textFrameCallbackStatus = 'done';
  m_textTabFrame = document.getElementById("TextTabFrame");

  var action = '';
  if(_args.indexOf('[@|@]') != -1)
  {
    action = _args.substring(0, _args.indexOf('[@|@]'));
    _args = _args.substring(_args.indexOf('[@|@]') + 5);
  }
  
  if(action.indexOf('-ReloadTextView') != -1)
  {
    // edit mode textview
    var ids = _args.split('@');
    var controlId = ids[0];
    var content = _args.substring(controlId.length+1);
    var hccontainer = document.getElementById('TCC_moretext');
    var tvControl = document.getElementById('TextViewControlContent');
    if(tvControl != null && hccontainer != null)
    {
      //debugger;
      if (tvControl.childNodes.length == 2) //IE
      {
        if(tvControl.childNodes[0].style.height != '30px')
        {
          tvControl.childNodes[0].style.height = '30px';
          tvControl.childNodes[0].style.position = 'absolute';
          tvControl.childNodes[0].style.top = '0px';
        }
        SetOuterHtml(tvControl.childNodes[1], content);
        
        /*if(tvControl.childNodes[1].style.height != '100%')
        {
          tvControl.childNodes[1].style.height = '100%'; //(hccontainer.clientHeight - 75) + 'px';
          tvControl.childNodes[1].style.width = '100%'; //(hccontainer.clientWidth - 5) + 'px';
          tvControl.childNodes[1].style.borderTop = 'solid 30px white';
          tvControl.childNodes[1].style.display = 'block';      
          //m_textViewControlSpanFixedSize = 1;
        }*/
        setTimeout("KGTextTabControl_AdjustTextViewControlSize()",100);

      }
      else if (tvControl.childNodes.length == 4) //FF - counts carriage returns in html as textnodes
      {
        if(tvControl.childNodes[0].style.height != '30px')
        {
          tvControl.childNodes[0].style.height = '30px';
          //tvControl.childNodes[0].style.position = 'absolute';
          //tvControl.childNodes[0].style.top = '0px';
        }
        var container = document.getElementById('TextViewControlContent');

        //tvControl.childNodes[2].outerHTML = content;
        // not support outerHtml
        var tempElement = document.createElement("div");
        tempElement.style.overflow = 'auto';
        
        var start = content.indexOf('<');
        if(start > 0)
          content = content.substring(start);
        var end = content.lastIndexOf('>');
        if(end < content.length -1)
          content = content.substring(0, end + 1);
          
        tempElement.innerHTML = content;
        
        var root = null;
        for(var i=0; i<tempElement.childNodes.length; i++) 
        {
          if(tempElement.childNodes[i].nodeType == 1) 
          {
            root = tempElement.childNodes[i];
            root.style.display = 'block';
            
            if(container != null && root.style.height != '100%')
            {
              root.className = 'KGTextViewControlContainer';
              root.style.height = '100%'; //(hccontainer.clientHeight - 75) + 'px';
              root.style.width = '100%'; //(hccontainer.clientWidth - 5) + 'px';
              root.style.borderTop = 'solid 30px white';      
              
              //m_textViewControlSpanFixedSize = 1;
            }
            break;
          }
        }
        
        if(root)
          tvControl.replaceChild(root, tvControl.childNodes[2]);
          
                  
      }
      
   if(navigator.userAgent.indexOf('Firefox') != -1 || navigator.userAgent.indexOf('Safari') != -1 || navigator.userAgent.indexOf('Opera') != -1)
   {
        var iframeDiv = document.getElementById('TextViewEditFrameDiv');
        if(iframeDiv != null)
          iframeDiv.style.position = 'relative';
   }


      setTimeout("LoadTextView()",300);
      
    }
      KGTextTabControl_HideOrShowLoadingDiv(false);

      m_textFrameCallbackStatus = 'none';
  }
  else
  { // read only text view
    if(_args.indexOf('|<TextViewInfo>|') != -1)
    {
      var values = _args.split('|<TextViewInfo>|');
      // set selected knowde id
      var ids = values[0].split('@');
      // get action key
      var actionKey = ids[0];
      var viewmode = ids[1];
      if(actionKey != 'NewWindowTextView')
      {
        // get old kgId
        var oldFrameKGID = m_strFrameSelectedKGID;
        // set view mode
        m_strFrameViewMode = viewmode;
        // set kgId
        m_strFrameSelectedKGID = ids[2];
        // knowdeID
        m_strFrameSelectedKnowdeDBID = ids[3];
        // use client Id for the moment
        m_strFrameSelectedKnowdeID = ids[4];
        var knowdeContexts = values[0].substring(ids[0].length + ids[1].length + ids[2].length + ids[3].length + ids[4].length + 5).split('||');
        m_strFrameSelectedKnowdeContext = knowdeContexts[0];
        m_strFrameCentreKnowdeContext = knowdeContexts[1];
        
        //alert(m_strFrameSelectedKnowdeID + '|' + m_strFrameSelectedKnowdeContext);
        
        if(oldFrameKGID != m_strFrameSelectedKGID || m_bTextFrameLoadSiblingKnowde == false)
        {
          // kg changed
          ClearTextTabFrame(false);
        }
       
        if(m_strFrameViewMode == "Full" && m_currentTextViewViewMode == m_strFrameViewMode)
        {
          // load all textviews
          HandleTextFrameLoadAll(values[1], values[2], 'TextTabFrame');
        }
        else if(m_strFrameViewMode == "Single" && m_currentTextViewViewMode == m_strFrameViewMode) 
        {
          // load single textview
          var content = values[2];
          var kndText = GetCurrentKnowdeTextForTextView(m_strFrameSelectedKnowdeID);
          if(kndText != '')
          {
            if(content == '')
            {
              content = GetDefaultTextViewContentWithTitle(m_strFrameSelectedKnowdeID, kndText, 1, m_noTextViewFoundContent);
              
              if(GetGlobalHighlightedWhatId() == m_strFrameSelectedKnowdeID
              && globalLastHighlightedWhat != null && globalLastHighlightedWhat.getAttribute('IsUserKI') == 'true'
              && AllowWhatEditOnly == 1 && content.indexOf(m_noTextViewFoundContent) != -1)
                content = content.replace(m_noTextViewFoundContent, m_noTextViewFoundAddYourOwn);

            }else
            {
              content = TrimTickerSpans(content);
              if (content.indexOf(m_textViewTickerSelectionHighlightColor) > -1)
                content = ReturnUnhighlightedTickerText(content);
                
              // check whether it has an existing title, if not, add the title manually
              if(CheckTextViewHasTitle(m_strFrameSelectedKnowdeID, kndText, content) == false)
                content = WrapTextViewContentWithTitle(m_strFrameSelectedKnowdeID, kndText, content);
            }
         }

          m_textTabFrame.contentWindow.document.write("<html><head><base target='_blank'><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body style='overflow:auto;'>"); //class='PersonalisedScrollBar' 
          m_textTabFrame.contentWindow.document.write(content);
          m_textTabFrame.contentWindow.document.write("</body></html>");
          
          setTimeout('KGTextTabControl_AdjustTextTabFrameSize()', 100);

         }
      }
      
   }
   
    // hide loading div
    /*if(m_textFrameLoadingDivTimeOut != null)
    {
      clearTimeout(m_textFrameLoadingDivTimeOut);
      m_textFrameLoadingDivTimeOut = null;
    }*/
    //m_textFrameLoadingDivTimeOut = window.setTimeout("HideOrShowHelpControlLoadingDiv(false)",20);
    KGTextTabControl_HideOrShowLoadingDiv(false);

    m_textFrameCallbackStatus = 'none';
  }
}

function KGTextTabControl_CallbackError(_args, _context)
{
  m_textFrameCallbackStatus = 'none';
  
  alert('Callback error on KGTextTabControl. \n\n' + _args);
}

function KGTextTabControl_AdjustTextViewControlSize()
{
   var tvControl = document.getElementById('TextViewControlContent');
   if(tvControl != null && tvControl.childNodes.length == 2)
   {
       tvControl.childNodes[1].className = 'KGTextViewControlContainer';
       tvControl.childNodes[1].style.height = '100%'; //(hccontainer.clientHeight - 75) + 'px';
       tvControl.childNodes[1].style.width = '100%'; //(hccontainer.clientWidth - 5) + 'px';
       tvControl.childNodes[1].style.borderTop = 'solid 30px white';
       tvControl.childNodes[1].style.display = 'block';   
   }
}

function KGTextTabControl_AdjustTextTabFrameSize()
{
   var m_textTabFrame = document.getElementById('TextTabFrame');
   if(m_textTabFrame != null)
   {
       m_textTabFrame.style.pixelHeight = '';
       
       m_textTabFrame.style.width = '100%';
       m_textTabFrame.style.height = '100%';
       m_textTabFrame.style.display = 'block';
       m_textTabFrame.height = '100%';
       m_textTabFrame.width = '100%';
   }
}

function FindSelectedTextFrameKnowdePathContext(_knowdeID)
{
  //debugger;
  var pathContext = '';
  
  if(_knowdeID != null && m_strFrameSelectedKnowdeDBID != '')
  {
    var knowdeID = _knowdeID;
    if(knowdeID < 0)
    {
      // find the knowdeID  instead
      for(var ki = 0; ki < m_FrameKnowdeClientIdsArray.length; ki++)
      {
        if(m_FrameKnowdeClientIdsArray[ki] == knowdeID)
        {
          knowdeID = m_FrameKnowdeIdsArray[ki];
          break;
        }
      }
    }
    
    if(knowdeID > 0 && knowdeID != m_strFrameSelectedKnowdeDBID)
    {
      // basic logic to find possible knowde context and locate the correct text view if knowde is reused
      // might need to be improved later on
      var pathStr = '';
      // in text view assocations:
      // new selected knowde is walked after the previous selected knowde
      var re = new RegExp('(\\[' + m_strFrameSelectedKnowdeDBID + '\\]([^,]+)\\['+knowdeID+'\\])', 'gi');
      // new selected knowde is walked before the previous selected knowde
      var re2 = new RegExp('(\\[' + knowdeID + '\\]([^,]+)\\['+m_strFrameSelectedKnowdeDBID+'\\])', 'gi');
      var matchResult = re.exec(m_FrameKnowdePathString);
      pathStr = m_FrameKnowdePathString;
      if(matchResult == null)
      {
        matchResult = re2.exec(m_FrameKnowdePathString);
      }
      
      if(matchResult != null)
      {
        var foundContext = '';
        var foundIdx = matchResult.index;
        if(foundIdx >= 0)
        {
          var endIdx = pathStr.indexOf(',',foundIdx);
          if(endIdx > 0)
          {
            var pathStr2 = pathStr.substr(0, endIdx);
            var startIdx = pathStr2.lastIndexOf(',');
            if(startIdx == -1)
              foundContext = pathStr2;
            else
              foundContext = pathStr2.substr(startIdx+1);
              
            if(foundContext != '')
            {
              var kidx = foundContext.indexOf('['+knowdeID+']');
              if(kidx != -1)
              {
                foundContext = foundContext.substr(0, kidx + knowdeID.length + 2);
                if(pathStr.indexOf(foundContext + ',') == 0 || pathStr.indexOf(',' + foundContext + ',') != -1)
                  pathContext = foundContext;
              }
            }
          }
        }
      }
    }else if(knowdeID > 0 && knowdeID == m_strFrameSelectedKnowdeDBID)
    {
      pathContext = m_strFrameSelectedKnowdeContext;
    }
    // end if knowdeID > 0
    
  }
  return pathContext;
}

function ChangeSelectedTextFrameKnowde(_selectedKnowdeID, _selectedKnowdePath)
{
  if(m_strFrameSelectedKnowdeID != _selectedKnowdeID)
  {
    if(_selectedKnowdePath == null)
      _selectedKnowdePath = '';
    m_strFrameSelectedKnowdeContext = _selectedKnowdePath;
    m_strFrameSelectedKnowdeID = _selectedKnowdeID;
    return true;
  }
  else
    return false;
}


function ClearTextTabFrame(_clearSelectedValues)
{
  
  var TextTabFrame = document.getElementById("TextTabFrame");
  if (TextTabFrame.src != null && TextTabFrame.src != "")
  {
    /*var parent = TextTabFrame.parentNode;
    
    var newFrame = document.createElement('iframe');
    newFrame.id = "TextTabFrame";
    newFrame.className = "TextTabFrame";
    newFrame.frameBorder = 0;
      
    purge(TextTabFrame);  
    parent.removeChild(TextTabFrame);
    InsertAdjacentElement(parent,"beforeend", newFrame);*/
  }
  else
  {
    // Make sure we clear the contents of the document window
    TextTabFrame.contentWindow.document.write("");
    TextTabFrame.contentWindow.document.close();
  }
  
  // clear member variables
    //debugger;
  
  m_FrameLoadedKnowdeIdList = new Array();
  m_FrameLoadedKnowdeIdString = '';
  m_FrameUnLoadedKnowdeIdString = '';

  // knowde and client knowde list
  m_FrameKnowdeIdsArray = new Array();
  m_FrameKnowdeClientIdsArray = new Array();

  m_FrameDivIDArray = new Array();
  m_FrameDivPathArray = new Array();
  m_FrameDivHeightArray = new Array();
  m_FrameKnowdePathString = '';
  
  if(_clearSelectedValues == null || _clearSelectedValues == true)
  {
    m_strFrameSelectedKGID = '';
    m_strFrameSelectedKnowdeID = '';
    m_strFrameSelectedKnowdeDBID = '';
    m_strFrameSelectedKnowdeContext = '';
    m_strFrameCentreKnowdeContext = '';
    m_bTextFrameLoadSiblingKnowde = false;
  }
  
  m_textFrameScrollTimeOut = null;
}
 
 
 function HandleTextFrameLoadAll(_knowdeSequenceInfo, _loadedContentList)
{
  //debugger;

  if(m_bTextFrameLoadSiblingKnowde == false)
  {
    m_FrameLoadedKnowdeIdList = new Array();
    m_FrameLoadedKnowdeIdString = '';
  
    m_FrameKnowdeIdsArray = new Array();
    m_FrameKnowdeClientIdsArray = new Array();
    
    m_FrameKnowdePathString = '';
    
    var frameDivHtml = '';
    
    // loop through all the knowdes m_strSelectedKnowdeID is the currently selecte knowde
    // knowdes above and below will be loaded in top and bottom iframes
    // don't use split incase the knowde title contains character that is used as our seperator
    var foundCurrentKnowde = 0;
    var kidx = _knowdeSequenceInfo.indexOf('(kid=');
    while(kidx >= 0)
    {
      var kidx2 = _knowdeSequenceInfo.indexOf('|ckid=', kidx+1);
      if(kidx2 > kidx)
      {
        var knowdeId = _knowdeSequenceInfo.substr(kidx+5, kidx2-(kidx+5));
        var kidx3 = _knowdeSequenceInfo.indexOf('|path=', kidx2+1);
        if(kidx3 > kidx2)
        {
          var clientKnowdeId = _knowdeSequenceInfo.substr(kidx2+6, kidx3-(kidx2+6));
          
          // store the knowde and client id mapping
          m_FrameKnowdeIdsArray.push(knowdeId);
          m_FrameKnowdeClientIdsArray.push(clientKnowdeId);
          
          var kidx4 = _knowdeSequenceInfo.indexOf('|title=', kidx3+1);
          if(kidx4 > kidx3)
          {
            var pathContext = _knowdeSequenceInfo.substr(kidx3+6, kidx4-(kidx3+6));
            kidx = _knowdeSequenceInfo.indexOf(')(kid=', kidx4+1);
            var knowdeTitle = '';
            if(kidx > kidx4)
            {
              knowdeTitle = _knowdeSequenceInfo.substr(kidx4+7, kidx-(kidx4+7));
              kidx = kidx + 1; // because we are searching for )( instead of just (
            }else if(kidx == -1)
            {
              knowdeTitle = _knowdeSequenceInfo.substr(kidx4+7, _knowdeSequenceInfo.length-1-(kidx4+7));
            }
            
            // now create div and load to the content
            var frame = m_textTabFrame;
             
             if(frame != null)
             {
               var loaded = 0;
               var sidx = _loadedContentList.indexOf('<HKTextView' + clientKnowdeId + '>');
               var sidx2 = _loadedContentList.indexOf('</HKTextView>', sidx+1);
               var content = '';
               if(sidx != -1 && sidx2 != -1)
               {
                  loaded = 1;
                  content = _loadedContentList.substr(sidx+11+clientKnowdeId.length+1,sidx2-(sidx+11+clientKnowdeId.length+1));
                  var kid = clientKnowdeId;
                 
                  m_FrameLoadedKnowdeIdList.push(kid);
                  m_FrameLoadedKnowdeIdString += kid + ','
                 
                  var bidx = content.toLowerCase().indexOf('<body');
                  var bidx2 = content.indexOf('>');
                  var bidx3 = content.toLowerCase().indexOf('</body>');
                  if(bidx != -1 && bidx2 > bidx && bidx3 > bidx2)
                    content = content.substr(bidx2+1, bidx3-(bidx2+1));
        
                  if(content == '')
                  {
                    content = GetDefaultTextViewContentWithTitle(clientKnowdeId, knowdeTitle, 1, m_noTextViewFoundContent);
                  }else
                  {
                    content = TrimTickerSpans(content);
                    if (content.indexOf(m_textViewTickerSelectionHighlightColor) > -1)
                      content = ReturnUnhighlightedTickerText(content);
                      
                    // check whether it has an existing title, if not, add the title manually
                    if(CheckTextViewHasTitle(clientKnowdeId, knowdeTitle, content) == false)
                      content = WrapTextViewContentWithTitle(clientKnowdeId, knowdeTitle, content);
                  }
                                    
               }else
               {
                 loaded = 0;
                 // text view is not loaded yet
                 content = GetDefaultTextViewContentWithTitle(clientKnowdeId, knowdeTitle, 1, m_notLoadedText);
                 m_FrameUnLoadedKnowdeIdString += clientKnowdeId + ','
               }
               
              if((m_strFrameSelectedKnowdeID == knowdeId || m_strFrameSelectedKnowdeID == clientKnowdeId)
              && m_strFrameSelectedKnowdeContext == '')
              {
                  m_strFrameSelectedKnowdeContext = pathContext;
              }
               
               //for scrolling position detection debug only//
               //content = pathContext + '<br>' + content; 
              
               m_FrameKnowdePathString += pathContext + ',';
               
                    var divHtml = "<div id='" + pathContext + "' kid='" + clientKnowdeId + "' title='" + knowdeTitle + "' isLoaded='" + loaded + "' width='100%'>";
                    //if (content.indexOf(m_textViewTickerSelectionHighlightColor) > -1)
                      //content = ReturnUnhighlightedTickerText(content);
                    
                    // directly add content can't deal with not proper formatted HTML
                    // like  missing ticker span close tag etc and then cause iframe's innerHTML 
                    // to be auto corrected later on by added a </span> in the end 
                    // so causing problem because childNodes is not right anymore
                    //divHtml += content; 
                    var tempDiv = document.createElement("div");
                    tempDiv.innerHTML = content; // the content will be auto corrected and guanrantee the ifram only contains divs as first level child nodes
                    divHtml += tempDiv.innerHTML; 
                    divHtml += "</div>";
                      
                    frameDivHtml += divHtml;
                 
             }
            
          }
        }
      }
    }// end while
    
    m_textTabFrame.contentWindow.document.write("<html><head><base target='_blank'><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body style='overflow:auto;' onscroll='parent.TextFrameScrollTimeOut(\"TextTabFrame\")'>"); //class='PersonalisedScrollBar' 
    m_textTabFrame.contentWindow.document.write(frameDivHtml);
    m_textTabFrame.contentWindow.document.write("</body></html>");
     
  } // end if
  else
  {
    
    // need to find out where the knowde is
    var knowdeFrame = '';
      
    // patial load text views
    if(_loadedContentList && _loadedContentList != ''
      && m_textTabFrame != null)
    {
       // loop through each textview content
        var sidx = _loadedContentList.indexOf('<HKTextView');
        var sidx2 = _loadedContentList.indexOf('>', sidx);
        var sidx3 = _loadedContentList.indexOf('</HKTextView>', sidx2);
        while(sidx != -1 && sidx2 != -1 && sidx3 != -1)
        {
          var content = _loadedContentList.substr(sidx2+1, sidx3-(sidx2+1));
          var kid = _loadedContentList.substr(sidx+11,sidx2-(sidx+11));
          
          if((m_FrameLoadedKnowdeIdString.indexOf(kid+',') != 0)
          && (m_FrameLoadedKnowdeIdString.indexOf(','+kid+',') == -1))
          {
            m_FrameLoadedKnowdeIdList.push(kid);
            m_FrameLoadedKnowdeIdString += kid + ',';
            
            // remove from unloaded list
            if(m_FrameUnLoadedKnowdeIdString.indexOf(kid+',') == 0)
              m_FrameUnLoadedKnowdeIdString = m_FrameUnLoadedKnowdeIdString.substring(kid.length+1);
            else
              m_FrameUnLoadedKnowdeIdString = m_FrameUnLoadedKnowdeIdString.replace(','+kid+',', ',');
              
            // load all the unloaded textviews for this knowde to the given content
            var bidx = content.toLowerCase().indexOf('<body');
            var bidx2 = content.indexOf('>');
            var bidx3 = content.toLowerCase().indexOf('</body>');
            if(bidx != -1 && bidx2 > bidx && bidx3 > bidx2)
               content = content.substr(bidx2+1, bidx3-(bidx2+1));
               
            var method = function(el){if(el.getAttribute('kid') == kid) return true; return false;};
            var frameDivs = YAHOO.util.Dom.getChildrenBy(m_textTabFrame.contentWindow.document.body,method);   
            for(var iCounter = 0; iCounter < frameDivs.length; iCounter++)
            {
                  var childDiv = frameDivs[iCounter];
                  
                  if(content == '')
                      content = childDiv.innerHTML.replace(m_notLoadedText, m_noTextViewFoundContent);
                  else
                  {
                    content = TrimTickerSpans(content);
                    if (content.indexOf(m_textViewTickerSelectionHighlightColor) > -1)
                      content = ReturnUnhighlightedTickerText(content);
                      
                    //for scrolling position detection debug only//
                    //content = childDiv.id + '<br>' + content; 
                    
                    // check whether it has an existing title, if not, add the title manually
                    var ckid = childDiv.getAttribute('kid');
                    var ktitle = childDiv.getAttribute('title');
                    if(CheckTextViewHasTitle(ckid, ktitle, content) == false)
                      content = WrapTextViewContentWithTitle(ckid, ktitle, content);
                  }
                  

                  if(childDiv != null && childDiv.getAttribute('kid') == kid && (childDiv.getAttribute('isLoaded') == 0 || childDiv.getAttribute('isLoaded') == '0'))
                  {
                    childDiv.innerHTML = content;
                    childDiv.setAttribute('isLoaded', 1);
                  }
             }      

            
          }
          
                         
            _loadedContentList = _loadedContentList.substr(sidx3+13);
            sidx = _loadedContentList.indexOf('<HKTextView');
            sidx2 = _loadedContentList.indexOf('>', sidx);
            sidx3 = _loadedContentList.indexOf('</HKTextView>', sidx2);
          
        }    // end while
      
    }
  }
  
  window.setTimeout("SetupTextFrameKnowdeTextViewDivs()",200);
}

function SetupTextFrameKnowdeTextViewDivs()
{
  //debugger;
  m_textTabFrame = document.getElementById("TextTabFrame");
  var adiv = null;
  
  if(m_textTabFrame != null)
    adiv = m_textTabFrame.contentWindow.document.body;

  m_FrameDivIDArray = new Array();
  m_FrameDivPathArray = new Array();
  m_FrameDivHeightArray = new Array();
  // m_FrameKnowdePathString  = '';

  var pos = 0;
  if(m_textTabFrame != null && adiv != null)
  {
     if(m_strFrameSelectedKnowdeContext == '' && m_strFrameSelectedKnowdeID != '')
     {
        var method = function(el){if(el.getAttribute('kid') == m_strFrameSelectedKnowdeID) return true; return false;};
        //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,adiv);  
        var frameDivs = YAHOO.util.Dom.getChildrenBy(adiv,method);   
        if(frameDivs.length > 0)
          m_strFrameSelectedKnowdeContext = frameDivs[0].id;
     }
                
        if(m_strFrameCentreKnowdeContext != '')
        {
          var method = function(el){if(el.id == m_strFrameCentreKnowdeContext) return true; return false;};
          //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,adiv);  
          var frameDivs = YAHOO.util.Dom.getChildrenBy(adiv,method);   
          if(frameDivs.length > 0)
          {
            // make sure scroll to this position
            m_bTextFrameManualScroll = true;
            
            var scrollTopValue = frameDivs[0].offsetTop - m_textTabFrame.offsetHeight/2;
            //scrollTopValue = scrollTopValue - m_frameScrollTopOffSet;
            if(scrollTopValue < 0)
              scrollTopValue = 0;
            adiv.scrollTop  = scrollTopValue;
          }
          
        }
        
        if(m_strFrameSelectedKnowdeContext != '')
        { 
          if(m_previousHighLightedPath != '')
          {
              // unhighlight
            var method = function(el){if(el.id == m_previousHighLightedPath) return true; return false;};
            //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,adiv);  
            var frameDivs = YAHOO.util.Dom.getChildrenBy(adiv,method);   
            if(frameDivs.length > 0)
            {
              //frameDivs[0].style.backgroundColor = 'white';
              frameDivs[0].style.borderLeft = 'none';
              frameDivs[0].style.paddingLeft = '0px';
              frameDivs[0].style.marginLeft = '0px';
            }
           
          }
          
          // highlight
          var method = function(el){if(el.id == m_strFrameSelectedKnowdeContext) return true; return false;};
          //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,adiv);  
          var frameDivs = YAHOO.util.Dom.getChildrenBy(adiv,method);   
          if(frameDivs.length > 0)
          {
            if(m_strFrameCentreKnowdeContext == '')
            {
              // make sure scroll to this position
              // m_bTextFrameManualScroll = true;
              var scrollTopValue = frameDivs[0].offsetTop - (m_frameScrollTopOffSet + 20);
              if(scrollTopValue < 0)
                scrollTopValue = 0;
              m_textFrameScrollMoreOnTopTimeOut = window.setTimeout("TextScrollMoreFromTop('TextTabFrame'," + scrollTopValue + ", 0)", m_textFrameScrollDelay);
              //adiv.scrollTop  = scrollTopValue;
            }
            
            // now get rid of the empty <P> tags in the end which makes the next div overlay a bit with the current div
            var content = frameDivs[0].innerHTML;
            content = content.replace(/(<p\/>|<p><\/p>|<p \/>|<p><br \/><\/p>|<p><br\/><\/p>)+$/i,'');//remove trailing empty paragraph
            content = content.replace(/(<p\/>|<p><\/p>|<p \/>|<p><br \/><\/p>|<p><br\/><\/p>)<\/div>+$/i,'</div>');//remove trailing empty paragraph
            frameDivs[0].innerHTML = content;

            frameDivs[0].style.borderLeft = m_textFrameHighlightBorderLeftStyle;
            frameDivs[0].style.paddingLeft = m_textFrameHighlightBorderLeftPadding + 'px';
            frameDivs[0].style.marginLeft = '-' + m_textFrameHighlightBorderLeftPadding + 'px';
            
           m_previousHighLightedPath = frameDivs[0].id;
         }
          
      }        
    
  }
  
    setTimeout('KGTextTabControl_AdjustTextTabFrameSize()', 100);
}


function ChangeSelectedTextTabFrameKnowde(_selectedKnowdeID, _selectedKnowdePath)
{
  if(m_strFrameSelectedKnowdeID != _selectedKnowdeID)
  {
    if(_selectedKnowdePath == null)
      _selectedKnowdePath = '';
    m_strFrameSelectedKnowdeContext = _selectedKnowdePath;
    m_strFrameSelectedKnowdeID = _selectedKnowdeID;
    return true;
  }
  else
    return false;
}

function GetTextViewCallBackArgs(_kgId)
{
  m_textTabFrame = document.getElementById("TextTabFrame");
  var kgid = Active_KGID;
  if(_kgId != null && _kgId > 0)
    kgid = _kgId;
  var args = "|KGId=" + kgid + "|ViewMode=" + m_currentTextViewViewMode;
  
  var loadamount = m_textTabFrame.offsetHeight/40/2;
    if(m_textViewPreLoadAmount > loadamount)
      loadamount = m_textViewPreLoadAmount;
  args += "|PreLoadAmount=" + loadamount;
  
  if(m_bTextFrameLoadSiblingKnowde == true)
  {
    args += "|LoadSiblingKnowde=true";
    var toLoadDivs = '';
    var knowdeContext = m_strFrameSelectedKnowdeContext;
    
    toLoadDivs = GetPreLoadDivsForTextFrameSelectedKnowde(m_tickerKnowdeID, knowdeContext, loadamount);       
    
    args += '|KnowdeId=' + m_tickerKnowdeID + '|KnowdePathContext=' + knowdeContext + '|KnowdeIdList=' + toLoadDivs;;
    
    if(toLoadDivs == '')
      args += "|KnowdeLoaded=true";
    else
      args += "|KnowdeLoaded=false";
  }else
  {
    // assume each text view has minimum 40px height
    args += "|KnowdeLoaded=false";
  }
  
  return args;
}

function FindSelectedTextViewFrameKnowdePathContext(_knowdeID)
{
  //debugger;
  var pathContext = '';
  
  if(_knowdeID != null && m_strFrameSelectedKnowdeDBID != '')
  {
    var knowdeID = _knowdeID;
    if(knowdeID < 0)
    {
      // find the knowdeID  instead
      for(var ki = 0; ki < m_FrameKnowdeClientIdsArray.length; ki++)
      {
        if(m_FrameKnowdeClientIdsArray[ki] == knowdeID)
        {
          knowdeID = m_FrameKnowdeIdsArray[ki];
          break;
        }
      }
    }
    
    if(knowdeID > 0 && knowdeID != m_strFrameSelectedKnowdeDBID)
    {
      // basic logic to find possible knowde context and locate the correct text view if knowde is reused
      // might need to be improved later on
      var pathStr = '';
      // in text view assocations:
      // new selected knowde is walked after the previous selected knowde
      var re = new RegExp('(\\[' + m_strFrameSelectedKnowdeDBID + '\\]([^,]+)\\['+knowdeID+'\\])', 'gi');
      // new selected knowde is walked before the previous selected knowde
      var re2 = new RegExp('(\\[' + knowdeID + '\\]([^,]+)\\['+m_strFrameSelectedKnowdeDBID+'\\])', 'gi');
      var matchResult = re.exec(m_FrameKnowdePathString);
      pathStr = m_FrameKnowdePathString;
      if(matchResult == null)
      {
        matchResult = re2.exec(m_FrameKnowdePathString);
      }
      
      if(matchResult != null)
      {
        var foundContext = '';
        var foundIdx = matchResult.index;
        if(foundIdx >= 0)
        {
          var endIdx = pathStr.indexOf(',',foundIdx);
          if(endIdx > 0)
          {
            var pathStr2 = pathStr.substr(0, endIdx);
            var startIdx = pathStr2.lastIndexOf(',');
            if(startIdx == -1)
              foundContext = pathStr2;
            else
              foundContext = pathStr2.substr(startIdx+1);
              
            if(foundContext != '')
            {
              var kidx = foundContext.indexOf('['+knowdeID+']');
              if(kidx != -1)
              {
                foundContext = foundContext.substr(0, kidx + knowdeID.length + 2);
                if(pathStr.indexOf(foundContext + ',') == 0 || pathStr.indexOf(',' + foundContext + ',') != -1)
                  pathContext = foundContext;
              }
            }
          }
        }
      }
    }else if(knowdeID > 0 && knowdeID == m_strFrameSelectedKnowdeDBID)
    {
      pathContext = m_strFrameSelectedKnowdeContext;
    }
    // end if knowdeID > 0
    
  }
  return pathContext;
}

function GetPreLoadDivsForTextFrameSelectedKnowde(_knowdeId, _knowdePath, _loadAmount)
{
  // when a knowde is selected in the mapview, find out what knowde text views need to be loaded around it
  var toLoadDivs = '';
  _loadAmount = Math.round(_loadAmount);
  
  if(_knowdePath == '')
  {
      // get the first occurrance of the knowde as default 
      var adiv = m_textTabFrame.contentWindow.document.body;
      
      var method = function(el){if(el.getAttribute('kid') == _knowdeId) return true; return false;};
      //var frameDivs = YAHOO.util.Dom.getElementsBy(method,null,adiv); 
      var frameDivs = YAHOO.util.Dom.getChildrenBy(adiv,method);
         
      if(frameDivs.length > 0)
         _knowdePath = frameDivs[0].id;
  }
    
  if(m_FrameLoadedKnowdeIdString.indexOf(_knowdeId + ',') != 0 &&  m_FrameLoadedKnowdeIdString.indexOf(',' + _knowdeId + ',') == -1)
    toLoadDivs = _knowdeId + ',';
    
  if(_knowdePath != '')
  {
    if(_knowdeId == m_strFrameSelectedKnowdeID)
      m_strFrameSelectedKnowdeContext = _knowdePath;
      
    // unique context found, now need to find out knowdes around the given knowde path
    var pathArray = m_textTabFrame.contentWindow.document.body.childNodes;
    
    var idx = -1;
    for(var icount = 0; icount < pathArray.length; icount++)
    {
      var childDiv = pathArray[icount];
      if(childDiv.id == _knowdePath)
      {
        idx = icount;
        break;
      }
    }
    if(idx >= 0)
    {
      var startIdx = idx - _loadAmount;
      var endIdx = idx + _loadAmount;
      if(startIdx < 0)
        endIdx -= startIdx;
      if(endIdx >= pathArray.length)
        startIdx -= (pathArray.length-1);
      if(startIdx < 0)
        startIdx = 0;
      if(endIdx >= pathArray.length)
        endIdx = pathArray.length - 1;
        
      for(var icount = startIdx; icount <= endIdx; icount++)
      {
        if(pathArray[icount])
        {
          if(m_FrameLoadedKnowdeIdString.indexOf(pathArray[icount].getAttribute('kid') + ',') != 0 &&  m_FrameLoadedKnowdeIdString.indexOf(',' + pathArray[icount].getAttribute('kid') + ',') == -1)
            toLoadDivs += pathArray[icount].getAttribute('kid') + ',';
        }
      }
    }
    
  }
  
  
  return toLoadDivs;
}


function SwitchTextViewViewMode(_newMode)
{
  if(m_textFrameCallbackStatus == 'trigger') // callback in process
  {
    alert('Text is still loading, please try later.');
    return;
  }
    
  var modeSwitchBtn = document.getElementById('TextViewModeSwitch');
  var previewSwitchBtn = document.getElementById('TextViewPreviewSwitch');
  if(_newMode == null)
  {
    if(m_currentTextViewViewMode == "Single")
    {
      // to full text view mode
      m_textViewViewModeChanged = true;
      m_currentTextViewViewMode = "Full";
      m_bTextFrameLoadSiblingKnowde = false;
      // load full text view
      var currentKnowdeID = m_strFrameSelectedKnowdeID;
      SetSessionProperty('TickerKnowde', currentKnowdeID);
      m_tickerKnowdeID = currentKnowdeID;
      DisplayTextViewInTab("TextForSpecifiedKnowde"); 
      
      if(modeSwitchBtn != null)
      {
        SetInnerText(modeSwitchBtn, "Back to Text Component"); 
      }
      
      if(previewSwitchBtn != null)
      {
        SetInnerText(previewSwitchBtn, "Back to Text Edit");
      }
    }else if(m_currentTextViewViewMode == "Full")
    {
      // to single text view mode
      //m_textViewViewModeChanged = true;
      m_currentTextViewViewMode = "Single";
      m_bTextFrameLoadSiblingKnowde = false;
      
      // get the existing seletected knowd div
      var divHtml = '';
      var currentframe = document.getElementById("TextTabFrame");
      if(currentframe != null)
      {
        var method = function(el){if(el.getAttribute('kid') == m_strFrameSelectedKnowdeID) return true; return false;};
        var frameDivs = YAHOO.util.Dom.getChildrenBy(currentframe.contentWindow.document.body,method);   
        if(frameDivs.length > 0)
        {
          var childDiv = frameDivs[0];
          divHtml = childDiv.innerHTML;
        }
      }

      // clear frame
      ClearTextTabFrame(false);
      
      // set variables like we actually done a callback done
      m_strFrameViewMode = "Single";
      // m_strFrameSelectedKGID, m_strFrameSelectedKnowdeDBID, m_strFrameSelectedKnowdeID remain unchanged
      m_strFrameSelectedKnowdeContext = "";
      m_strFrameCentreKnowdeContext = "";
      
      // load single text view
      if(currentframe != null)
      {
         if(GetGlobalHighlightedWhatId() == m_strFrameSelectedKnowdeID
         && globalLastHighlightedWhat != null && globalLastHighlightedWhat.getAttribute('IsUserKI') == 'true'
         && AllowWhatEditOnly == 1 && content.indexOf(m_noTextViewFoundContent) != -1)
         divHtml = divHtml.replace(m_noTextViewFoundContent, m_noTextViewFoundAddYourOwn);

          currentframe.contentWindow.document.write("<html><head><base target='_blank'><link href='CSS/KGHelpControl.css' type='text/css' rel='stylesheet'/><link href='CSS/TextViewDocument.css' type='text/css' rel='stylesheet'/></head><body style='overflow:auto;'>"); //class='PersonalisedScrollBar' 
          currentframe.contentWindow.document.write(divHtml);
          currentframe.contentWindow.document.write("</body></html>");
          
          setTimeout('KGTextTabControl_AdjustTextTabFrameSize()', 100);
      }
                      
      
      if(modeSwitchBtn != null)
      {
        SetInnerText(modeSwitchBtn, "Show Full Document"); 
      }
      
      if(previewSwitchBtn != null)
      {
        SetInnerText(previewSwitchBtn, "Preview Full Document");
      }
    }
  }else
  {
    if(_newMode == "Full" && m_currentTextViewViewMode != "Full")
    {
      // to full text view mode
      m_currentTextViewViewMode = "Full";
      
      if(modeSwitchBtn != null)
      {
        SetInnerText(modeSwitchBtn, "Back to Text Component"); 
      }
      
      if(previewSwitchBtn != null)
      {
        SetInnerText(previewSwitchBtn, "Back to Text Edit");
      }
    }else if(_newMode == "Single" && m_currentTextViewViewMode != "Single")
    {
      // to single text view mode
      m_currentTextViewViewMode = "Single";
      
      if(modeSwitchBtn != null)
      {
        SetInnerText(modeSwitchBtn, "Show Full Document"); 
      }
      
      if(previewSwitchBtn != null)
      {
        SetInnerText(previewSwitchBtn, "Preview Full Document");
      }
    }
  }
}

function KGTextTabControl_HideOrShowTextViewOptionDiv(_showOption)
{
//debugger;
  var optionDiv = document.getElementById('TextViewModeSwitch');
  //m_textTabFrame = document.getElementById("TextTabFrame");
  if(_showOption != null && _showOption == true)
  {
    if(optionDiv != null)
      optionDiv.style.display = 'block';
  }
  else
  {
    if(optionDiv != null)
      optionDiv.style.display = 'none';
  }
  
}


function KGTextTabControl_HideOrShowLoadingDiv_Wrapped(_divId, _show, _message)
{
  if(m_textFrameLoadingDivTimeOut != null)
  {
    clearTimeout(m_textFrameLoadingDivTimeOut);
    m_textFrameLoadingDivTimeOut = null;
  }
  
   var div = null; 
   
   if(_divId != null && _divId != '')
      div = document.getElementById(_divId);
   if(_message == null)
    _message = 'Loading...';
    
   if(_show != null && _show == true && (_message != 'Saving...' && m_textFrameCallbackStatus != 'trigger'))
   {
    // callback done has finished before the trigger time out to show the loading div, 
    // so don't need to show it anymore
    return;
   }
    
   if (div != null)
   {
    if(_show != null && _show == true)
    {
      if(div.style.display != 'block')
      {
        div.innerHTML = "<img src=\"Images/loadingbar.gif\" /> " + _message; // m_LoadingMessage;
        div.style.display = 'block';
  
        if(navigator.userAgent.indexOf('Firefox') != -1 || navigator.userAgent.indexOf('Safari') != -1 || navigator.userAgent.indexOf('Opera') != -1)
        {
          div.style.width = '100%';
        }
      }
    }else if(div.style.display != 'none')
    {
      div.style.display = 'none';
      div.innerHTML = '';
    }
   }
   
}

function PreviewFullTextView()
{
  if(m_textFrameCallbackStatus == 'trigger') // callback in process
  {
    alert('Text is still loading, please try later.');
    return;
  }
  // save text view
  SaveCurrentlyEditingTextView(false);
  
  // hide the button
  if(m_currentTextViewViewMode == "Single")
  {
    // set the view mode to full document
    SwitchTextViewViewMode("Full");
    m_textViewViewModeChanged = true;
    DisplayTextViewInTab('TextView', '', 'true', Active_KGID);
  }else
  {
    // back to single mode text edit 
    SwitchTextViewViewMode("Single");
    
    DisplayTextViewInTab("KnowdeSelected-ReloadTextView", globalSplitterSetting, "true"); 
    globalLastTickerAction = "KnowdeSelected-ReloadTextView" + m_tickerKnowdeID;
  }
}


function TextFrameScrollTimeOut(_frameID)
{
  if(m_textFrameScrollTimeOut != null)
  {
      clearTimeout(m_textFrameScrollTimeOut);
      m_textFrameScrollTimeOut =  null;
  }
  if(m_bTextFrameManualScroll == true)
  {
    m_bTextFrameManualScroll = false;
    return;
  }
  // if in full text view mode and has unloaded textviews, then trigger partial loading
  if(m_FrameUnLoadedKnowdeIdString != '' && m_strFrameViewMode == "Full")
  {
      m_textFrameScrollTimeOut = setTimeout('HandleTextFrameScroll()', 2000);
  }
}

function HandleTextFrameScroll(_frameID)
{
   
  //debugger;
  
  if(m_textFrameScrollTimeOut != null)
  {
      clearTimeout(m_textFrameScrollTimeOut);
      m_textFrameScrollTimeOut =  null;
  }
  
    
  //debugger;
  var frameType = '';
  m_textTabFrame = document.getElementById("TextTabFrame");
  var textFrameDiv = null;
  
  // get frame info and decide which frame to do the partial loading
  var textFrameWidth = -1;
  if(m_textTabFrame != null)
  {
    textFrameDiv = m_textTabFrame.contentWindow.document.body;
    textFrameWidth = m_textTabFrame.offsetWidth;;
  }
  
  var frameDiv = null;
  var frame = null;
  if(_frameID != null && _frameID != '')
    frame = document.getElementById(_frameID);
    
  if(frame == null)
  {
    if(textFrameDiv != null && textFrameWidth != -1)
    {
      frameType = 'Popup';
      frameDiv = textFrameDiv;
      frame = m_textTabFrame;  
    }
  }else
  {
    frameDiv = frame.contentWindow.document.body;
  }
    
  if(frameDiv != null)
  {
    // clear the knowde hover scroll timeout because user now manually scrolling
    clearTimeout(m_textFrameScrollMoreOnTopTimeOut);

    var scrollTop = frameDiv.scrollTop;
    var visibleStartPosition = scrollTop;
    var visibleEndPosition = scrollTop + frame.offsetHeight;
    var centrePosition = visibleStartPosition + frame.offsetHeight/2;
    
    // also preload stuff that fall into 100px ouside the visible range
    if(visibleStartPosition - 60 <= 0)
      visibleStartPosition = 0
    else
      visibleStartPosition -= 60;
    
    if(visibleEndPosition + 60 >= frameDiv.scrollHeight + 30)
      visibleEndPosition = frameDiv.scrollHeight + 30
    else
      visibleEndPosition += 60;
        
    // check which divs are in visible area
    var visibleDivs = '';
    var toLoadDivs = '';
    var centreID = '';
    var centrePath = '';
      // might need to load top frame contents
      var pos = 0;
            
      /*for(var dividx = 0; dividx < m_FrameDivIDArray.length; dividx++)
      {
        if((pos+ parseInt(m_FrameDivHeightArray[dividx]) >= visibleStartPosition && pos <= visibleEndPosition))
        {
          visibleDivs += m_FrameDivIDArray[dividx] + ',';
          if(pos <= centrePosition && pos+ parseInt(m_FrameDivHeightArray[dividx]) >= centrePosition)
          {
            centreID = m_FrameDivIDArray[dividx];
            centrePath = m_FrameDivPathArray[dividx];
          }
          // check whether need to load this div
          if((m_FrameUnLoadedKnowdeIdString.indexOf(m_FrameDivIDArray[dividx]+',') == 0)
          || (m_FrameUnLoadedKnowdeIdString.indexOf(','+m_FrameDivIDArray[dividx]+',') != -1))
          {
            toLoadDivs += m_FrameDivIDArray[dividx] + ',';
          }
        }
        pos += parseInt(m_FrameDivHeightArray[dividx]);
        pos += m_frameDivGapHeight;
      }*/
      
      for(var dividx = 0; dividx < frame.contentWindow.document.body.childNodes.length; dividx++)
      {
        var childDiv = frame.contentWindow.document.body.childNodes[dividx];
        
        if((childDiv.offsetHeight + childDiv.offsetTop >= visibleStartPosition && childDiv.offsetTop <= visibleEndPosition))
        {
          visibleDivs += childDiv.getAttribute('kid') + ',';
          if(childDiv.offsetTop <= centrePosition && childDiv.offsetTop + childDiv.offsetHeight >= centrePosition)
          {
            centreID = childDiv.getAttribute('kid');
            centrePath = childDiv.id;
          }else if(childDiv.offsetTop > centrePosition && centreID == '')
          {
            // the middle point fall into the gap between two divs, sometimes there is a 19px gap between
            centreID = childDiv.getAttribute('kid');
            centrePath = childDiv.id;
          }
          // check whether need to load this div
          if((m_FrameUnLoadedKnowdeIdString.indexOf(childDiv.getAttribute('kid')+',') == 0)
          || (m_FrameUnLoadedKnowdeIdString.indexOf(','+childDiv.getAttribute('kid')+',') != -1))
          {
            toLoadDivs += childDiv.getAttribute('kid') + ',';
          }
        }else if(centreID != '')
          break;
      }

    //alert(centreID + '|' + centrePath + '#' + visibleDivs);
    // store the centre knowde path context
    m_strFrameCentreKnowdeContext = centrePath;
    //alert('Center: ' + centrePath);
        
    if(toLoadDivs != '')
    {
      if(centreID == '' || centrePath == '')
      {
        alert('Invalid centre ID and Path.');
        //debugger;
      }
      else
      {
        m_bTextFrameLoadSiblingKnowde = true;
        // trigger callback to partial load
        var args = "|KGId=" + m_strFrameSelectedKGID + '|KnowdeId=' + m_strFrameSelectedKnowdeID + '|KnowdePathContext=' + m_strFrameSelectedKnowdeContext + '|KnowdeTitle=|CentreKnowdePathContext=' + centrePath + '|KnowdeIdList=' + toLoadDivs;
        args += "|LoadSiblingKnowde=true";
        args += "|KnowdeLoaded=false";
        args += "|LoadTrigger=Scrolling";
        args += "|ViewMode=Full";
        
        if(m_textFrameScrollTimeOut != null) // been scroll again
        {
            //clearTimeout(m_textFrameScrollTimeOut);
            // m_textFrameScrollTimeOut =  null;
        }else
          KGTextTabControl_CallbackTrigger('TextView', args); //, globalHelpTopicParams); //We're no longer using the xml help
      }
    }
    
  }
}

function TextScrollMoreFromTop(_target, _scrollTop, _amount)
{
  //debugger;
  var div = null;
  m_textTabFrame = document.getElementById("TextTabFrame");
  var adiv = null;
  
  if(m_textTabFrame != null)
    adiv = m_textTabFrame.contentWindow.document.body;

  if(_target == 'TextTabFrame')
  {
    clearTimeout(m_textFrameScrollMoreOnTopTimeOut);
    m_textFrameScrollMoreOnTopTimeOut = null;
    div = adiv;
  } 
  //debugger;
  if(div != null)
  {
    //alert(_scrollTop + '|' + _amount + '|' + div.scrollTop);

    if(_scrollTop < 0)
      _scrollTop = 0;
      
    if(_amount <= 0)
    {
      // calculate scroll amount
      var diff = Math.abs(_scrollTop - div.scrollTop);
      if(diff == 0)
        return;
      else if(diff < 100)
      {
        _amount = Math.ceil(diff/2); // minum 2 times
      }
      else if(diff <= 500)
        _amount = 50;
      else
      {
        _amount = Math.ceil(diff/10); // maximum do it 10 times
      }
      if(_amount <= 0)
        _amount = 10;
    }
    
      var scrollTo = div.scrollTop;
      if(div.scrollTop > _scrollTop)
      {
        scrollTo -=  _amount;
        if(scrollTo < _scrollTop)
          scrollTo = _scrollTop;
      }else if(div.scrollTop < _scrollTop)
      {
        scrollTo += _amount;
        if(scrollTo > _scrollTop)
          scrollTo = _scrollTop;
      }
      // now scroll to the position
      m_bTextFrameManualScroll = true;
      div.scrollTop = scrollTo;
      // if we have scroll to the desire location, and also haven't reach the end 
      if(div.scrollTop != _scrollTop && div.scrollTop == scrollTo)
      {
        if(_target == 'TextTabFrame')
        {
          m_textFrameScrollMoreOnTopTimeOut = window.setTimeout("TextScrollMoreFromTop('TextTabFrame'," + _scrollTop + "," + _amount + ")", m_textFrameScrollDelay);
        }
      }
  }    
}

function SwitchTextTabControlMode(_editable)
{
  //debugger;
 	
  if(_editable != null && _editable == true )
  {
    // text view edit mode
    var div = document.getElementById('TextTabControlContent');
    if(div != null)
    {
      div.style.display = 'none';
      // hide link button by default, will show on callback trigger
      KGTextTabControl_HideOrShowTextViewOptionDiv(false);
    }
    var div2 = document.getElementById('TextViewControlContent');
    if(div2 != null && div2.style.display != 'block')
    {
      div2.style.display = 'block';
      // hide link button by default, will show on callback trigger
      KGTextTabControl_HideOrShowPreviewFullTVButton(false);
      KGTextTabControl_HideOrShowTextViewEditButton(false);
      
      KGTextTabControl_AdjustTextViewControlSize();
      
    }
    
  }
  else
  {
    var div2 = document.getElementById('TextViewControlContent');
    if(div2 != null)
    {
      div2.style.display = 'none';
      // hide link button by default, will show on callback trigger
      KGTextTabControl_HideOrShowPreviewFullTVButton(false);
    }
    var div = document.getElementById('TextTabControlContent');
    if(div != null && div.style.display != 'block')
    {
      div.style.display = 'block';
      // hide link button by default, will show on callback trigger
      KGTextTabControl_HideOrShowTextViewOptionDiv(false);
      KGTextTabControl_HideOrShowTextViewEditButton(false);
      
      //if(navigator.userAgent.indexOf('Safari') != -1)
      //{
        //row.style.height = (row.parentNode.clientHeight - 10) + 'px';
        //row.style.width = (row.parentNode.clientWidth - 10) + 'px';
      //}
    }
    
    
  }
}

function KGTextTabControl_HideOrShowPreviewFullTVButton(_show)
{
  var btn = document.getElementById('TextViewPreviewSwitch');
  
  if(btn != null)
  {
    if(_show == true)
    {
        btn.style.display = 'block';
    }
    else
    {
        btn.style.display = 'none';
    }
  }
}

function KGTextTabControl_HideOrShowTextViewEditButton(_show, _reset)
{
  var btn = document.getElementById('TextViewEditSwitch');
  
  if(btn != null)
  {
    if(_reset == true)
    {
      m_bWhatTextWritable = false;
      SetInnerText(btn, "Start Editing"); 
    }
      
    if(_show == true)
    {
        btn.style.display = 'block';
    }
    else
    {
        btn.style.display = 'none';
    }
  }
}

function SwitchSingleTextViewEditing()
{
  if(m_bWhatTextWritable != true) 
  {
    // need to go into edit mode
    // check whether the textview is for currently selected what
    // and whether it's a UserKI what
    if(CurrentlyShowingWhats !=  true || m_strFrameSelectedKnowdeID == null || m_strFrameSelectedKnowdeID == '' 
      || GetGlobalHighlightedWhatId() != m_strFrameSelectedKnowdeID || m_IsEditFromNewWhat == true
      || globalLastHighlightedWhat == null || globalLastHighlightedWhat.getAttribute('IsUserKI') != 'true'
      || AllowWhatEditOnly != 1)
    {
      alert("You are not allow to edit this knowde's text.");
      return;
    }
    
    m_bWhatTextWritable = true;
    
    // go into edit mode
    AutoLoadTextViewForKnowde('StartSingleTextEditing', m_strFrameSelectedKnowdeID);

  }
  else
  {
    m_bWhatTextWritable = false;
    
    if(m_bTextViewWritable == true && m_EditFrame != null) 
    {
      SwitchTextViewEditing();
    }    

    AutoLoadTextViewForKnowde('StopEditing', m_strFrameSelectedKnowdeID);
  }
      
   var switchBtn = document.getElementById('TextViewEditSwitch');

   if(switchBtn != null)
   {
     if(m_bWhatTextWritable == true)
      SetInnerText(switchBtn, "Stop Editing"); 
     else
      SetInnerText(switchBtn, "Start Editing"); 
   }
}

function HandleNewKnowdeForTextView()
{
  SaveCurrentlyEditingTextView(false);
  
  m_EditFrameDiv = document.getElementById('TextViewEditFrameDiv');

  if(m_EditFrameDiv != null)
  {
    m_EditFrameDiv.innerHTML = "";
    SetAutoSaveButtonStatus(-1);
  }
  globalLastTickerAction = "";
}



// JScript File
function KGDetailsControl_CallbackDone(args, context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
    
  if(args.toString() == "true")
  {
		// Toggle the control to hide it 
		KGDetailsControl_ToggleControl();
		window.setTimeout("Pfl_KGUserObjectSummaryControl_CallbackTrigger('action=refresh|kgId=0')", 10);
		return;
  }
  // Test if we have any callback result
  // YES: Continue processing 
  //  NO: Fail the callback with error message
  if(args.length > 0)
  {
    var token = args.split('|');
		
    // Test if we have a correct formatted callback result
    // FORMAT is <ControlDivId>@<HTML of the control>
    // YES: Continue processing 
    //  NO: Fail the callback with error message
    if(token.length > 0)
    {
      // Split the callback result into holderId and CallbackResult string
      var holderID = token[0];
      var callbackResult  = token[1];
			
      // Test if we have valid values
      // YES: Continue processing 
      //  NO: Fail the callback with error message
      if(holderID.length > 0 && callbackResult.length > 0)
      {
        // Get a handle on the DOM element for the control 
        var holder = document.getElementById(holderID);
				
        // Test if we have the correct DOM element
        // YES: we update the control with new HTML
        //  NO: fail the callback with error message
        if(holder != null)
        {
          // debugger;
          SetOuterHtml(holder,callbackResult);
          KGDetailsControl_ToggleControl();
        }
        else
          KGDetailsControl_CallbackError('Control div cannot be found.');
      }
      else
        KGDetailsControl_CallbackError('Malformed Callback Reuslt.');
    }
    else
      KGDetailsControl_CallbackError('Malformed Callback Reuslt.');
  }
  else
    KGDetailsControl_CallbackError('Empty callback result string.');			
    
  // make sure the publish control is hidden, otherwise it will pop to top left after rerender
  if(g_publishHolderId != null && window.KGPublishOptionControl_HideMenu)
  {
    KGPublishOptionControl_HideMenu(g_publishHolderId);
  }
	
}

function KGDetailsControl_CallbackError(_msg)
{
    alert('AJAX callback failed on KGDetailsControl:' + _msg);
}

function KGDetailsControl_CancelButton_Click()
{
  // Toggle the control to hide it 
  KGDetailsControl_ToggleControl();
}

function KGDetailsControl_SaveButton_Click()
{
	KGDetailsControl_CallbackTrigger(null, true);
}

function KGDetailsControl_CallbackTrigger_Wrapped(_kgId, _save, _cbRef)
{
	//debugger;
	var args;
	if(_save == true)
	{
		var detailsDesc = document.getElementById("SiteOverlays_LoginView1_KGDetailsControl_KGDescription");
		detailsDesc = detailsDesc.innerText;
		var args='save=true|desc=' + detailsDesc;
		eval(_cbRef);
	}
	else
	{
		if(_kgId<=0)
			return;
		var args='kgId='+_kgId;
		eval(_cbRef);
	}
}
// JScript File
function KGUserDescriptionControl_CallbackDone(args, context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  // extract the predefined control client IDs
  var s = args.split('|');
  if(s.length > 1)
  {
    var id = s[0];
    var htmlText = s[1];
    
    // search for the control container
    var holder = document.getElementById(id);
    
    // Test if the container is found
    // Yes: replace the innerHTML with the callback result
    //  No: call CallbackError with Content div not found error message
    if(holder != null)
    {
      SetOuterHtml(holder,htmlText);   
    }//end if(holder ....
    else
    {
      KGUserDescriptionControl_CallbackError('ContentDiv not found in KGUserDescriptionControl.', '');
    }
  }
}

function KGUserDescriptionControl_CallbackError(args, context)
{
  alert(args);
}

function KGUserDescriptionControl_EditButtonClick()
{
  var args = 'action=start_update';
  KGUserDescriptionControl_CallbackTrigger(args);
}

function KGUserDescriptionControl_SaveButtonClick(_TextAreaControlID)
{
  // debugger;
  var userDescriptionText = document.getElementById(_TextAreaControlID);
  var newUserDescription = '';

  if(userDescriptionText != null)
    newUserDescription = userDescriptionText.value;

  var args = 'action=save_update|newDescription='+newUserDescription;
  KGUserDescriptionControl_CallbackTrigger(args);
}

function KGUserDescriptionControl_CancelButtonClick()
{
  var args = 'action=cancel_update';
  KGUserDescriptionControl_CallbackTrigger(args);
}
// JScript File
var m_MessageBoxSP = null;
var CurrentlyShowingMessageBoxSP = null;
var selectedGroupIdForCancelSP = null;

function KGSubscriptionControl_CallbackError(args, context, resultDiv)
{
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    var controlDiv = document.getElementById(resultDiv);
    
    if(controlDiv != null)
      controlDiv.innerHTML = args;
    else
      alert('Callback on KGSubscriptionControl has failed: ' + args);
  }
}

// CallbackDone
function KGSubscriptionControl_CallbackDone_Wrapped(args, context, resultDiv)
{
	if(globalReloadCategories == true)
	{
		globalReloadCategories = false;
		setTimeout("HorizontalCategoriesControl_Reload();", 200);
	}
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
   
  // extract all the cdatas lines from callback result
  var actions = args.split('[@|@]');
  args = args.substring(actions[0].length+5);

  var cdatas = args.split('<![CDATA[');
  
  // extract the predefined control client IDs
  var s = args.split('=');
  var ids = s[0].split('@');
  
  // search for the control container
  var holder = document.getElementById(resultDiv);
  
  // Test if the container is found
  // Yes: replace the innerHTML with the callback result
  //  No: call CallbackError with Content div not found error message
  if(holder != null)
  {
    // holder.innerHTML = args.substring(args.indexOf('=') + 1);
    holder.innerHTML = args;
    
    // loop through the cdatas and process each of them
    // ignoring the first one coz it is just HTML
    var z = 0;
    for(z = 1; z < cdatas.length; z++)
    {
      // javascript starting position
      var posStart = cdatas[z].indexOf('window');
      
      // javascript ending position 
      var posEnd = cdatas[z].lastIndexOf('}') + 1;
      
      if(posStart > -1 && posEnd > -1)
      {
        // attemp to extract the javascript
        var jscript = cdatas[z].substring(posStart, posEnd);
       
        // Now we have the potential jscript we need to execute it to 
        // reinitiallise the grid
        if(jscript.length != 0)
        {        
          // redefine the init script on Page
          eval(jscript);
          var posNameStart = jscript.indexOf('window');
          var posNameEnd = jscript.indexOf('=');
          
          var functionName = jscript.substring(posNameStart, posNameEnd);
          // execute the script
          eval(functionName+'()');
        }// end if(jscript.....
      }// end if(posStart ......         
    }// end for
    
    if(actions[0] == 'CancelSP')
    {
      // refresh the page so the horizontal category and user object summary list can be refreshed
      window.setTimeout('KGSubscriptionControl_PageReload()', 10);
    }
  }//end if(holder ....
  else
  {
    KGSubscriptionControl_CallbackError('ControlDiv not found in KGSubscriptionControl.', '');
  }
}

function KGSubscriptionControl_PageReload() 
{
  //debugger;
  try
  {
    var args = "Action=Load";
    Pfl_KGMemberControl_CallbackTrigger(args);
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}
function KGSubscriptionControl_ViewPaymentHistoryClick(_groupid)
{
  try
  {
    var keys = 'KGCurrentGroupID|Topics_SelectedTopicGroupId';
	  var values = _groupid + '|' + _groupid;
    SetSessionProperty(keys, values, true);

    //SetSessionProperty('KGCurrentGroupID', _groupid);
    //SetSessionProperty('Topics_SelectedTopicGroupId', _groupid);
    
    //SetSessionProperty('ConfigureCommunitySpace_Mode','PAYMENTHISTORY');
    
    try
    {
      if (m_srmGetTimes!= null && m_srmGetTimes == "True")
      {
        var now = new Date();
        SetSessionProperty('Srm_T0', now.getTime());
        SetSessionProperty('Srm_Action', 'PAYMENTHISTORY');
        SetSessionProperty('Srm_Callbacks', 1);
      }
    }
    catch(e){}
  
    window.location = "ConfigureCommunitySpace.aspx?Mode=PAYMENTHISTORY";
  }
  catch (e) 
  {
    alert("An exception occurred in the KGSubscriptionControl_ViewPaymentHistoryClick_Wrapped. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function KGSubscriptionControl_ConfigureCommunitySpace(_groupID)
{
  try
  {
    SetSessionProperty('KGCurrentGroupID', _groupID);
    SetSessionProperty('Topics_SelectedTopicGroupId', _groupID);
    //SetSessionProperty('ConfigureCommunitySpace_Mode','GENERAL');
    
    try
    {
      if (m_srmGetTimes!= null && m_srmGetTimes == "True")
      {
        var now = new Date();
        SetSessionProperty('Srm_T0', now.getTime());
        SetSessionProperty('Srm_Action', 'ConfigurePrivateSpace');
        SetSessionProperty('Srm_Callbacks', 1);
      }
    }
    catch(e){}
  
    //window.location = "PrivateSpaceAdmin.aspx"; 
    window.location = "ConfigureCommunitySpace.aspx";
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function KGSubscriptionControl_DislayCancelSPMessage(_groupId, _controlDivClientID)
{
  try
  {
    selectedGroupIdForCancelSP = _groupId;
    EnsureCancelSPMessage(_controlDivClientID);
    PositionMessageBoxSP(_controlDivClientID, false, e);
  }
  catch (e) 
  {
    alert("An exception occurred in the KGSubscriptionControl_DislayCancelSPMessage(). Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

///////////////////////
// Ensures that the cancel private space message box is on the page
function EnsureCancelSPMessage(_parentControlDivId)
{
  m_MessageBoxSP = document.getElementById("CancelSPMessageBox");
  
  if(m_MessageBoxSP == null)
  {
    m_MessageBoxSP = document.createElement("div");
    m_MessageBoxSP.setAttribute("id", "CancelSPMessageBox");
    m_MessageBoxSP.style.display = "none";
    m_MessageBoxSP.style.width = "400px"
    m_MessageBoxSP.style.height = "120px";
    m_MessageBoxSP.style.position = "absolute";
    m_MessageBoxSP.style.zIndex = TopZIndex();
    
    m_MessageBoxSP.innerHTML = "<div class='MessageBox'><table border='0' cellpadding='5' cellspacing='0'><tr><td colspan='2' class='MessageBoxHeader'>UnSubscribe Private Space</td></tr><tr><td rowspan='2' valign='top'><img src='images/recycle.png' height='50' width='50'/></td><td style='font-size:x-small;'>Are you sure to remove subscription of this private space? <br />Click 'Yes' button to continue or 'Cancel' button to ignore it.</td></tr><tr><td align='right'><button type='button' onclick='KGSubscriptionControl_CancelSP()'>Yes</button><button id = defaultButton type='button' onclick='CloseMessageBoxSP()'>Cancel</button></td></tr></table></div>";
    
    var parentControlDiv = document.getElementById(_parentControlDivId);
    InsertAdjacentElement(parentControlDiv,"afterBegin", m_MessageBoxSP);
  }
  else
  {
    m_MessageBoxSP.style.zIndex = TopZIndex(); //Show on top of other items
  }
}
var globalReloadCategories = false;
function KGSubscriptionControl_CancelSP()
{
  m_MessageBoxSP.innerHTML= '<div style=\"position:absolute;width:400px;height:120px;border:gray solid 1pt;background:white\"><table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" />Cancelling Subscription....</td></tr></table></div>';
  globalReloadCategories = true;
  var args = 'action=CancelSP|groupId='+ selectedGroupIdForCancelSP;
  KGSubscriptionControl_CallbackTrigger(args);
}


//////////////////
// Closes the message box
function CloseMessageBoxSP()
{
  if(m_MessageBoxSP != null)
  {
    m_MessageBoxSP.style.visibility = "hidden";
    m_MessageBoxSP.style.display = "none";
    CurrentlyShowingMessageBoxSP = false;
  }
}

/////////////////////
// Positions the supplied message box relative to the cursor
function PositionMessageBoxSP(_parentControlDivId, _isKeyPressEvent, e)
{
  var parentControl = document.getElementById(_parentControlDivId); 
  
  
  if(_isKeyPressEvent)
  {
    // we don't know where the cursor is (may be off the page) so display in middle of parentControlDiv
    m_MessageBoxSP.style.top = (parentControl.offsetHeight/2);
    m_MessageBoxSP.style.left = (parentControl.offsetWidth/2) - (GetPixelWidth(m_MessageBoxSP)/2);
  }
  else
  {
    //Displays messagebox relative to cursor     
    e = e || window.event;
    var x = e.x || e.pageX;
    var y = e.y || e.pageY;
    
        
    m_MessageBoxSP.style.top = Math.min(document.body.clientHeight - GetPixelHeight(m_MessageBoxSP),y + 30);   
    if(_parentControlDivId.toLowerCase().indexOf("subscrip") != -1)  
    {
			m_MessageBoxSP.style.top = y;
			//debugger;
			//m_MessageBoxSP.style.top = parseInt(y.replace("px","")) + document.body.clientHeight + document.getElementById("TCC_myProfile").scrollTop;// parseInt(m_MessageBoxSP.style.top.replace("px","")) + 800;
    }
    m_MessageBoxSP.style.left = x - GetPixelWidth(m_MessageBoxSP) / 2;
    
  }
    
  m_MessageBoxSP.style.display = "block";
  m_MessageBoxSP.style.zIndex = TopZIndexSP();
  m_MessageBoxSP.style.visibility = "visible";
  focusOn("defaultButton");
  CurrentlyShowingMessageBoxSP = true;
}


function TopZIndexSP()
{
  var maxZindex = 0;
  var elems = document.getElementsByTagName("div");
  
  for (var ti=0; ti<elems.length; ti++)
  {
    if (elems[ti].style.zindex > maxZindex)
    {
       maxZindex = parseInt(elems[ti].style.zindex);
    }
  }

  return maxZindex + 1;
}

function KGSubscriptionControl_ConfigurePrivateSpace(_groupID)
{
  try
  {
    SetSessionProperty('KGCurrentGroupID', _groupID);
    SetSessionProperty('Topics_SelectedTopicGroupId', _groupID);
    //SetSessionProperty('ConfigureCommunitySpace_Mode','GENERAL');
    
    try
    {
      if (m_srmGetTimes!= null && m_srmGetTimes == "True")
      {
        var now = new Date();
        SetSessionProperty('Srm_T0', now.getTime());
        SetSessionProperty('Srm_Action', 'ConfigurePrivateSpace');
        SetSessionProperty('Srm_Callbacks', 1);
      }
    }
    catch(e){}
  
    //window.location = "PrivateSpaceAdmin.aspx"; 
    window.location = "ConfigureCommunitySpace.aspx";
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}


function CreateAnotherPrivateSpace()
{
	try
  {
		globalReloadCategories = true;
		var args = 'action=CreateAnotherPS';
		KGSubscriptionControl_CallbackTrigger(args);
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}
// JScript File

// This callback trigger is not of the normal Script callback trigger
// this time we use the iFrame as a way to trigger and deliver the assembled 
// file to the user
function PDFExporterControl_CallbackTrigger(_action, _btnType)
{
  var message = document.getElementById("KGButtonToolbar_CreatingPdfMessage");
  if (message != null)
  {
    PDFExporterControl_HideMenu();
    var menu = PDFExporterControl_GetMenu();
    if (menu)
    {
      message.style.top = (GetPixelTop(menu) + 5) + 'px';
      message.style.left = menu.style.left;
    }
    message.style.visibility = "visible";
  }

  if(_btnType == "print") // special case
  {
    var thePopup = window.open('','PDFFile');
    thePopup.document.write("<table class='ButtonToolbar_CreatingPdfMessage'><tr><td><img src='Images/loadingbar.gif' /></td><td>Creating file</td></tr></table>");  

    var qs = "location=browser&exporter=pdf&kgid=" + Active_KGID + "&type=" + _action;
    if (navigator.appName == "Opera")
    {
    // Opera will block the pdf if you load GenerateFile directly (for security - combination of js, pdf and iframe). 
    // This page has a link to the GenerateFile page, the link is clicked automatically when the iframe is loaded. Opera lets that one through
      thePopup.document.location = "BeforeGenerateFile.aspx?" + qs;
    }
    else
	    thePopup.document.location = "GenerateFile.aspx?" + qs;
  
  }
  else // not the print button
  {
    var exporter; // get the exporter from the button type
    switch (_btnType)
    {
      case 'pdf':
        exporter = 'pdf';
        break;
      case 'word':
        exporter = 'odt';
        break;
      default:
        exporter = 'pdf';
        break;
    }
    
    // Create an iFrame to prepare the way to generate and download
    // the PDF file
    var iframe = document.createElement("iframe");
  
    // Set the source URI to an empty processing page, the GenerateFile.aspx.
    // 1. In OnPageLoad event in the code behind of GenerateFile.aspx, the new page 
    //    will process the parameters to see which exporter to use, the target KGId and 
    //    which type of report it is going to generate
    // 2. It then goes off and start the file assembly and generation
    // 3. When the file is ready to download, it will just pass back an file stream object 
    //    with the HTTP Response, so the browser will know how to hand it 
    var qs = "exporter=" + exporter + "&kgid=" + Active_KGID + "&type=" + _action;
    if (navigator.appName == "Opera")
    {
      // Opera will block the pdf if you load GenerateFile directly (for security - combination of js, pdf and iframe). 
      // This page has a link to the GenerateFile page, the link is clicked automatically when the iframe is loaded. Opera lets that one through
      iframe.src = "BeforeGenerateFile.aspx?" + qs;
    }
    else
      iframe.src = "GenerateFile.aspx?" + qs;
    
    // Set the display mode to none so the iFrame will be hidden
    iframe.style.display = "none";
    
    // 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);
  }
  setTimeout("HidePDFMessage()",3000);
}

function HidePDFMessage()
{
  var message = document.getElementById("KGButtonToolbar_CreatingPdfMessage");
  
  if (message != null)
  {
    message.style.visibility = "hidden";
  }
}

// _btnType = pdf, print or word
function PDFExporterControl_ShowMenu_Wrapped(_controlDivId, _CSSCLASS, e, _btnType)
{
  var holder = document.getElementById(_controlDivId);
  
  if(holder != null)
  {
    holder.className = _CSSCLASS;
    UpdatePDFExporterControlPos('absolute', parseInt((e.x || e.pageX)), parseInt((e.y || e.pageY)) + 5);
  
    var targ = e.target || e.srcElement;
    
    var mapTextCell = document.getElementById("SiteOverlays_PDFExporterControl_maptext");
    var mapOnlyCell = document.getElementById("SiteOverlays_PDFExporterControl_map");
    var textOnlyCell = document.getElementById("SiteOverlays_PDFExporterControl_text");
    
    // set onclick so it can pass in the exporter
    mapTextCell.onclick = function(){PDFExporterControl_CallbackTrigger('maptext', _btnType); PDFExporterControl_HideMenu();};
    mapOnlyCell.onclick = function(){PDFExporterControl_CallbackTrigger('map', _btnType); PDFExporterControl_HideMenu();};
    textOnlyCell.onclick = function(){PDFExporterControl_CallbackTrigger('text', _btnType); PDFExporterControl_HideMenu();};
    
    // show or hide options
    if (_btnType == 'word')
    {
      mapTextCell.style.display = 'none';
      mapOnlyCell.style.display = 'none';
      textOnlyCell.style.display = '';
    }
    else
    {
      mapTextCell.style.display = '';
      mapOnlyCell.style.display = '';
      textOnlyCell.style.display = '';
    }
      
  }
}

function PDFExporterControl_HideMenu_Wrapped(_controlDivId, _hiddenCSSclass)
{
  var holder = document.getElementById(_controlDivId);
  
  if(holder != null)
    holder.className = _hiddenCSSclass;
}

var PDFExporterControl_HideMenuTimer;
var PDFExporterControl_HideMenuTimerLength = 500;

function PDFExporterControl_handleMenuOnMouseOver()
{
  clearTimeout(PDFExporterControl_HideMenuTimer);
}

function PDFExporterControl_handleMenuOnMouseOut()
{
  PDFExporterControl_HideMenuTimer = setTimeout("PDFExporterControl_HideMenu()", PDFExporterControl_HideMenuTimerLength);
}
var globalCommunityVisibleTab;
var globalCommunityListViewShowAddBtn;
var globalCommunityKnowdeChanged;
var globalCommunityTabLoaded;
var globalCommunityContainerId;

function LoadCommunityTab(_mode, _extraRepopArgs)
{   
  //changes the tab mode and loads the content

  // clear the new tab first so it looks tidy while the callback's happening
  KGCommunityTabControl_ClearTab(_mode);

  // switch to list view, user or iframe tab
  KGCommunityTabControl_SwitchTab(_mode, true);
  
  // repopulate the selected tab
  KGCommunityTabControl_RepopulateCurrentTab(_extraRepopArgs);
}

function LoadCommunityTabPageLoad(_addLink)
{
  LoadCommunityTab('ListView');
  ChangeTabToolStrip('communities');
  DoExpandMapViewPane('split');
  if (_addLink)
    window.setTimeout('OpenKGAddCommunityLinkControl()');
}

function KGCommunityTabControl_ClearTab(_mode)
{
  switch (_mode)
  {
    case "ListView":
      KGCommunityTabControl_ResetToLoading(KGCommunityTabControl_GetComCtlId());
      break;
    case "User":
      KGCommunityTabControl_ResetToLoading(KGCommunityTabControl_GetMemberCtlId());
      break;
    case "Iframe":
      KGCommunityTabControl_SetIframeSrc("");
      break;
  }
}

function KGCommunityTabControl_ResetToLoading(_ctlId)
{
  var ctl = document.getElementById(_ctlId);
  if (ctl)
    ctl.innerHTML = "<table class=\"MapLoadingIcon\" ><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>"
}

function KGCommunityTabControl_SwitchTab_Wrapped(_mode, _isRepop, _listViewTabId, _userTabId, _iframeTabId)
{
  //changes the tab mode without loading any content
  //_isRepop should only be set to true when KGCommunityTabControl_RepopulateCurrentTab is going to be called
  //  i.e. from LoadCommunityTab
  
  SetCommunityTabButtons(_mode, globalCommunityVisibleTab, _isRepop); // call this BEFORE updating globalCommunityVisibleTab

  globalCommunityVisibleTab = _mode;
  // show the relevant tab and hide the other(s)
  var listViewTab = document.getElementById(_listViewTabId);
  var userTab = document.getElementById(_userTabId);
  var iframeTab = document.getElementById(_iframeTabId);
  
  switch (_mode)
  {
    case "ListView":
      listViewTab.style.display = "block";
      userTab.style.display = "none";
      iframeTab.style.display = "none";
      break;
    case "User":
      listViewTab.style.display = "none";
      userTab.style.display = "block";
      iframeTab.style.display = "none";
      break;
    case "Iframe":
      listViewTab.style.display = "none";
      userTab.style.display = "none";
      iframeTab.style.display = "block";
      break;  
  }
}

function SetCommunityTabButtons(_newTab, _oldTab, _isRepop)
{
  // Add Link button - show with the ListView
  // Show List button - show if new tab isn't ListView
  if (_newTab == "ListView") 
  {
    // if the ListView is going to repopulate, don't show the button until callback done
    //    because of the iframe logic it might switch to the iframe tab in callback done, then these buttons will change again quickly - looks odd
    if (!_isRepop) 
      KGCommunityTabControl_UpdateButtonsForListView(); // using a separate function here so it'll be exactly the same when it's called from callback done, just later
  }
  else // not showing the list view
  {
    KGCommunityTabControl_ShowHideAddLinkBtn(false);
    KGCommunityTabControl_ShowHideShowListBtn(true);
  }
  
  // Back to User button - show when we leave a user; hide when we show a user
  if (_newTab == "User") // hide the button when we're showing a user
    KGCommunityTabControl_ShowHideBackToUserBtn(false);
  else if (_oldTab == "User") // show the button when we leave a user page
    KGCommunityTabControl_ShowHideBackToUserBtn(true);
}

function KGCommunityTabControl_UpdateButtonsForListView()
{
  // are we in edit mode editing a new knowde
  var editingNewKnowde = m_bEditable && m_SelectedKnowdeEditing && m_IsEditFromNewKnowde;

  // hide the add link button if we are editing a new knowde
  if (editingNewKnowde)
    KGCommunityTabControl_ShowHideAddLinkBtn(false);
  else // otherwise do the usual check
    KGCommunityTabControl_ShowHideAddLinkBtn(globalCommunityListViewShowAddBtn);
  KGCommunityTabControl_ShowHideShowListBtn(false);
}
      
function KGCommunityTabControl_ShowHideAddLinkBtn(_show)
{
 ShowHideButton(_show, "KGToolStrip_AddLinkButton")
}

function KGCommunityTabControl_ShowHideBackToUserBtn(_show)
{
  ShowHideButton(_show, "KGToolStrip_BackToUser")
}

function KGCommunityTabControl_ShowHideShowListBtn(_show)
{
  ShowHideButton(_show, "KGToolStrip_ShowList")
}

function KGCommunityTabControl_ShowList()
{
  if (globalCommunityKnowdeChanged)
    LoadCommunityTab("ListView"); // do need to repopulate it - I'm not sure we can get to here atm
  else
    KGCommunityTabControl_SwitchTab("ListView"); // don't need to repopulate it
}

function KGCommunityTabControl_RepopulateCurrentTab(_extraRepopArgs)
{
  
  var whatId = '';
  try
  {
    whatId = GetGlobalHighlightedWhatId();
  }
  catch(e)
  {
  }
	  
  // callback to inner control
  switch (globalCommunityVisibleTab)
  {
    case "ListView":
      if((window.globalLastSelectedKnowde && globalLastSelectedKnowde != null && globalLastSelectedKnowde != "undefined")
      || whatId != '')
	    {
	      var knowdeID = whatId;
				if(knowdeID == '')
				  knowdeID = returnKnowdeID(globalLastSelectedKnowde)
		    SetSessionProperty('CurrentKnowdeIDForTab', knowdeID); // could pass this in and set it during the callback for performance, but I think the CommunityLinkControl needs it aswell so it might get set too late
	    }
      var args = "Action=Load";
      if (_extraRepopArgs)
        args += "|" + _extraRepopArgs;
      KGCommunityControl_CallbackTrigger(args);    
      break;
    case "User":
      var args = "Action=Load"
      if (_extraRepopArgs)
        args += "|" + _extraRepopArgs;
      Com_KGMemberControl_CallbackTrigger(args);
      break;
    case "Iframe":
      // _extraRepopArgs holds the new src for the iframe
      // on a timeout to give the 'clear' chance to happen before loading the new page as loading the new page isn't very fast
      setTimeout("KGCommunityTabControl_SetIframeSrc('" + _extraRepopArgs + "')", 10);
      break;
  }
  globalCommunityTabLoaded = true;
}
  
function KGCommunityControl_CallbackError(_args, _context)
{
  var alertMessage = "The KGCommunityControl encountered an error. \n\n" + _args;
  alert(alertMessage);
}

function KGCommunityControl_CallbackDone(_args, _context)
{
  // check for exceptions
  if (_args.indexOf("Exception") == 0 || _args.length == 0)
  {
    KGCommunityControl_CallbackError(_args, _context);
    return;
    // looking for indexOf == 0 instead of > -1 incase it's genuine html that happens to contain 'Exception' in there
    // e.g. a user called "... Exceptional ..." 
  }

  // get the parameters
  var argsSplit = _args.split('[@|@]');
  var json = argsSplit[0];
  
  
  var retMsg = eval( '(' + json + ')' );
  
  if (retMsg.KeepIframe)
  { // keep the iframe instead of loading the contents
    if (retMsg.IframeUrl != "")
    {
      // this will clear the tab before loading in the new src, so it's tidier incase it's slow
      KGCommunityTabControl_SetIframeSrc("");
      setTimeout("KGCommunityTabControl_SetIframeSrc('" + retMsg.IframeUrl + "')", 10);
    }
    
    KGCommunityTabControl_SwitchTab("Iframe");
  }
  else
  { // don't keep the iframe; do load the contents
    var javascripts = argsSplit[1];
    var htmlContent = argsSplit[2];
    
    var holderId = retMsg.HolderId;

    var holder = document.getElementById(holderId);
    if (!holder)
    {
      KGCommunityControl_CallbackError('The holder doesn\'t exist ' + holderId);
      return;
    }
    
    // fill the control
    SetOuterHtml(holder, htmlContent);
    globalCommunityKnowdeChanged = false;
    globalCommunityContainerId = retMsg.ContainerId;
    
    // show the "ComingSoon" message if required
    if (retMsg.ShowComingSoon)
      KGCommunityControl_ShowHideComingSoon(true, retMsg.ContainerId, retMsg.ComingSoonCtrId);
    if(retMsg.ShowIframeMsg)
      KGCommunityControl_ShowMessageBox('NoLinkedConversation', 150, 10);
    
    // eval any javascripts
    if (javascripts)
      eval(javascripts);
    
    globalCommunityListViewShowAddBtn = retMsg.ShowAddLinkBtn;
    // update the buttons
    KGCommunityTabControl_UpdateButtonsForListView();
  }
}

function KGCommunityTabControl_SetIframeSrc(_src)
{
  var iframe = KGCommunityTabControl_GetIframe();
  iframe.src = _src;
}

function KGCommunityTabControl_GetIframe()
{
  var iframeId = KGCommunityTabControl_GetIframeId();
  return document.getElementById(iframeId);
}

function KGCommunityControl_ShowHideComingSoon(_show, _containerId, _comingSoonCtrId)
{
  var container = document.getElementById(_containerId);
  var comingSoonCtr = document.getElementById(_comingSoonCtrId);
  
  if (_show)
  {
    // the container needs to be wider to fit them both in
    container.className = "KGCommunityControl_ContainerWide";
    container.childNodes[0].style.position = 'absolute';
    comingSoonCtr.style.display = ""; // clear display none to display the message
  }
  else
  {
    container.className = "KGCommunityControl_Container";
    container.childNodes[0].style.position = 'relative';
    comingSoonCtr.style.display = "none";
  }
}

function KGCommunityControl_CommunityLinkRatingOnClick(_star, _kclID)
{
  // get the KGRatingControl to handle the star click
  var starRating = KGRatingControl_StarClicked(_star);
  
  // callback to save the setting
  var args = "Action=RateCommunityLink";
  args += "|KCLID=" + _kclID;
  args += "|Rating=" + starRating;
  KGCommunityControl_CallbackTrigger(args);
}

function setCommunityTabMode()
{ // knowde changed either from knowde click or new map
  globalCommunityKnowdeChanged = true; // will need to reload the list view for the new knowde
}

function KGCommunityTabControl_Activate()
{
  // could be a knowde click or a tab click
  // might need to reload some content, might not

  if (globalCommunityKnowdeChanged) // knowde changed since the last repop
  {
    if (globalCommunityVisibleTab == "Iframe")
    {
      var iframe = KGCommunityTabControl_GetIframe();
      var extraRepopArgs = "IsIframe=true|Url=" + iframe.src; // urls shouldn't contain pipes - it's caught in the add link validation
      LoadCommunityTab("ListView", extraRepopArgs); // mode depends whether conversation from that domain is linked to new knowde
      // assume it's the ListView and switch back to the iframe later if not
      //    means we can do it all in one callback to the CommunityControl, because if we need an iframe we just send back the src; if we need the ListView we can get the ListView same as usual
      // tiny thing to watch - the ListView tab will get cleared and then if it's an iframe not repopulated
      //    but globalCommunityKnowdeChanged isn't updated in that case so we still know that tab needs repopulating
    }
    else // not showing iframe - default to list view, unless it was on an iframe conversation
      LoadCommunityTab("ListView");
  }
  else // knowde hasn't changed
  {
    if (globalCommunityTabLoaded) // we already have something to show, so just leave it
      return;
    else 
      LoadCommunityTab("ListView"); // load a list view
  }
}
function KGCommunityControl_OpenLinkInNewWindow(e, _url, _divClientID, _newWindowAtts)
{
  e = e || window.event;
  //debugger;
  
  window.open(_url, _divClientID + '_linkWindow', _newWindowAtts);
  KGCommunityControl_ShowMessageBox('LinkInNewWindow', 120, e.y - 70);
}

function KGCommunityControl_ShowMessageBox(_type, _posX, _posY)
{
  if(_type != 'LinkInNewWindow' && _type != 'NoLinkedConversation')
    return;
    
  // check cookie setting
  if(WM_readCookie('Message_' + _type) == "off")
    return;
    
  var container = document.getElementById(globalCommunityContainerId);
  if(container != null && container.childNodes.length == 3)
  {
    var msgBoxDiv = container.childNodes[2];
    if(msgBoxDiv != null)
    {
      var userMsg = '';
      if(_type == 'LinkInNewWindow')
        userMsg += 'This site has been opened in a new browser. The linked site has not yet implemented the required technology to be embedded in our site.';
      else if(_type == 'NoLinkedConversation')
        userMsg += 'No linked conversations for the current domain have been found. You are therefore viewing the list view for this Knowde.';
      userMsg += '<br /><br />';
      userMsg += '<div style="width:100%;"><span style="float: left; margin-top: 3px; color: grey;"><INPUT id="MessageCheckBox_' + _type + '" type="checkbox" />Do not show this message again</span><input type="button" class="CommunityLinkControlBtn" value="OK" onclick="KGCommunityControl_HideMessageBox(\''+ _type + '\');"/></div>';
          
      msgBoxDiv.innerHTML = userMsg;
      
      // position the box
      if(_posX < 0)
        _posX = 5;
      if(_posY < 0)
        _posY = 5;        
        
      // check TCC scroll postiion
      var tcc = document.getElementById('TCC');
      if(tcc != null && tcc.parentNode != null)
      {
        var scrollTop = tcc.parentNode.scrollTop;
        if(_posY < scrollTop)
          _posY = scrollTop;
      }

      msgBoxDiv.style.left = _posX + 'px';
      msgBoxDiv.style.top = _posY + 'px';
      msgBoxDiv.style.position = 'absolute';
      msgBoxDiv.style.display = 'block';
    }
  }
  
}

function KGCommunityControl_HideMessageBox(_type)
{
  var cb = document.getElementById('MessageCheckBox_' + _type);
  if(cb != null && cb.checked == true)
  {
    WM_setCookie('Message_' + _type,'off', m_helpCookieExpiration); // turn it off, cookie expire in 7 days
  }
  
  var container = document.getElementById(globalCommunityContainerId);
  if(container != null && container.childNodes.length == 3)
  {
    var msgBoxDiv = container.childNodes[2];
    if(msgBoxDiv != null)
    {
      msgBoxDiv.style.display = 'none';
      msgBoxDiv.innerHTML = '';
    }
  }
}




// KGApplicationControl JScript File
var m_KGApplicationControl_appID = 0;
var m_KGApplicationControl_appKGID = 0;
var m_KGApplicationControl_appKGExecutionType = 'Native';
var m_KGApplicationControl_appKGDragDrop = 'false';

var m_applicationFrameLoadingDivTimeOut;
var m_applicationFrameCallbackStatus;
var m_applicationControlOpen = false;
var m_applicationKGID = 0;
var m_applicationKGGroupID = -1;
var m_dragBox;
var m_appForceOpen = false; // set to true to keep the application window open over page redirects etc.

function KGApplicationControl_CallbackDone_Wrapped(_args, _context, _controlDivID)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
	// set the callback status
	m_applicationFrameCallbackStatus = 'done';
	// hide the loading div
	HideOrShowApplicationControlLoadingDiv(false);
  
	if (_args.indexOf("Exception") == -1)
	{
		// 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 + ')');
    
		if (retMessage.Action != "Unload")
		{
			// set overlay div size and position
			applicationBox = document.getElementById(_controlDivID);
			applicationBox.style.top = screen.height/4;//"30%"; //screen.height/3;
			applicationBox.style.height = screen.height/2;
			applicationBox.style.left = "15%";
			applicationBox.style.width = "900px";
    	
			OpenApplicationControl();
      
			var ApplicationFrame = document.getElementById("ApplicationFrame");
      
      switch (retMessage.Action)
      {
        case "Load":
          ApplicationFrame.src = retMessage.InterfaceURL;
          // reset the global var once load complete
          m_KGApplicationControl_appID = 0;
          m_KGApplicationControl_appKGID = 0;
          m_applicationKGID = retMessage.AppKGID;
          m_applicationKGGroupID = retMessage.AppKGGroupID;
          switch (retMessage.ExecutionType)
          {
            case "Native":
              m_appForceOpen = false;
              break;
            case "KGContextual":
              m_appForceOpen = true;
              break;
          }
          if (retMessage.MaximiseOnLoad)
            MaximiseKGApplicationControl();

          if (typeof loadAppKnowde == "object" && loadAppKnowde != null)
          {
            setTimeout((function(){ApplicationContextChanged(loadAppKnowde.kid, loadAppKnowde.kgid);}),100);
          }
          break;
        case "LoadAlert":
          ApplicationFrame.src = retMessage.InterfaceURL;
          ApplicationFrame.className = "applicationIFrame";
          ApplicationFrame.style.width = '100%';
          ApplicationFrame.style.height = '100%';
          // reset the global var once load complete
          m_KGApplicationControl_appID = 0;
          m_KGApplicationControl_appKGID = 0;
          m_applicationKGID = 0;
          m_applicationKGGroupID = 0;
          m_appForceOpen = false;
          
          if (retMessage.MaximiseOnLoad)
            MaximiseKGApplicationControl();

          break;
        case "ContextChanged":
          ApplicationFrame.src = retMessage.InterfaceURL;
          if (typeof loadAppKnowde == "object" && loadAppKnowde != null && retMessage.MaximiseOnLoad)
          {
            MaximiseKGApplicationControl();
		    loadAppKnowde = null;
          }
          break;
      }
    }
  }
  else
  {
    alert(_args);
  }
}

function KGApplicationControl_CallbackError(_args, _context)
{
  alert(_args);
}

function HideOrShowApplicationControlLoadingDiv_Wrapped(_divId, _show, _message)
{
  if(m_applicationFrameLoadingDivTimeOut != null)
  {
    clearTimeout(m_applicationFrameLoadingDivTimeOut);
    m_applicationFrameLoadingDivTimeOut = null;
  }
  
  var div = null; 

  if(_divId != null && _divId != '')
    div = document.getElementById(_divId);
  if(_message == null)
    _message = 'Loading...';

  if(_show != null && _show == true && m_applicationFrameCallbackStatus != 'trigger')
  {
    // callback done has finished before the trigger time out to show the loading div, 
    // so don't need to show it anymore
    return;
  }
   
  if (div != null)
  {
    if(_show != null && _show == true && div.style.display != 'block')
    {
      var top = 60;
      var left = 172;
      
      // calculate the position based on the textView region
      var parentDiv = div.parentNode;
      
      //if(parentDiv.clientHeight != null && parentDiv.clientHeight != '' && parentDiv.clientHeight > 60)
        //top = 60;
          
      if(parentDiv.clientWidth != null && parentDiv.clientWidth != '' && parentDiv.clientWidth > 0)
        left = parentDiv.clientWidth/2 - 60;
        
      if(left <= 0)
        left = 0;
  
      div.innerHTML = "<img src='Images/LoadingBar.gif' width='21px' height='21px'/>&nbsp;" + _message;
      div.style.top = top + 'px';
      div.style.left = left + 'px';
      div.style.display = 'block';
    }
    else if(div.style.display != 'none')
    {
      div.style.display = 'none';
      div.innerHTML = '';
      div.style.top = '0px';
      div.style.left = '0px';
    }
  }
}

function OpenApplicationControl_wrapped(_hideDockButton, _imgDockInPageID)
{
  var docButton = document.getElementById(_imgDockInPageID);
  if (docButton != null)
  {
    if (_hideDockButton)
    {
      docButton.style.display = "none";
      globalHideDockButton = true;
    }
    else
    {
      docButton.style.display = "";
      globalHideDockButton = false;
    }
  }
  
  // make sure the docked window is close then the help control popup
  //if(document.getElementById('DockedApplicationWindowContainer') != null)
    //CloseDockedKGApplicationControl('ApplicationFrame');
  
  ShowKGApplicationControl();
  m_applicationControlOpen = true;
  // enable drag and drop KG into appWindow
  
  setupKGDragDropBox();
}

function KGApplicationControl_CallbackTrigger_Wrapped(_args, _callbackScript)
{

  //var MapHelpBox = document.getElementById("KGHelpControlID1");
  //MapHelpBox.title = "Associated Text";
  
  //var imgDockInPage = document.getElementById(_imgDockInPageID);
  //if (imgDockInPage.style.display == "none")
    //imgDockInPage.style.display = "";
  var args;
  // Construct the callback arguments
  if(_args != null)
  { 
    args = _args;
    
    if(args.length > 0)
    {
      if(m_applicationFrameLoadingDivTimeOut != null)
      {
        clearTimeout(m_applicationFrameLoadingDivTimeOut);
        m_applicationFrameLoadingDivTimeOut = null;
      }
      
      if (m_applicationControlOpen)
      {
        // Make sure we clear the contents of the application window
        ClearApplicationFrame();
        // show the loading div
        m_applicationFrameLoadingDivTimeOut = window.setTimeout("HideOrShowApplicationControlLoadingDiv(true, 'Loading...')",10);
      }
      
      // the current status of the callback
      m_applicationFrameCallbackStatus = 'trigger';
      // trigger the callback
      eval(_callbackScript);
    }
  }
}

function CloseApplicationControl()
{  
	if(document.getElementById("GreyDiv") != null)
	{
	    purge(document.getElementById("GreyDiv"));
		document.getElementById("Form1").removeChild(document.getElementById("GreyDiv"));
		document.getElementById("m_cookieDiv").className = "m_cookieDivHidden";
		document.getElementById("miniGlobe").className = "miniGlobe";
	}
  var ApplicationBox = document.getElementById("KGApplicationControlID1");
  
  // reset the tooltip
  ApplicationBox.title = "Associated Text";
  // hide textview view option div
  //if(window.HideOrShowTextViewOptionDiv)
    //HideOrShowTextViewOptionDiv(false);
  
  // reset the view mode
  //if(window.SwitchTextViewViewMode)
    //SwitchTextViewViewMode("Single");
  
  ClearApplicationFrame()
  m_applicationControlOpen = false;
  m_appForceOpen = false;
  HideKGApplicationControl();
  ApplicationUnload();
  
  // if in profile page, refresh the alerting control
  if(window.location.href.toLowerCase().indexOf('options.aspx') > -1)
  {
    var args='action=load';
    KGAppAlertingControl_CallbackTrigger(args);
  }
  
}

function ClearApplicationFrame()
{
  
  var ApplicationFrame = document.getElementById("ApplicationFrame");
  if (ApplicationFrame.src != null && ApplicationFrame.src != "")
  {
    var parent = ApplicationFrame.parentNode;
    
    var newApplicationFrame = document.createElement('iframe');
    newApplicationFrame.id = "ApplicationFrame";
    newApplicationFrame.className = "applicationIFrame";
    newApplicationFrame.frameBorder = 0;
      
    purge(ApplicationFrame);  
    parent.removeChild(ApplicationFrame);
    InsertAdjacentElement(parent,"beforeend", newApplicationFrame);
  }
  else
  {
    // Make sure we clear the contents of the document window
    ApplicationFrame.contentWindow.document.write("");
    ApplicationFrame.contentWindow.document.close();
  }
}

function LoadApplicationControl(_reload, _checkExistingOpenApp)
{
  if (window.KGApplicationControl_CallbackTrigger)
  {
		if(_reload == "true")
		{
		  if(_checkExistingOpenApp == "true")
		  { 
		    // for auto open app after go to other pages and back to home page by click a category
		    if(window.location.href.toLowerCase().indexOf('home.aspx?category=') != -1 && m_KGApplicationControl_appKGDragDrop == 'false')
		    {
		      if(!m_applicationControlOpen && m_KGApplicationControl_appID != 0 && m_KGApplicationControl_appKGExecutionType == 'KGContextual')
		      {
		        var args = 'Action=Load|AppID=' + m_KGApplicationControl_appID + '|AppKGID=' + m_KGApplicationControl_appKGID;
				    KGApplicationControl_CallbackTrigger(args);
		      }
		    }
		  }
		  else
		  {
			  if (m_KGApplicationControl_appID != 0)
			  {
				  var args = 'Action=Load|AppID=' + m_KGApplicationControl_appID + '|AppKGID=' + m_KGApplicationControl_appKGID;
				  KGApplicationControl_CallbackTrigger(args);
			  }
			  else if (m_applicationControlOpen)
			  {
				  CloseApplicationControl();
			  }
			}
    }
  }
  else
  {
    setTimeout("LoadApplicationControl('" + _reload + "', '" + _checkExistingOpenApp + "')", 100);
  }
}

function LoadApplicationControlAlert()
{
  if (window.KGApplicationControl_CallbackTrigger && g_exMapCtl)
  {
			if (m_KGApplicationControl_appID != 0)
			{
				var args = 'Action=LoadAlert|AppID=' + m_KGApplicationControl_appID + '|AppUrl=' + g_exMapCtl.url.replace(new RegExp('=',"g"),'[eq]');
				KGApplicationControl_CallbackTrigger(args);
			}
			else if (m_applicationControlOpen)
			{
				CloseApplicationControl();
			}
  }
}


var global_appKgID = "";
function ApplicationContextChanged(_knowdeID, _appKgID, _contextKGID)
{
//debugger;
	if(global_appKgID == "")
		global_appKgID = _appKgID;
	if(global_appKgID == _appKgID)
	{
		var args = 'Action=ContextChanged'
		if (_knowdeID != null)
			args += '|ClientKnowdeID=' + _knowdeID;
		if (_appKgID != null)
			args += '|AppKGID=' + _appKgID;
		if (_contextKGID != null)
			args += '|ContextKGID=' + _contextKGID;
		KGApplicationControl_CallbackTrigger(args);
  }
}

function ApplicationUnload()
{
	global_appKgID = "";
  var args = 'Action=Unload';
  KGApplicationControl_CallbackTrigger(args);
}

// DragDropBox class
function DragDropBox(_box)
{
  // setup the drag box for dragging
  this.startDrag = function()
  {
    this.CurrentlyDragging = true;
    box.style.display = '';
  }
  
  // hide the drag box
  this.stopDrag = function()
  {
    this.CurrentlyDragging = false;
    box.style.display = 'none';
  }
  
  var box = _box;
  box.style.position = 'absolute';
  this.stopDrag();
  
  // return box id
  this.getId = function()
  {
    return box.id;
  }
  
  this.getBox = function()
  {
    return box;
  }
  
  // set box position
  this.setPosition = function(_x, _y)
  {
    if(box.childNodes.length > 0 && box.childNodes[0].tagName == 'group')
    {
      box.style.left = _x - box.childNodes[0].style.width.replace('px','')/2 + "px";
      box.style.top = _y - box.childNodes[0].style.height.replace('px','')/2 + "px";
    }
    else
    {
      box.style.left = _x - box.offsetWidth/2 + "px";
      box.style.top = _y - box.offsetHeight/2 + "px";
    }
  }
  
  // set the box size
  this.setSize = function(_height, _width)
  {
    box.style.height = _height + "px";
    box.style.width = _width + "px";
  }
  
  // insert the box into the _parent
  this.insertInto = function(_parent)
  {
    _parent.appendChild(box);
  }
  
  // remove the element from the DOM
  this.remove = function()
  {
    box.parentNode.removeChild(box);
  }
  
  // store the Target position and size
  this.setTarget = function(_target)
  {
    this.TargetTop = GetPixelTop(_target);
    this.TargetLeft = GetPixelLeft(_target);
    this.TargetWidth = _target.offsetWidth;
    this.TargetHeight = _target.offsetHeight;
  }
  
  // check to see if the coordinates _x, _y are within the target
  this.targetHit = function(_x, _y)
  {
    if (_x > this.TargetLeft && _x < this.TargetLeft + this.TargetWidth
         && _y > this.TargetTop && _y < this.TargetTop + this.TargetHeight)
      return true;
    else
      return false;
  }
  return true;
}

function setupKGDragDropBox()
{
  var kgDragDropBox = document.getElementById('KGDragDropBox');
  if(kgDragDropBox != null)
  {
    // remove the old one
    kgDragDropBox.parentNode.removeChild(kgDragDropBox);
  }
  kgDragDropBox = document.createElement('div');
  kgDragDropBox.id = 'KGDragDropBox';
  kgDragDropBox.className = 'docList_KGIcon';

  m_dragBox = new DragDropBox(kgDragDropBox);
  
  // insert the dragbox as a sibling of the ApplicationBox
  var ApplicationBox = document.getElementById("KGApplicationControlID1");
  m_dragBox.insertInto(ApplicationBox.parentNode);
  // set the size and position of the dragBox
//  var width = 100;
//  var height = 100;
//  m_dragBox.setSize(height, width);
}

function KGDragStart(e, _kgID, _knowdeID, _content)
{
  if (m_dragBox != null)
  {
    m_dragBox.KGID = _kgID;
    m_dragBox.KndID = _knowdeID;
    var box = m_dragBox.getBox();
    
    // set appearance
    if(_knowdeID == null)
    {
      box.className = 'docList_KGIcon';
    }else
    {
      box.className = '';
      if(_content != null)
      {
        box.innerHTML = _content;
      }
    }

    m_dragBox.startDrag();
    
    // set the dragbox target
    var ApplicationBox = document.getElementById("KGApplicationControlID1");
    m_dragBox.setTarget(ApplicationBox);
    
    e = e || window.event;
    var x, y;
    
    // Get cursor position with respect to the page.
    if (window.scrollX)
    {
      x = e.clientX + window.scrollX;
      y = e.clientY + window.scrollY;
    }
    else
    {
      x = e.clientX + document.documentElement.scrollLeft
        + document.body.scrollLeft;
      y = e.clientY + document.documentElement.scrollTop
        + document.body.scrollTop;
    }
    
    // show thee drag box where the mouse was clicked
    m_dragBox.setPosition(x, y);
    dragStart(e, m_dragBox.getId());
  }
}

function KGDragCancel()
{
  m_dragBox.stopDrag();
}

function KGDragStop(e)
{
  //debugger;
  KGDragCancel();
  
    // empty drag box
    var box = m_dragBox.getBox();
    box.innerHTML = '';
  
  e = e || window.event;
  var x, y;
  
  // Get cursor position with respect to the page.
  if (window.scrollX)
  {
    x = e.clientX + window.scrollX;
    y = e.clientY + window.scrollY;
  }
  else
  {
    x = e.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = e.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  
  if (m_dragBox.targetHit(x, y))
  {
    // dragbox dropped on the app window.  Callback the app control
    var contextKGID = m_dragBox.KGID;
    var contextKndID = m_dragBox.KndID;
    
    var currentLocation = window.location.href;
    var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
    //if (currentPage.indexOf('home') > -1 || currentPage.length == 0)
    //{
      //ApplicationContextChanged('', '', contextKGID);
    //}
    //else
    //{
     var keys = 'ApplicationContextKGID';
	   var values = contextKGID;

      //SetSessionProperty('ApplicationContextKGID', contextKGID);
      if(contextKndID != null)
      {
        //SetSessionProperty('ApplicationContextKID', contextKndID);
        keys += '|ApplicationContextKID';
        values += '|' + contextKndID;
      }
      keys += '|ApplicationDragDropTriggerred|SelectedPersonalKGID|MapViewDisplayMode|KGTabbedWindowsControl1_SelectedTab|IndexedDocListMode|KGMapViewCollapsed|KGExpandMap|TriggerMapViewCallbackOnload';
      values += '|true|' + m_applicationKGID + '|KGMapView|Indexed Documents|IndexedDocuments|false|true|true';
      SetSessionProperty(keys, values, true);
      
      /*SetSessionProperty('ApplicationDragDropTriggerred', 'true');
      SetSessionProperty('SelectedPersonalKGID', m_applicationKGID);
      SetSessionProperty('MapViewDisplayMode', "KGMapView");
      SetSessionProperty('KGTabbedWindowsControl1_SelectedTab', 'Indexed Documents');
      //SetSessionProperty('SelectedAuthorID', selectedKgAuthorId);
      //SetSessionProperty('KGButtonToolbar_AuthorID', selectedKgAuthorId);
      SetSessionProperty('IndexedDocListMode', 'IndexedDocuments');
      SetSessionProperty('KGMapViewCollapsed',false);
      SetSessionProperty('KGExpandMap',true); //flip the splitter to show the map in button toolbar callback done (KGMapViewCollapsed is removed in aspx.cs)
      SetSessionProperty('TriggerMapViewCallbackOnload', "true");*/

      var currentLocation = window.location.href;
      var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
      if(m_applicationKGGroupID > 0)
	      window.location = hostURL + 'Home.aspx?category=' + m_applicationKGGroupID;
	    else
	      window.location = hostURL + 'Home.aspx';
    //}
    
  }
  
}

var appBoxWidth;
var appBoxHeight;
var appBoxTop;
var appBoxLeft;
  
function MaximiseKGApplicationControl_Wrapped(_appBoxID, _maximiseBtnId)
{
//debugger;
// get the help box
  var appBox = document.getElementById(_appBoxID);
  
  // store the help box'x current width, height and positioning for a 'restore'
  appBoxWidth = appBox.style.width;
  appBoxHeight = appBox.style.height;
  appBoxTop = appBox.style.top;
  appBoxLeft = appBox.style.left;
  
  // Set the help windows new properties
  appBox.style.width = document.body.clientWidth;
  appBox.style.height = document.body.clientHeight;
  appBox.style.top = "0";
  appBox.style.left = "0";
  
  // change image and onclick handler
  document.getElementById(_maximiseBtnId).className = "RestoreButtonImage";
  document.getElementById(_maximiseBtnId).onclick = function(){RestoreKGApplicationControl(_appBoxID, _maximiseBtnId)}; 
}

function RestoreKGApplicationControl(_appBoxID, _restoreBtnId)
{
//debugger;
  var appBox = document.getElementById(_appBoxID);
  
  // reset the old size and positioning
  appBox.style.top = appBoxTop;
  appBox.style.left = appBoxLeft;
  appBox.style.width = appBoxWidth;
  appBox.style.height = appBoxHeight;
  
  // change image and onclick handler
  document.getElementById(_restoreBtnId).className = "MaximiseButtonImage";
  document.getElementById(_restoreBtnId).onclick = function(){MaximiseKGApplicationControl()}; 
}

var g_exMapCtl; // the control for show/hide, also stores some properties

// called when the user first clicks on a KG
// should only be called if the KG has at least one app that the user can execute
// but there are checks later on to make sure
function KGExecuteMapControl_ShowMenu(e, _mode, _strApps, _kgid, _authorID, _conceptName, _knowdeId, _url, _groupID)
{
  //debugger;
  if (!g_exMapCtl)
  {
    var controlId = KGExecuteMapControl_GetControlDivId();
    g_exMapCtl = document.getElementById(controlId);
  }
  
  if (g_exMapCtl)
  {
    // set some properties on the control so we can access them in the onclick methods
    g_exMapCtl.mode = _mode;
    g_exMapCtl.strApps = _strApps;
    g_exMapCtl.kgid = _kgid;
    g_exMapCtl.authorID = _authorID;
    g_exMapCtl.knowdeId = _knowdeId; // may be null, if so still set it here and we can get null back later
    g_exMapCtl.conceptName = _conceptName; // may be null, if so still set it here and we can get null back later
    g_exMapCtl.url = _url;
    g_exMapCtl.groupID = _groupID;
    
    // position and show the control
    //KGExecuteMapControl_PositionMenu(e);  //NB - there's a bug here at the moment when you try to go to a knowde via a url and it doesn't pass in the event.  But we're no longer showing this control so I've just commented out the call for the time being.
    //g_exMapCtl.style.display = 'block';
    // don't show the menu, directly execute it
    window.setTimeout('KGExecuteMapControl_Execute()', 5);
    
    // turn off tour bubble
    var toggleElement = document.getElementById('BubbleTourToggle');
    if(toggleElement != null && toggleElement.className == 'TourBubbleOn')
    {
        toggleElement.className = "TourBubbleOff";
				document.getElementById("KGBubbleControl1_BubbleVisibilityContainer").style.display = "none";
				WM_setCookie('HelpBubble','hide', m_helpCookieExpiration);
				WM_setCookie('TourBubble','off', m_helpCookieExpiration);
				ProceedWithTour();
		}
  }
  
  if(e != null)
    CancelBubble(e);
}

// position with cursor from event object passed in
function KGExecuteMapControl_PositionMenu(e)
{
  if (g_exMapCtl)
  {
    var x = e.clientX - 10;
    var y = e.clientY - 10;
      
    //make sure the control isn't off the page 
    var maxX = document.body.clientWidth - g_exMapCtl.clientWidth - 2;  
    maxX = Math.max(maxX, 0); // maxX shouldn't be less than zero
    x = Math.min(x, maxX); // x shouldn't be greater than maxX
    
    g_exMapCtl.style.left = x + 'px';
    g_exMapCtl.style.top = y + 'px';
  }
}

// hide the menu and clear its properties
// shouldn't need to clear it's properties because they're reset in show, but it can't hurt
function KGExecuteMapControl_HideMenu()
{
  if (g_exMapCtl)
  {
    g_exMapCtl.style.display = 'none';
    
    g_exMapCtl.mode = '';
    g_exMapCtl.strApps = '';
    g_exMapCtl.kgid = '';
    g_exMapCtl.authorID = '';
    g_exMapCtl.knowdeId = ''; 
    g_exMapCtl.conceptName = '';
    g_exMapCtl.groupID = '';
  }
}

var KGExecuteMapControl_HideMenuTimer;
function KGExecuteMapControl_MouseOut()
{
  KGExecuteMapControl_HideMenuTimer = setTimeout("KGExecuteMapControl_HideMenu()", 500);
}

function KGExecuteMapControl_MouseOver() // cancel the hide so the menu doesn't disappear
{
  clearTimeout(KGExecuteMapControl_HideMenuTimer);
}

// user chose to learn the KG, so load the map
function KGExecuteMapControl_Learn()
{
  //if (confirm('Do you want to view the hyperknowledge map?'))
  {
    if (g_exMapCtl)
      KGExecuteMapControl_LoadKG(true, g_exMapCtl.mode, g_exMapCtl.authorID, g_exMapCtl.kgid, g_exMapCtl.knowdeId, g_exMapCtl.conceptName, g_exMapCtl.groupID);
  }
  KGExecuteMapControl_HideMenu();
}

// user chose to execute the KG, set the ApplicationID session property (or choose one from multiple?) then load the KG
function KGExecuteMapControl_Execute()
{
  if (g_exMapCtl)
  {
    var strApps = g_exMapCtl.strApps;
    if (!strApps)
      KGExecuteMapControl_HandleNoApp();
    else 
    {
      if (strApps.indexOf('@@') == -1) // only one app
      {
        var app = KGExecuteMapControl_GetApp(strApps, g_exMapCtl.mode);
        if (app)
          KGExecuteMapControl_StartExecuteApp(app);
        else
          KGExecuteMapControl_HandleNoApp();
      }
      else // seems there are multiple apps
      {
        var arrStrApps = strApps.split('@@');
        var arrApps = new Array();
        
        var count = 0;
        for (var j in arrStrApps)
        {
          var app = KGExecuteMapControl_GetApp(arrStrApps[j], g_exMapCtl.mode);
          if (app)
          {
            arrApps[count] = app;
            count ++;
          }
        }
        
        if (count == 0) // double check count incase string was in the wrong format
          KGExecuteMapControl_HandleNoApp();
        else if (count == 1)
          KGExecuteMapControl_StartExecuteApp(arrApps[0]);
        else
          KGExecuteMapControl_HandleMultipleApps(arrApps);
      }
    }
  }
  KGExecuteMapControl_HideMenu();
}

// returns an object to represent the application from a string of "id|name"
// app.Id and app.Name
// returns null if there's a problem e.g. string in wrong format
function KGExecuteMapControl_GetApp(_strApp, _mode)
{
  var app = new Object();
  if (_strApp)
  {
    var posPipe = _strApp.indexOf('|');
    if (posPipe > -1)
    {
       app.Id = _strApp.substring(0,posPipe);
       app.Name = _strApp.substring(posPipe + 1);
    }else if(_mode != null && _mode == 'MyAlert')
    {
      app.Id = _strApp;
    }
  }
  
  if (app && app.Id)
    return app;
}

// somehow the ExecuteMapControl has shown without an appplication, so there's probably a bug
function KGExecuteMapControl_HandleNoApp()
{
  //if (confirm('No application available. Do you want to view the Knowledge Gene?'))
  //    just load the KG - the message doesn't make sense if you don't see the control
  {
    if (g_exMapCtl)
      KGExecuteMapControl_LoadKG(true, g_exMapCtl.mode, g_exMapCtl.authorID, g_exMapCtl.kgid, g_exMapCtl.knowdeId, g_exMapCtl.conceptName, g_exMapCtl.groupID);
  }
}
    
function KGExecuteMapControl_StartExecuteApp(_app)
{
  if (_app)
  {
    // set the AppID
    if (window.m_KGApplicationControl_appID != null)
      m_KGApplicationControl_appID = _app.Id;
    SetSessionProperty('ApplicationID', _app.Id);
    //alert('Execute Application \r\nappId = ' + _app.Id + '\r\nappName = ' + _app.Name);
    //if (confirm('Do you want to view the hyperknowledge map?'))
    {
      if (g_exMapCtl)
      {
        if(g_exMapCtl.mode == 'MyAlert')
        {
          LoadApplicationControlAlert();
        }
        else
        {
          m_KGApplicationControl_appKGID = g_exMapCtl.kgid;
          SetSessionProperty('ApplicationKGID', g_exMapCtl.kgid);
          // Production site: replace -99999 with the actual DashboardAppID to boost performance by not loading the map
          if((m_KGApplicationControl_appID == -99999 && g_exMapCtl.mode == 'Category' && window.location.href.toLowerCase().indexOf('home.aspx?category=') != -1) || (window.location.href.toLowerCase().indexOf('apphome.aspx') != -1))
            LoadApplicationControl('true');
          else
            KGExecuteMapControl_LoadKG(false, g_exMapCtl.mode, g_exMapCtl.authorID, g_exMapCtl.kgid, g_exMapCtl.knowdeId, g_exMapCtl.conceptName, g_exMapCtl.groupID);
        }
      }
    }
  }
  else
    KGExecuteMapControl_HandleNoApp();
}

// this needs coding
function KGExecuteMapControl_HandleMultipleApps(_arrApps)
{
  var message = "There are multiple apps: ";
  
  var app;   
  for (var j in _arrApps)
  {
    app = _arrApps[j];
    if (app)
      message += '\r\nappId = ' + app.Id + ';  appName = ' + app.Name;
  }
  //alert(message);
  
  //if (confirm('Do you want to view the hyperknowledge map?'))
  {
    if (g_exMapCtl)
      KGExecuteMapControl_LoadKG(false, g_exMapCtl.mode, g_exMapCtl.authorID, g_exMapCtl.kgid, g_exMapCtl.knowdeId, g_exMapCtl.conceptName, g_exMapCtl.groupID);
  }
}
                
function KGExecuteMapControl_Highlight(_cell)
{
  if (_cell)
    _cell.style.background = '#DDDDDD';
}

function KGExecuteMapControl_UnHighlight(_cell)
{
  if (_cell)
    _cell.style.background = '';
}

// continue with the KG load code that used to be called directly from the KGClick
// allowText boolean = whether to allow call to ShowTextView - not for execute
// knowdeId and conceptName might be null
// authorId could be personId or userKey depending on mode
function KGExecuteMapControl_LoadKG(_allowText, _mode, _authorID, _kgid, _knowdeId, _conceptName, _groupID)
{
  switch (_mode)
  {
    case "MyHK":
    case "Category":
      KGTabbedWindowsControl_MyHK_KGSelected(null, _authorID, _kgid, false, _groupID);
      break;
    case "IndexedDocs":
      RelatedConcept = _conceptName; 
      KGTabbedWindowsControl_KGSelected(_knowdeId, _authorID, _kgid, false, false, _groupID);
      break;
    case "UOS": // User Object Summary Control = authored maps
      KGTabbedWindowsControl_MyHK_KGSelected(null, _authorID, _kgid, false, _groupID);
      break;
    case "MyKnowl": // MyKnowledgeControl = My Hyperknowledge on profile page
      KGTabbedWindowsControl_MyHK_KGSelected(null, _authorID, _kgid, false, _groupID);
      break;
    /*
    case "MyHK":
    case "Category":
    case "IndexedDocs":
      var link = document.getElementById(_kgid);
      if (link)
        location.href = link.href;
      break;
    // how to stop the text view from showing for execute?
    */
  }
}

function KGExecuteMapControl_LoadCurrentKG(_allowText, _authorID, _kgid)
{
  if(globalSplitterSetting == "split") // SplitView == true
  {
    // if the map isn't showing, show it
    var mapCollapsed = PaneBStatus(); //if false or null then map is visible
    if (mapCollapsed) 
      DoExpandMapViewPane("split");
    if (_allowText)
      ShowTextView(null, _authorID, _kgid, false, true, true);
  }
  else
    SwitchPaneView('map');
}
// JScript File
var m_HideKnowde = null;
var globalKnowdePermissionsInFilterStatus = 'BOTH';
var globalKnowdePermissionsOutFilterStatus = 'BOTH';

//var USERSARRAY = null;
//var USERPERMISSIONRBTNARRAY = null;

function KnowdePermissionsControl_CallbackTrigger_Wrapped(_args, _cbreference)
{

  var args;
  
  args = 'ACTION=' + _args + appendKGInfo();
  
  eval(_cbreference);
}

function KnowdePermissionsControl_ProcessCallBackError_Wrapped(_args, _context, _controlID)
{
}

function HideKnowde()
{
	if(m_HideKnowde == null)
		m_HideKnowde = document.getElementById("KnowdePermissionsControlID1");

  m_HideKnowde.style.top = screen.height/4;
	m_HideKnowde.style.left = "25%";
        
  globalKnowdePermissionsInFilterStatus = 'BOTH';
  globalKnowdePermissionsOutFilterStatus = 'BOTH';
  SetSessionProperty('KnowdePermissionInGridSort', globalKnowdePermissionsInFilterStatus);
  SetSessionProperty('KnowdePermissionOutGridSort', globalKnowdePermissionsOutFilterStatus);
  
  KnowdePermissionsControl_CallbackTrigger('LOAD'); 
}

function CloseKnowdePermissionsControl()
{
  HideKnowdePermissionsControl();
}

function KnowdePermissionsControl_ToggleCheckBox_Wrapped(_chkIdPrefix, _cbref)
{
  // this function is the onclick handler for when a user clicks any of the check boxes when setting up knowde permissions.
  // to distinguish between the two grids we pass through the gridId (_chkIdPrefix) to help us get the correct check boxes
  var groupCheckBoxStatus = document.getElementById(_chkIdPrefix + "_groupCheckBox").checked;
  var peopleCheckBoxStatus = document.getElementById(_chkIdPrefix + "_peopleCheckBox").checked;
  
  var filterStatus;
  
  if(peopleCheckBoxStatus == true && groupCheckBoxStatus == true)
  {
      filterStatus = 'BOTH';
      args += "SETUP=BOTH|"
  }
  else if(peopleCheckBoxStatus == true && groupCheckBoxStatus == false)
  {
      filterStatus = 'USERS';
      args += "SETUP=USERS|"
  }
  else if(peopleCheckBoxStatus == false && groupCheckBoxStatus == true)
  {
      filterStatus = 'GROUPS';
      args += "SETUP=GROUPS|"
  }
  else if(peopleCheckBoxStatus == false && groupCheckBoxStatus == false)
  {
      filterStatus = 'NEITHER';
      args += "SETUP=NEITHER|"
  }
  
  
  
  if(_chkIdPrefix == "InGroupList")
  {
    globalKnowdePermissionsInFilterStatus = filterStatus;
    SetSessionProperty('KnowdePermissionInGridSort', filterStatus);
    
    var args = "ACTION=TOGGLEIN" + appendKGInfo();
  }
  else
  {
    globalKnowdePermissionsOutFilterStatus = filterStatus;
    SetSessionProperty('KnowdePermissionOutGridSort', filterStatus);
    var args = "ACTION=TOGGLEOUT" + appendKGInfo();
  }
  
  eval(_cbref);
}

function KnowdePermissionsControl_CallbackDone_Wrapped(_args, _contentTableID, _inGrid, _outGrid)
{
  try
  {
    // Check for a session time out before completing the callback
    if (CheckSessionTimeout())
      return;
    
    var argsSplit = _args.split('[@|@]');
    var ctrlMode = argsSplit[0];
    var args = argsSplit[1];
    // if the permission check failed in the ProcessAJAXCallback (server side)
    if(args == "Permission Message")
    {
			alert("Sorry, you have insufficient permissions for this action");
			return;
    }
    // We need to split the HTML and the JS and eval the JS first
    var split = args.indexOf('~');
    if (split > - 1)
    {
      var html = args.substring(0, split);
      // Check if the HTML has CDATA sections that need evaluating
      if(html.indexOf('<![CDATA[') >= 0)
      {
        SplitAndEvalHTML(html);
      }   
      var js = args.substring(split + 1, args.length);
      EvalRegisterJavaScripts(js); 
    }

    if(ctrlMode == 'GRIDIN')
      window.setTimeout('SetHeadingCellClientTemplateId(' + _inGrid.Id + ', "' + ctrlMode + '"), 200');
    else if(ctrlMode == 'GRIDOUT')
      window.setTimeout('SetHeadingCellClientTemplateId(' + _outGrid.Id + ', "' + ctrlMode + '"), 200');
    
    if(ctrlMode == 'UPDATE')
    {
      document.getElementById("SiteOverlays_KnowdePermissionsControl1_OutGroupList_dom").style.height = "100%";
      document.getElementById("SiteOverlays_KnowdePermissionsControl1_InGroupList_dom").style.height = "100%";
      ShowKnowdePermissionsControl();
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }       
}

function SplitAndEvalHTML(_html)
{
  //debugger;
  try
  {
    // extract all the cdatas lines from callback result
    var cdatas = _html.split('<![CDATA[');
    
    // loop through the cdatas and process each of them
    // ignoring the first one coz it is just HTML
    var z = 0;
    for(z = 1; z < cdatas.length; z++)
    {
      // javascript starting position
      var posStart = cdatas[z].indexOf('window');
      
      // javascript ending position 
      var posEnd = cdatas[z].lastIndexOf('//]]');
      
      if(posStart > -1 && posEnd > -1)
      {
        // attemp to extract the javascript
        var jscript = cdatas[z].substring(posStart, posEnd);
       
        // Now we have the potential jscript we need to execute it to reinitiallise the grid
        if(jscript.length != 0)
        {        
          // redefine the init script on Page
          eval(jscript);     
        }
      }      
    }
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    debugger;
  }
}

function SetHeadingCellClientTemplateId(_grid, _ctrlMode)
{
//debugger;
  var FirstColumn = _grid.get_table().get_columns()[2];
  
  var filterStatus;
  
  if(_ctrlMode == 'GRIDIN')
    filterStatus = globalKnowdePermissionsInFilterStatus;
  else
    filterStatus = globalKnowdePermissionsOutFilterStatus;
  

  switch (filterStatus)
  {
    case 'BOTH':
        FirstColumn.set_headingCellClientTemplateId('GridHeaderCheckBoxBoth');
        break;
    case 'USERS':
        FirstColumn.set_headingCellClientTemplateId('GridHeaderCheckBoxUsers');
        break;
    case 'GROUPS':
        FirstColumn.set_headingCellClientTemplateId('GridHeaderCheckBoxGroups');
        break;
    case 'NEITHER':
        FirstColumn.set_headingCellClientTemplateId('GridHeaderCheckBoxNeither');
        break;
    default:
        FirstColumn.set_headingCellClientTemplateId('GridHeaderCheckBoxBoth');
        break;
  }
  //eval("window.setTimeout('" +  _grid + ".Render()', 200)");
  _grid.Render();
}

function KnowdePermissionsControl_ConfigureMembers_Wrapped(_inGridID, _outGridID, _mode, _cbref)
{
  //debugger;
  //var args = 'ACTION=CONFIGURE|KGID=' + currentlySelectedKG + '|KNOWDEID=' + returnKnowdeID(globalLastSelectedKnowde) + '|USER=';
  var args = 'ACTION=CONFIGURE' + appendKGInfo() + '|USER=';
  
  // The format of the attached args for the user is as follows...
  // x_y_z
  // where x is either the user id or perm group id
  // y is the permission. 1 if adding to hide list and 0 if adding to visible list
  // z is an id for item type. 1 is a perm group and 0 is a user.  This is needed server side when saving to db
  switch (_mode)
  {
    case 'ADD':
      // get the array of selected items
      var selectedItems = _inGridID.GetSelectedItems();
      
      // Loop thougth them and collect the UserID append to the callback args
      for(var x=0; x<selectedItems.length; x++)
      {
        var item = selectedItems[x];
        var userID = item.GetMember('UserID').Text;
        
        //check if the user id is "". if it is then we have ourselves a perm group!
        if(userID == "0")
        {
          var groupID = item.GetMember('ID').Text;
          args = args + groupID + '_1_1' + ';';
        }
        else          
          args = args + userID + '_1_0' + ';';
      }  
      
      if(selectedItems.length > 0)
        eval(_cbref);
      break;
    case 'ADDALL':
      for(var k=0; k<_inGridID.Data.length; k++)
      {
         var item = _inGridID.Data[k];
         var userID = item[0];
         
         //check if the user id is "". if it is then we have ourselves a perm group!
        if(userID == "0")
        {
          var groupID = item[1];
          args = args + groupID + '_1_1' + ';';
        }
        else          
          args = args + userID + '_1_0' + ';';              
      }
      
      if(_inGridID.Data.length > 0)
        eval(_cbref);
      break;
    case 'REMOVE':
      // get the array of selected items
      var selectedItems = _outGridID.GetSelectedItems();      

      // Loop thougth them and collect the UserID append to the callback args
      for(var x=0; x<selectedItems.length; x++)
      {
        var item = selectedItems[x];
        var userID = item.GetMember('UserID').Text;
        
        //check if the user id is "". if it is then we have ourselves a perm group!
        if(userID == "0")
        {
          var groupID = item.GetMember('ID').Text;
          args = args + groupID + '_0_1' + ';';
        }
        else          
          args = args + userID + '_0_0' + ';';         
      }
        
      if(selectedItems.length > 0)
        eval(_cbref);
      break;
    case 'REMOVEALL':
      for(var k=0; k<_outGridID.Data.length; k++)
      {
         var item = _outGridID.Data[k];
         var userID = item[0];
         
        //check if the user id is "". if it is then we have ourselves a perm group!
        if(userID == "0")
        {
          var groupID = item[1];
          args = args + groupID + '_0_1' + ';';
        }
        else          
          args = args + userID + '_0_0' + ';';   
      }
      if(_outGridID.Data.length > 0)
        eval(_cbref);
      break;
  }
}

function appendKGInfo()
{
//debugger;
  var kgInfo;
  
  return kgInfo = '|KGID=' + currentlySelectedKG + '|KNOWDEID=' +  returnKnowdeID(globalLastSelectedKnowde) + '|PARENTKNOWDEID=' + globalLastSelectedKnowde.getAttribute('parentKnowdeID') + '|MAPDIRECTION=' + globalMapDirection;
}

//function updateUserList(_cbref)
//{
//  //debugger;  
//  try
//  {
//    //set up the array
//    if(USERSARRAY == null)
//    {
//      USERSARRAY = new Array();
//      USERPERMISSIONRBTNARRAY = new Array();
//    }     
//    
//    // Add user and permission to array
//    USERSARRAY[_userID] = _permisionID;   
//    USERPERMISSIONRBTNARRAY[_userID] = _configButton.id;
//    return true;
//  }
//  catch (e) 
//  {
//    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
//    debugger;
//  }       
//}

//function KnowdePermissionsControl_Save_Wrapped(_clientId, _mode, _cbref)
//{
//   // Do save stuff              
//   var users = '';
//   if(USERSARRAY != null && USERSARRAY.length > 0)
//   {          
//      for (var i in USERSARRAY)
//      {
//         users += USERSARRAY[i] + ':';
//      } 
//   }
//   USERSARRAY = null; 
//   
//   eval(_cbref)
//}


// JScript File
function KGPublishingChoicesControl_UpdateMouseOver(_id)
{
  document.getElementById(_id).style.color = "#000e98";
}  

function KGPublishingChoicesControl_UpdateMouseOut(_id)
{
  document.getElementById(_id).style.color = "#535353";
} 

function KGPublishingChoicesControl_SelectionClick()
{
  //Call through to the existing publishing here with the appropriate variables.
  
  /*  The current control calls
   * KGPublishOptionControl_PublishClick(_object, _action, 
                                                  _originalKgId, 
                                                  _publishedKgId, 
                                                  _locationId,
                                                  e)
   */
}

function KGPublishingChoicesControl_CallbackTrigger_Wrapped(_action, 
                                                        _originalKgId, 
                                                        _publishedKgId, 
                                                        _locationId,
                                                        e,
                                                        _callbackScript)
{
  // debugger;
  var args;

  // Construct the callback arguments
  if(_action.length > 0)
    args = 'action=' + _action;
  
  if(_originalKgId > 0)
    args += '|originalKgId=' + _originalKgId;

  if(_publishedKgId != null && _publishedKgId.length > 0)
    args += '|publishedKgId=' + _publishedKgId;

  if(_locationId != null && (_locationId > 0 || _locationId == -1))
    args += '|locationId=' + _locationId;
    

  // Test if we are dealing with Remove or Publish action
  // YES: use the coords saved from gen-menu (1st callback), 
  //      coz we don't want to move the menu to the new event location
  //  NO: we are dealing with gen-menu action, so used the event location
  //      also we need to save the coords for subsequent actions (2nd callback)
  if(_action == 'generate')
  {
    if(e != null)
    {
      g_originalKgId = _originalKgId;
      g_locationId = _locationId;
      //if(_isOnCommunityTab.toLowerCase() == "true")
      //{
      //  g_eventX = e.clientX;
      //  g_eventY = e.clientY;
      //}
      //else
      {
        g_eventX = e.x || e.pageX;
        g_eventY = e.y || e.pageY;
      }
    }
  }
  
  args += '|eventX=' + g_eventX;
  args += '|eventY=' + g_eventY;
  
  if(args.length > 0)
  {      
    CancelBubble(e);
    eval(_callbackScript);
  }
}

function KGPublishingChoicesControl_CallbackDone_Wrapped(_args, _context, _isOnCommunityTab)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  // for firefox
  // set the current scroll position
  if(Splitter1 != null && Splitter1.childNodes != null)
  {
    g_splitter1DivScrollTop = Splitter1.childNodes[0].scrollTop;
    g_splitter1DivScrollLeft = Splitter1.childNodes[0].scrollLeft;
  }


  var tokens = _args.split('|');
  if(tokens.length == 5)
  {
    var holder = document.getElementById(tokens[0]);
    //g_publishHolderId = tokens[0];
    var action = tokens[1];
    var eventX = tokens[2];
    var eventY = tokens[3];
    var content = tokens[4];
   
    if(holder != null)
    {
      holder.innerHTML = content;
      // eval javascripts
      var cdatas = _args.split('<![CDATA[');
      var z = 0;
      for(z = 1; z < cdatas.length; z++)
      {
	      var posStart = cdatas[z].indexOf('window');      
	      var posEnd = cdatas[z].lastIndexOf('}') + 1;
	      if(posStart > -1 && posEnd > -1)
	      {
	  	    if (posEnd < posStart)
	  	    {
	          posEnd = cdatas[z].lastIndexOf(']') + 1;
	          var jscript = cdatas[z].substring(posStart, posEnd);
		        if(jscript.length != 0)
		        {
		          eval(jscript);
		        }
	        }
	        else
	        {
		        var jscript = cdatas[z].substring(posStart, posEnd);
		        if(jscript.length != 0)
		        {
			        eval(jscript);
			        var posNameStart = jscript.indexOf('window');
			        var posNameEnd = jscript.indexOf('=');
			        if(posNameStart > -1 && posNameEnd > -1)
			        {
			          var functionName = jscript.substring(posNameStart, posNameEnd);
			          eval(functionName+'()');
			        }
		        }
		      }
	      }
      }
      
      // for firefox
     if(Splitter1 != null && Splitter1.childNodes != null && Splitter1.childNodes.length > 0)
     {
        if(Splitter1_pane_0.scrollTop != g_splitter1DivScrollTop)
          Splitter1_pane_0.scrollTop = g_splitter1DivScrollTop;
        
        if(Splitter1_pane_0.scrollLeft != g_splitter1DivScrollLeft)
          Splitter1_pane_0.scrollLeft = g_splitter1DivScrollLeft;
     }


     ShowKGPublishingChoicesControl();
     
     //Bug 5997: position in middle of screen instead of alongside menu
     var control = document.getElementById('KGPublishingChoicesControl_DIV_ID') 
     eventY = ((screen.height - control.offsetHeight) / 2) + document.body.scrollTop;    //Display in middle of visible screen.  JPC. 
     eventX = (screen.width / 2) - (control.offsetWidth / 2);
           
      // Need to test for which page we are on to decided what co-ordinates to use:
      // MapTabbedView.aspx has an extra spliter pane which will mess up the normal event.x and event.y
      // so we have to use event.clientX and clientY to correctly position the popup relative to the 
      // extra spliter pane.
      // Options.aspx does not have the extra spliter pane so it can use the normal event.x and event.y
      // however, if we apply clientX and clientY the positioning is wrong for that page.
      // Hence, we need to detect where we are and apply the correct co-ordinates [PL05Mar2008]
      if(_isOnCommunityTab.toLowerCase() == "true")
      {
        //if(action == 'publish'|| action =='remove' || action == 'republishall' || action == 'unpublishall')
        //  window.setTimeout("KGPublishOptionControl_ShowAndReposition('absolute', " + parseInt(g_eventX) + 2 + "," + (parseInt(g_eventY) - 5) + ",'" + tokens[0] + "')", 1000);
        //else
          UpdateKGPublishingChoicesControlPos('absolute', parseInt(eventX) + 2, parseInt(eventY) - 5);
      }
      else 
      { 
        //if(action == 'publish'|| action =='remove' || action == 'republishall' || action == 'unpublishall')
        //  window.setTimeout("KGPublishOptionControl_ShowAndReposition('absolute', " + parseInt(g_eventX) + "," + (parseInt(g_eventY) + 5) + ",'" + tokens[0] + "')", 1000);
        //else
          UpdateKGPublishingChoicesControlPos('absolute', parseInt(eventX), parseInt(eventY) + 5);
      }

    }
    else
      KGPublishingChoicesControl_CallbackError('Content Div element is missing.');
  }
}


// JScript File

var m_KGAppAlertingControlLoaded;
var m_KGAppAlertPageLoaded;
var globalAppAlertGridClientID;
var m_KGAppAlertNResets = 0;
var m_KGAppAlertPreLoaded = 0;

function KGAppAlertingControl_PreLoadApp(_appId, _url)
{
  if(m_KGAppAlertPreLoaded == 0)
  {
    // auto scroll to bottom of the page so can see the alerting details
    var scrollPan = document.getElementById('Splitter1_pane_1');
    if(scrollPan != null && scrollPan.childNodes.length > 0)
      scrollPan.childNodes[0].scrollTop = scrollPan.childNodes[0].scrollHeight;
      
    if(_url.indexOf('@') == -1) // just query string, not url, append empty one
      _url = '@' + _url;
      
    window.setTimeout("KGExecuteMapControl_ShowMenu(null, 'MyAlert', '" + _appId + "', 0, null, null, null, '" + _url + "')", 1000);
    m_KGAppAlertPreLoaded = 1;
  }
}

// KGAppAlertingControlGrid OnClientSideSelect event handler
function KGAppAlertingControl_Grid_OnClientSideSelect_Wrapped(_appId, _alertUrl, _alertUrlQS, _redirectUrl, _loggedInUser)
{
  var strApps = _appId + ''; //make sure it's a string not an int for all the ExecuteMap string manipulation
  if (strApps && (_alertUrl.length > 0 || _alertUrlQS.length > 0) )
    KGExecuteMapControl_ShowMenu(e, 'MyAlert', strApps, 0, null, null, null,  _alertUrl + '@' + _alertUrlQS)

	return true;
}

function KGAppAlertingControl_CallbackDone_Wrapped(args, context, contentDiv)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  if(args.length == 0 || args.indexOf("System exception caught") == 0) // this might be too specific and miss some exceptions, but need to avoid showing message box if e.g. a KG happens to have 'exception' in its name or description
  {
    if (args.indexOf('deadlocked on lock resources with another process') > -1)
      alert("Sorry, our servers are too busy at the moment\n\nPlease try again later");
    else
      alert("AJAX Failure:\n\n" + args);
    return;
  }
  
  // search for the control container
  var holder = document.getElementById(contentDiv);
  
  // Test if the container is found
  // Yes: replace the innerHTML with the callback result
  //  No: call CallbackError with Content div not found error message
  if(holder != null)
  {
    // holder.innerHTML = args.substring(args.indexOf('=') + 1);
    holder.innerHTML = args;
    
  }//end if(holder ....
  else
  {
    KGMyKnowledgeControl_CallbackError('ContentDiv not found in KGAppAlertingControl.', '');
  }
}

function KGAppAlertingControl_CallbackTrigger_Wrapped(args, _cbreference)
{
  eval(_cbreference);
}

function KGAppAlertingControl_CallbackError(args, context)
{
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
   
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    // It was left empty before the edit[PL08JAN2008]
  }
}


// JScript File
var globalVisibleTab;
var globalVisibleLeftTab;
var globalAutoLoadTextView = true;
var globalLoadTabOnPageLoad = true;
var globalCurrentKnowdeIDForTab;
var globalDrawInitial = false;

function LoadTabContentForPageLoad()
{
  if(globalLoadTabOnPageLoad == true && globalVisibleTab != null)
  {
    var initialTab = globalVisibleTab;
	  var tab = document.getElementById(initialTab);
	  if(tab == null)
	  {
	    window.setTimeout('LoadTabContentForPageLoad()', 400);
	  }
	  
    globalVisibleTab = null;
    ChangeTab(initialTab.replace('TSC_',''));
  }
}

function ChangeTabFromMapView(_tabID, _tabName)
{
	if(window.location.href.toLowerCase().indexOf("home.aspx") > -1 )
	{
		// Hide Map View Strip Control & expand splitter
		HideTabWidget();
		DoExpandMapViewPane("split");
		globalSplitterSetting = "split";
		ShowSplitterArrowDown();
		
		// Run Change Tab Code
		ChangeTab(_tabID, _tabName);
	}
	else
	{
	  if ( _tabID == "genes" )
	  {
	    window.location = "examples.aspx";
	    return;
	  }
		SetSessionProperty('CurrentlySelectedTab', _tabID);
		SetSessionProperty('GenesTabMode', "");
		
    window.location = "home.aspx?t=load";
	}
	
}

function ShowTabWidget()
{
	var TabStripWidget = document.getElementById("TabStripControl");
	TabStripWidget.style.display = "block";
}

function HideTabWidget()
{
	var TabStripWidget = document.getElementById("TabStripControl");
	TabStripWidget.style.display = "none";
}

function UpdateTourOnTabClick(_tabID)
{
  switch(_tabID)
  {
	  case "TSC_moretext":
		  UpdateTour(4);
		  break;
	  case "TSC_web":
		  UpdateTour(3);
		  break;
	  case "TSC_genes":
		  break;
	  case "TSC_communities":
	    UpdateTour(5);
		  break;
	  case "TSC_myprofile":
		  break;
  }
}

function ChangeTab(_tabID, _tabName, _loadContent)
{
	// Grab the Tab & Tabstrip Elements
	var TabID = "TSC_" + _tabID;
	var Tab = document.getElementById(TabID);
	var TabStrip = Tab.parentNode;
	var currentContainerID = "TCC_" + _tabID;
	var currentContainer = document.getElementById(currentContainerID);
	
	// Deselect Current Tab & Select new one
	UpdateTabUI(TabStrip, Tab);
	// Show/Hide toolstrip
	ChangeTabToolStrip(_tabID);
	
	// Set the global js variable
	var previousTab = globalVisibleTab;
	globalVisibleTab = TabID;
	
	// Update the tour;
	UpdateTourOnTabClick(TabID);
	
	// render the categories control if req.
	if(globalHCCRenderComplete != true && (_tabID == "myprofile" || _tabID == "genes"))
		setTimeout("HorizontalCategoriesControl_Render()", 1);
	
	// Perform Splitter Manipulation
	AdjustSplitterOnTabChange();
	
	// Call-back necessary control
	// we may need to callback tab as they have different modes... new check required.
	if(_loadContent == null || _loadContent != false)
	  TabContainerControl_CallbackDirection(_tabID);
	
	// Hide the other DIV containers
	HideContainers(currentContainer);
	
	// Show the new container
	ShowContainer(currentContainer);
	
	// hide publishing controls
	 // make sure the publish control is hidden, otherwise it will pop to top left after rerender
	if (globalVisibleTab.indexOf("myprofile") == -1)
	{
    if(g_publishHolderId != null && window.KGPublishOptionControl_HideMenu)
    {
	    window.setTimeout('KGPublishOptionControl_ReSetPublishingChoicesControl()', 500);
      KGPublishOptionControl_HideMenu(g_publishHolderId);
    }
  }
}

// Just update the selected tab UI of the TabStrip
function UpdateTabUI(_tabStrip, _tab, _LeftPaneTabs)
{
	// deselect all Tabs
	for(tabCounter = 0; tabCounter < _tabStrip.childNodes.length; tabCounter++)
	{
		_tabStrip.childNodes[tabCounter].isSelected = false;
		_tabStrip.childNodes[tabCounter].className = _tabStrip.childNodes[tabCounter].className.replace("Selected","Visible");
		_tabStrip.childNodes[tabCounter].childNodes[0].className = _tabStrip.childNodes[tabCounter].childNodes[0].className.replace("Selected", "Visible");
		_tabStrip.childNodes[tabCounter].childNodes[1].className = _tabStrip.childNodes[tabCounter].childNodes[1].className.replace("Selected", "Visible");
		_tabStrip.childNodes[tabCounter].childNodes[2].className = _tabStrip.childNodes[tabCounter].childNodes[2].className.replace("Selected", "Visible");
		if(_LeftPaneTabs == true)
			_tabStrip.childNodes[tabCounter].childNodes[3].className = _tabStrip.childNodes[tabCounter].childNodes[3].className.replace("Selected", "Visible");
	}
	
	// select new tab
	_tab.isSelected = true;
	_tab.className = _tab.className.replace("Visible","Selected");
	_tab.childNodes[0].className = _tab.childNodes[0].className.replace("Visible","Selected");
	_tab.childNodes[1].className = _tab.childNodes[1].className.replace("Visible","Selected");
	_tab.childNodes[2].className = _tab.childNodes[2].className.replace("Visible","Selected");
	if(_LeftPaneTabs == true)
		_tab.childNodes[3].className = _tab.childNodes[3].className.replace("Visible","Selected");
}

// Hide a Single Tab
function HideTab(_tab)
{
	// select new tab
	if(_tab.isSelected == true)
	{
		// need to change to default tab as we are hiding the selected one.
		ChangeToDefaultTab();
		_tab.isSelected = false;
		_tab.className = _tab.className.replace("Selected","Hidden");
		_tab.childNodes[0].className = _tab.childNodes[0].className.replace("Selected","Hidden");
		_tab.childNodes[1].className = _tab.childNodes[1].className.replace("Selected","Hidden");
		_tab.childNodes[2].className = _tab.childNodes[2].className.replace("Selected","Hidden");
	}
	else
	{
		_tab.className = _tab.className.replace("Visible","Hidden");
		_tab.childNodes[0].className = _tab.childNodes[0].className.replace("Visible","Hidden");
		_tab.childNodes[1].className = _tab.childNodes[1].className.replace("Visible","Hidden");
		_tab.childNodes[2].className = _tab.childNodes[2].className.replace("Visible","Hidden");
	}
}

// Show a Single Tab
function ShowTab(_tab, _widgetTab)
{
	// NOT THE SAME AS CHANGE TAB - DOES NOT PERFORM A SELECT
	if(_tab != null)
	{
		_tab.className = _tab.className.replace("Hidden","Visible");
		_tab.childNodes[0].className = _tab.childNodes[0].className.replace("Hidden","Visible");
		_tab.childNodes[1].className = _tab.childNodes[1].className.replace("Hidden","Visible");
		_tab.childNodes[2].className = _tab.childNodes[2].className.replace("Hidden","Visible");
	}
	
	if(_widgetTab != null)
	{
		_widgetTab.className = _widgetTab.className.replace("Hidden","Visible");
		// HACK: in firefox, _widgetTab has more childNodes than expected, so instead 
		// just loop through all of them and check for defined _widgetTab.childNodes[index].className
		for (var index in _widgetTab.childNodes)
		{
		  if (_widgetTab.childNodes[index].className != null)
		    _widgetTab.childNodes[index].className = _widgetTab.childNodes[index].className.replace("Hidden","Visible");
		}
	}
}

// update splitter if required
function AdjustSplitterOnTabChange()
{
}

// If tab you are hiding is selected Tab
function ChangeToDefaultTab()
{
}

function TabControl_ResetScrollBar()
{
  document.getElementById("TCC").parentNode.scrollTop = 0;
}

function GetTabScroller()
{
  return document.getElementById("TCC");
}

function ShowLoadingSymbolForTab(_tab, _mode)
{
	switch(_tab)
	{
		case "Genes":
			// show loading symbol prior to callback for instant feedback to user.
			var grid = document.getElementById("TCC_GenesTabControl_Grid");
			var msgDiv = document.getElementById("GenesTabMessageDiv");
			if(grid != null)
			{
				// show loading symbol on the list grid
				grid.outerHTML = '<table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
				
				// clear the empty message
				var empty = document.getElementById("TCC_GenesTabControl_emptyCont");
				if(empty != null)
					empty.innerHTML = "";
				
				// show loading when on cat home page
				var catHome = document.getElementById("TCC_GenesTabControl_CatHomePageDiv");
				if(catHome != null)
					catHome.innerHTML = '<table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
				var catHomeSwitch = document.getElementById("TCC_GenesTabControl_CatHomeSwitch");
				if(catHomeSwitch != null)
					catHomeSwitch.style.display = "none";
				
				// put up correct title
				var header = document.getElementById("TCC_GenesTabControl_headerContTitle");
				if(header != null)
				{
					switch(_mode)
					{
						case "GenesList":
							header.innerHTML = "Genes List<sup><font color='white'>&#174</font></sup>";
							break;
						case "Search":
							header.innerHTML = "Search Results<sup><font color='white'>&#174</font></sup>";
							break;
						case "Category":
							header.innerHTML = "Featured Knowledge Genes<sup>&#174</sup>";
							break;
					}
				}
			}
			else if(msgDiv != null)
			{
			  	msgDiv.innerHTML = '<table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
			}
			break;
		case "Web":
			var grid;
			grid = document.getElementById("TCC_WebTabControl_Grid");
			var msgDiv = document.getElementById("WebTabMessageDiv");
			if(grid != null)
			{
				grid.outerHTML = '<table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
				var empty;
				empty = document.getElementById("TCC_WebTabControl_emptyCont");
				if(empty != null)
					empty.innerHTML = "";
				var header;
				header = document.getElementById("TCC_WebTabControl_headerContTitle");
				if(header != null)
				{
					switch(_mode)
					{
						case "Knowde":
							header.innerHTML = "Indexed Documents<sup><font color='white'>&#174</font></sup>";
							break;
						case "Search":
							header.innerHTML = "Search Results<sup><font color='white'>&#174</font></sup>";
							break;
					}
				}
			}
			else if(msgDiv != null)
			{
			  	msgDiv.innerHTML = '<table width=\"100%\"><tr><td align=\"center\" style=\"font-size: xx-small\"><br/><img src=\"Images/loadingbar.gif\" /> Loading...</td></tr></table>';
			}
			break;
	}
}

/*********************************************************************************/

var globalWebTabMode;

function setWebTabMode(_mode, _mergeRequests)
{
  var keys = '';
	var values = '';
	
	if(globalWebTabMode != _mode || m_bEditable == true)
	{
		switch(_mode)
		{
			case "Knowde":
				globalWebTabMode = "Knowde";
				keys += 'WebTabMode|';
				values += 'Knowde|';
				//SetSessionProperty('WebTabMode', "Knowde");
				if(globalLastSelectedKnowde != null && globalLastSelectedKnowde != "undefined")
				{
					var knowdeID = returnKnowdeID(globalLastSelectedKnowde);
				  keys += 'CurrentKnowdeIDForTab|';
				  values += knowdeID + '|';
				  // set global value so if tab callback trigger been called, then no need to set CurrentKnowdeIDForTab session
				  globalCurrentKnowdeIDForTab = knowdeID;
					//SetSessionProperty('CurrentKnowdeIDForTab', knowdeID);
			  }
				break;
			case "Search":
				globalWebTabMode = "Search";
				keys += 'WebTabMode|';
				values += 'Search|';
				//SetSessionProperty('WebTabMode', "Search");
				break;
		}
	}
	
	if(keys.length > 0 && values.length > 0)
	{
	  if(_mergeRequests == null || _mergeRequests == false)
	    SetSessionProperty(keys, values, true);
	}
	
	return keys + '[@|@]' + values;
}

var WebTab_KnowdeMemory;
var WebTab_ModeMemory;
function WebTabControl_CallbackTrigger_Wrapped(_mode, _cbref)
{//debugger;
  ClearWebTabSessionValuesForMode(globalWebTabMode);
  if(globalWebTabMode == null)
		globalWebTabMode = "Knowde";
		
  var whatId = '';
  try
  {
    whatId = GetGlobalHighlightedWhatId();
  }
  catch(e)
  {
  }  
	
  switch(globalWebTabMode)
  {
		case "Knowde":
			if((!(window.globalLastSelectedKnowde) || globalLastSelectedKnowde == null || globalLastSelectedKnowde == "undefined")
			    && (whatId == null || whatId == ''))
			{
				// show no context message
				var args = "Action=NoContext";
					eval(_cbref);
			}
			else
			{
				var knowdeID = whatId;
				if(knowdeID == '')
				  knowdeID = returnKnowdeID(globalLastSelectedKnowde)
				if(WebTab_KnowdeMemory != knowdeID || WebTab_ModeMemory != globalWebTabMode || m_bEditable == true || globalDrawInitial == true)
				{
					globalDrawInitial = false;
					// callback web list if its not already loaded against this knowde.
					WebTab_KnowdeMemory = knowdeID;
					WebTab_ModeMemory = globalWebTabMode;
					//if(globalCurrentKnowdeIDForTab == null || globalCurrentKnowdeIDForTab !=  knowdeID)
					  SetSessionProperty('CurrentKnowdeIDForTab', knowdeID);
					// reset value
					globalCurrentKnowdeIDForTab = null;
					ShowLoadingSymbolForTab("Web", globalWebTabMode);
					var args = "Action=Reload";
					eval(_cbref);
				}
			}
			break;
		case "Search":
			WebTab_ModeMemory = globalWebTabMode;
			ShowLoadingSymbolForTab("Web", globalWebTabMode);
			var args = "Action=WebSearch";
			eval(_cbref);
			break;
  }	
}

function WebTabControl_CallbackDone_Wrapped(_args, _context)
{ 
  KGListViewControl_CallbackDone(_args, _context);
}

function WebTabControl_ProcessCallBackError_Wrapped(_args, _context, _clientId)
{
}

function ClearWebTabSessionValuesForMode(_mode)
{
	if(_mode == null)
	{
	  // clear search session
    SetSessionProperty('WebSearch_PhraseName', ''); 
	}
}

function setTabModes(_genesMode, _webMode)
{
  var sessionkeys = '';
	var sessionvalues = '';
  var keyvalues = setGenesTabMode(_genesMode, true);
  var kvpairs = keyvalues.split('[@|@]');
  if(kvpairs.length == 2 && kvpairs[0].length > 0)
  {
    sessionkeys += kvpairs[0];
    sessionvalues += kvpairs[1];
  }
  keyvalues = setWebTabMode(_webMode, true);
  kvpairs = keyvalues.split('[@|@]');
  if(kvpairs.length == 2 && kvpairs[0].length > 0)
  {
    sessionkeys += kvpairs[0];
    sessionvalues += kvpairs[1];
  }
  
  if(sessionkeys.length > 0 && sessionvalues.length > 0)
  {
    SetSessionProperty(sessionkeys, sessionvalues, true);
  }
}
/*********************************************************************************/

var globalGenesTabMode;

function setGenesTabMode(_mode, _mergeRequests)
{
  var keys = '';
	var values = '';

	if(globalGenesTabMode != _mode  || m_bEditable == true)
	{
		switch(_mode)
		{
			case "GenesList":
				globalGenesTabMode = "GenesList";
				keys += 'GenesTabMode|';
				values += 'GenesList|';
				//SetSessionProperty('GenesTabMode', "GenesList");
				if(globalLastSelectedKnowde != null && globalLastSelectedKnowde != "undefined")
				{
					var knowdeID = returnKnowdeID(globalLastSelectedKnowde);
				  keys += 'CurrentKnowdeIDForTab|';
				  values += knowdeID + '|';
				  // set global value so if tab callback trigger been called, then no need to set CurrentKnowdeIDForTab session
				  globalCurrentKnowdeIDForTab = knowdeID;
					//SetSessionProperty('CurrentKnowdeIDForTab', knowdeID);
			  }
				break;
			case "Search":
				globalGenesTabMode = "Search";
				keys += 'GenesTabMode|';
				values += 'Search|';
				//SetSessionProperty('GenesTabMode', "Search");
				break;
			case "Category":
				globalGenesTabMode = "Category";
				keys += 'GenesTabMode|';
				values += 'Category|';
				//SetSessionProperty('GenesTabMode', "Category");
				break;
		}
	}
	
	
	if(keys.length > 0 && values.length > 0)
	{
	  if(_mergeRequests == null || _mergeRequests == false)
	    SetSessionProperty(keys, values, true);
	}
	
	return keys + '[@|@]' + values;
}

var GenesTab_KnowdeMemory;
var GenesTab_ModeMemory;
function GenesTabControl_CallbackTrigger_Wrapped(_mode, _cbref)
{
  ClearGenesTabSessionValuesForMode(_mode);
    
	switch(globalGenesTabMode)
	{
		case "GenesList":
      var whatId = GetGlobalHighlightedWhatId();
		
			if((!(window.globalLastSelectedKnowde) || globalLastSelectedKnowde == null || globalLastSelectedKnowde == "undefined")
			&& (whatId == null || whatId == ''))
			{
				// show no context message
				var args = "Mode=NoContext";
			if((m_applicationControlOpen == null || m_applicationControlOpen == false) 
			    && (m_appForceOpen == null || m_appForceOpen == false)
			    && m_KGApplicationControl_appID <= 0)
  	    window.location = "examples.aspx";  
  	    else
			    eval(_cbref);
			}
			else
			{
				// callback genes list if its not already loaded against this knowde.
				var knowdeID = whatId;
				if(knowdeID == '')
				  knowdeID = returnKnowdeID(globalLastSelectedKnowde)

				if(GenesTab_KnowdeMemory != knowdeID || GenesTab_ModeMemory != globalGenesTabMode || m_bEditable == true || globalDrawInitial == true)
				{
					globalDrawInitial = false;
					GenesTab_ModeMemory = globalGenesTabMode;
					GenesTab_KnowdeMemory = knowdeID;
					ShowLoadingSymbolForTab("Genes", globalGenesTabMode);
					//if(globalCurrentKnowdeIDForTab == null || globalCurrentKnowdeIDForTab != knowdeID)
					  SetSessionProperty('CurrentKnowdeIDForTab', knowdeID);
					// reset value
					globalCurrentKnowdeIDForTab = null;
					var args = "Mode=Genes";
					eval(_cbref);
				}
			}
			break;
		case "Search":
			GenesTab_ModeMemory = globalGenesTabMode;
			ShowLoadingSymbolForTab("Genes", globalGenesTabMode);
			var args = "Mode=Search";
			eval(_cbref);
			break;
		case "Category":
		  LastKnowdeClickedKGID = '';
			GenesTab_ModeMemory = globalGenesTabMode;
			ShowLoadingSymbolForTab("Genes", globalGenesTabMode);
			var args = "Mode=Category";
			eval(_cbref);
			break;
		default:
		  // show no context message
		  var args = "Mode=NoContext";
		  // redirect to the examples
			if((m_applicationControlOpen == null || m_applicationControlOpen == false) 
			    && (m_appForceOpen == null || m_appForceOpen == false)
			    && m_KGApplicationControl_appID <= 0)
	    window.location = "examples.aspx";  
			else
				eval(_cbref);
			break;
		
	}
}

function GenesTabControl_CallbackDone_Wrapped(_args, _context)
{ 
  KGListViewControl_CallbackDone(_args, _context);
}

function ClearGenesTabSessionValuesForMode(_mode)
{
  if(_mode == "GenesList")
	{
	  // clear search session and 
    SetSessionProperty('GenesSearch_PhraseName', ''); 
	}
	if(_mode == "Category")
	{
	  // clear search session and knowde session
	  // this needs to be clear in SetSessionForHomeClick in HK.js and MembershipHeader usercontrols code behind as well
	  var keys = 'GenesSearch_PhraseName|CurrentKnowdeIDForTab';
	  var values = '|';
    SetSessionProperty(keys, values, true);
	}
	if(_mode == "Search")
	{
	  // clear knowde session
    SetSessionProperty('CurrentKnowdeIDForTab', ''); 
	}
}

function GenesTabControl_ProcessCallBackError_Wrapped(_args, _context, _clientId)
{
}

function GenesTabControl_GenesDocumentAvatarClick(_ownerKey, _event)
{
	ShowUser(_ownerKey);
	//alert("Have to Open Community Tab for OwnerKey " + _ownerKey + " Here...");
}

function SwitchBetweenCategoryHomeAndList()
{
	var Header = document.getElementById("TCC_GenesTabControl_ListHeaderContainer");
	var Grid = document.getElementById("TCC_GenesTabControl_ListViewGridContainer");
	var Empty = document.getElementById("TCC_GenesTabControl_emptyCont");
	var CatHome = document.getElementById("TCC_GenesTabControl_CatHomePageDiv");
	var CatSwitch = document.getElementById("TCC_GenesTabControl_CatHomeSwitch");
	
	if(CatHome.style.display == "block")
	{
		if(Header != null)
			Header.style.display = "block";
		if(Grid != null)
			Grid.style.display = "block";
		if(Empty != null)
			Empty.style.display = "block";
		if(CatHome != null)
			CatHome.style.display = "none";
		if(CatSwitch != null)
			CatSwitch.innerHTML = "View Home Page for this Category";
	}
	else
	{
		if(Header != null)
			Header.style.display = "none";
		if(Grid != null)
			Grid.style.display = "none";
		if(Empty != null)
			Empty.style.display = "none";
		if(CatHome != null)
			CatHome.style.display = "block";
		if(CatSwitch != null)
			CatSwitch.innerHTML = "View Knowledge Genes in this Category";
	}
}

/*********************************************************************************/

function TabContainerControl_CallbackDirection(_TabID)
{
	switch(_TabID)
	{
		case "communities":
		  KGCommunityTabControl_Activate();
			break;
		case "moretext":
		  // auto load text view	
	    AutoLoadTextViewForKnowde('ChangeTab', null);
			break;
		case "myprofile":
		  KGMyProfileTab_Activate();
			break;
		case "genes":
			GenesTabControl_CallbackTrigger();
			break;
		case "web":
			WebTabControl_CallbackTrigger();
			break;
		default:
			break;
	}
}

function TabContainerControl_CallbackDone_Wrapped(_args, _context)
{
  var stringArray = _args.split('[@.|.@]'); 
  var TabName = stringArray[0];
  var HTML = stringArray[1];
  var javaScripts = stringArray[2];
  
  // Register Appropriate Scripts
  if (javaScripts.length > 0)
	  EvalRegisterJavaScripts(javaScripts);
	
  // Update Container Content
	var currentContainer = document.getElementById("TCC_" + TabName);
	if(currentContainer != null)
	{
		UpdateHTML(currentContainer, HTML);
	}
	
	// Hide the other DIV containers
	HideContainers(currentContainer);
	
	// Show the new container
	ShowContainer(currentContainer);
}

function UpdateHTML(_currentContainer, _HTML)
{
	// extract all the cdatas lines from callback result
	var cdatas = _HTML.split('<![CDATA[');  
	_currentContainer.innerHTML = _HTML;
	// loop through the cdatas and process each of them
  var z = 0;
  for(z = 1; z < cdatas.length; z++)
  {
    // javascript starting position
    var posStart = cdatas[z].indexOf('window');
    
    // javascript ending position 
    var posEnd = cdatas[z].lastIndexOf('}') + 1;
    
    if(posStart > -1 && posEnd > -1)
    {
      // attemp to extract the javascript
      var jscript = cdatas[z].substring(posStart, posEnd);
     
      // Now we have the potential jscript we need to execute it to 
      // reinitiallise the grid
      if(jscript.length != 0)
      {        
        // redefine the init script on Page
        eval(jscript);
        var posNameStart = jscript.indexOf('window');
        var posNameEnd = jscript.indexOf('=');
        
        var functionName = jscript.substring(posNameStart, posNameEnd);
        // execute the script
        eval(functionName+'()');
        
        var objectNameStart = jscript.indexOf('new ComponentArt_Grid(') + 23;
        var objectNameEnd = jscript.indexOf('List\')') + 4;
        if(objectNameEnd > objectNameStart)
        {
          var objectName = jscript.substring(objectNameStart, objectNameEnd);           
          eval(objectName+'.Render()');
        }
      }
    }      
  }
}

function TabContainerControl_ProcessCallBackError_Wrapped(_args, _context, _clientId)
{
}

function HideContainers(_currentContainer)
{
	var parentContainer = _currentContainer.parentNode;
	for(containerCounter = 0; containerCounter < parentContainer.childNodes.length; containerCounter++)
	{
		parentContainer.childNodes[containerCounter].className = "TabContainerHidden";
	}
}

function ShowContainer(_currentContainer)
{
	_currentContainer.className = "TabContainerShown";
}

/*********************************************************************************
ToolStrip
**********************************************************************************/
var m_toolStripUCIDPrefix = '';

function ChangeTabToolStrip(_tabID)
{
  //debugger;
  var toolStrip = document.getElementById(m_toolStripUCIDPrefix+ 'ToolStripContainerDiv');

  if(toolStrip == null)
    return;
    
  // hide all the tool divs first
  for(var tidx=0; tidx<toolStrip.childNodes.length; tidx++)
  {
		try{toolStrip.childNodes[tidx].style.display = 'none';}
		catch(e){}
  }
  
  // Hide the categories control
  HideCategories();
  
  switch(_tabID)
  {
    case 'genes':
      SetTooStripSearchButton(_tabID);
      ShowToolStrip(toolStrip, m_toolStripUCIDPrefix + 'KGToolStrip_SearchDiv');
      // show the categories control
      ShowCategories(1000, true);
      break;
    case 'web':
      SetTooStripSearchButton(_tabID);
      ShowToolStrip(toolStrip, m_toolStripUCIDPrefix + 'KGToolStrip_SearchDiv');
      break;
    case 'communities':
      if(window.Active_KGID && Active_KGID != "")
        ShowToolStrip(toolStrip, m_toolStripUCIDPrefix + 'KGToolStrip_CommunityDiv');
      else
        toolStrip.style.display = 'none';
      break;
    case 'moretext':
      SetTooStripSearchButton(_tabID);
      ShowToolStrip(toolStrip, m_toolStripUCIDPrefix + 'KGToolStrip_TextDiv');
      break;
      /* can't do this here - it hides all the lower toolstrips and the categories controls at the beginning, but doesn't hide the left hand toolstrips
    case 'whats' :
			ShowToolStrip(toolStrip, m_toolStripUCIDPrefix + 'KGToolStrip_WhatsDiv');
			break;
		case 'semantictree' :
			ShowToolStrip(toolStrip, m_toolStripUCIDPrefix + 'KGToolStrip_TreeDiv');
			break;
			*/
    default:
			// show the categories control
      ShowCategories(1000, false);
      // hide tool strip
      toolStrip.style.display = 'none';
      break;
  }
}


// _width is the desired width for the categories control
function ShowCategories(_width, _showSelected)
{
	// show horizontal categories
	var categories = document.getElementById("TSC_HorizontalCategoriesControl1");
	if(categories != null)
		categories.parentNode.style.display = "block";
 
  if (globalHCCRenderComplete)
  {
     // resize if necessary
    if (_width != globalHCCCurrentWidth) // only resize if desired width is different to current width
    {
	    HorizontalCategoriesControl_Resize(_width, _showSelected);
	  }
	  else
	  {
	    // show or hide the selected category - tab dependent
	    // only need to do this if there isn't a callback, otherwise it'll be handled there
	    // don't need to do it if the control hasn't rendered yet
      if (_showSelected)
        HorizontalCategoriesControl_ShowSelection();
	    else
	      HorizontalCategoriesControl_HideSelection();
	  }
	  
	  // show or hide the breadcrumbs - tab dependent
	  // this isn't handled in the resize callback, but it is handled in the first Render
    if (_showSelected)
      HorizontalCategoriesControl_ShowLoadedBreadcrumbTrail();
    else
      HorizontalCategoriesControl_HideBreadcrumbTrail();
	}
}

function HideCategories()
{
	var categories = document.getElementById("TSC_HorizontalCategoriesControl1");
	if(categories != null)
		categories.parentNode.style.display = "none";
}

function SetTooStripSearchButton(_tabID)
{
  var btn = document.getElementById('KGToolStrip_SearchButton');
  var searchBox = document.getElementById('KGToolStrip_KGSearchTextBox');
  if(btn != null && searchBox != null)
  {
     switch(_tabID)
      {
        case 'genes':
          if(btn.innerText != 'Search for Genes')
          {
            SetInnerText(btn, 'Search for Genes');
            searchBox.value = '';
          }
          break;
        case 'web':
          if(btn.innerText != 'Search the Web')
          {
            SetInnerText(btn, 'Search the Web');
            searchBox.value = '';
          }
          break;
      }
    
  }
}

function ShowToolStrip(_toolStrip, _toolDivId)
{
 // show tools
 if(_toolDivId != null)
 {
    var toolDiv = document.getElementById(_toolDivId);
    if(toolDiv != null)
      toolDiv.style.display = 'block';
 }
  // show strip
  _toolStrip.style.display = 'block';
}

/**************** Search ****************/
function KGTabSearch_Click()
{
  var itemType = 0;
  var searchBox = document.getElementById('KGToolStrip_KGSearchTextBox');
  if(searchBox != null && searchBox.value!=null && searchBox.value!='' && searchBox.value.replace(/'/g, '').replace(/^\s*/, '').replace(/\s*$/, '') != '')
  {
    // KGSearchServer will query QuerySearchResults when itemID = '-1'
    var itemName = searchBox.value; //.replace(/'/g, "\\" + "\'")
    
    
    if(globalVisibleTab.toLowerCase().indexOf('_genes') != -1)
    {
			// Set the mode for the Genes Tab control
			setGenesTabMode("Search");
			
      // store in session as root phrase name
      SetSessionProperty('GenesSearch_PhraseName', itemName); 
            
      // callback to GenesTabControl
      GenesTabControl_CallbackTrigger();
    }else if(globalVisibleTab.toLowerCase().indexOf('_web') != -1)
    {
			// Set the mode for the Web Tab control
			setWebTabMode("Search");
			
      // store in session as root phrase name
      SetSessionProperty('WebSearch_PhraseName', itemName); 
            
      // callback to GenesTabControl
      WebTabControl_CallbackTrigger();
    }
  }
  else 
  {
    if(searchBox != null && searchBox.value!=null && searchBox.value!='' && searchBox.value.replace(/^\s*/, '').replace(/\s*$/, '') == '')
    {
      searchBox.value = '';
    }
    
  }
}

function ToolStrip_SearchBoxKeyPress(e)
{
  e = e || window.event;
  //if(e && e.type == "keydown")
  //{
    //alert(e.keyCode);
    if (e.keyCode == 13) // enter
    {
      KGTabSearch_Click();
      return false;
    }
  //}
}

/********************* LEFT PANE TABS ******************************/

function ChangeLeftTab(_tabID, _tabName, _loadContent)
{
	// Grab the Tab & Tabstrip Elements
	var TabID = "LTSC_" + _tabID;
	//var Tab = document.getElementById(TabID);
	//var TabStrip = Tab.parentNode;
	
	// Grab container
	var currentContainerID = "LTSC_" + _tabID + "Container";
	var currentContainer = document.getElementById(currentContainerID);
	
	// Deselect Current Tab & Select new one
	//UpdateTabUI(TabStrip, Tab, true);
	
	// Show/Hide toolstrip
	//ChangeLeftTabToolStrip(_tabID);
	
	// Set the global js variable
	//var previousTab = globalVisibleLeftTab;
	//globalVisibleLeftTab = TabID;
	
	// Hide the other DIV containers
	//HideContainers(currentContainer);
	
	// Show the new container
	var wimage = document.getElementById('WhatWhatIsArrowImage');
	if(_tabID == "whats")
	{
		currentContainer.className = "whatsContainer";
		if(wimage != null)
		  wimage.style.display = 'block';
  }
	else
	{
		currentContainer.className = "semTreeContainer";
		if(wimage != null)
		  wimage.style.display = 'none';
	}
}

function ShowHideButton(_show, _btnId)
{
  var btn = document.getElementById(_btnId);
  if (btn)
  {
    if (_show)
      btn.style.display = "";
    else
      btn.style.display = "none";
  }
}

function IsLeftTabShown(_tabID)
{
  var currentContainerID = "LTSC_" + _tabID + "Container";
  var currentContainer = document.getElementById(currentContainerID);
  if (currentContainer != null && currentContainer.className.indexOf("TabContainerHidden") == -1)
    return true;
  else
    return false;
}

/**************** What WhatIs Tab Control *********************/
var globalWhatWhatIsTabKnowdeId;
var globalWhatWhatIsTabDirection; // set this using SetWhatWhatIsTabDirection to toggle the change direction buttons as well
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_Reload(_knowdeID, _direction, _parentKnowdeID, _thenPriorKnowdeID, _knowdeDirection, _focusOnMap)
{
  //debugger;
  
  ShowHideSelectIntoKnowdeBtn(false);
    
  if(_knowdeID == 0 || m_IsEditFromNewKnowde == true)
  {
    WhatWhatIsTabControl_ClearContent();
    return;
  }
  
  // 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;
    if(_direction != null)
      args += '|Direction=' + _direction;
    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';
    WhatWhatIsTabControl_CallbackTrigger(args);
    globalWhatWhatIsTabKnowdeId = _knowdeID;
    if(_direction == null)
      SetWhatWhatIsTabDirection(globalWhatWhatIsTabDirection);
    else
      SetWhatWhatIsTabDirection(_direction);
  }
}

function WhatWhatIsTabControl_Edit()
{  
  // check whether selected knowde has changed
  if(globalWhatWhatIsTabKnowdeId != null)
  {
    var args = 'Action=Edit|KnowdeId=' + globalWhatWhatIsTabKnowdeId;
    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 args = 'Action=SwitchDirection|KnowdeId=' + globalWhatWhatIsTabKnowdeId;
    if(_direction != null)
      args += '|Direction=' + _direction;
    if(parentKnowdeID != null)
      args += '|ParentId=' + parentKnowdeID;
    if(knowdeDirection != null)
			args += '|KnowdeDirection=' + knowdeDirection;
    
    CurrentlyShowingWhats = false;
    CurrentlyShowingWhatIss = false;
    m_SelectedWhatEditing = false;
    m_IsEditFromNewWhat = false;
    WhatWhatIsTabControl_CallbackTrigger(args);
    SetWhatWhatIsTabDirection(_direction);
    RemoveBottomWhatEditBox();
    ActivateAddWhatsLink(true);
  }
}

function WhatWhatIsTabControl_CallbackTrigger_Wrapped(_args, _cbref)
{
  //debugger;
	var args = _args;
  if(m_bEditable == true) // in edit mode
      args +=  '|MapEditing=true';
	eval(_cbref);
}

function WhatWhatIsTabControl_CallbackDone_Wrapped(_args, _context)
{ 
  // 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();
  }
}

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("LTSC_KGWhatWhatIsTabCtrl_selectIntoKnowde").className = "enabledLink";
	else
		document.getElementById("LTSC_KGWhatWhatIsTabCtrl_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 = "WhatIsArrowGrey";
			else
				document.getElementById("WhatIsArrow").className = "WhatIsArrow";
			break;
		case "What":
			if(_greyed == true)
				document.getElementById("WhatArrow").className = "WhatArrowGrey";
			else
				document.getElementById("WhatArrow").className = "WhatArrow";
			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();
	}
}

function OpenWhatsForTour()
{
	ChangeArrowClass('WhatIs', true); 
	ChangeArrowClass('What', false); 
	OpenLeftPanel();
	UpdateTour(7); 
	ChangeLeftTab('whats', 'What / What-Is'); 
	showWhats(globalLastSelectedKnowde);
}

/************* Repopulation ***********************************/
// Waits until any scrolling has finished before repopulating 
function RepopulateTabbedWindow(_action, _knowdeID)
{
	// repopulate if the tab windows are visible
	var PaneC = Splitter1.Panes[1];
	if(PaneC.element.style.display != "none")
	{
		if(globalVisibleTab != null)
		{
			// repopulate open tab only
			switch(globalVisibleTab)
			{
				case "TSC_moretext":
					AutoLoadTextViewForKnowde(_action, _knowdeID);
					break;
				case "TSC_web":
					WebTabControl_CallbackTrigger();
					break;
				case "TSC_genes":
					GenesTabControl_CallbackTrigger();
					break;
				case "TSC_communities":
				  KGCommunityTabControl_Activate();
					break;
				case "TSC_myprofile":
					break;
			}
		}
  }
}

// Waits until any scrolling has finished before repopulating 
function RepopulateTextView()
{
  /*if (globalAutoScrollDirection != null)
  {
    clearTimeout(repopulate);
    repopulate = setTimeout("RepopulateTextView()", 200); 
  }
  else
    KGTabbedWindowsControl_CallbackTrigger('KnowdeHover-ReloadTextView'); */
}

function LoadMoreTextTabPageLoad()
{
  ChangeTabToolStrip('moretext');
  DoExpandMapViewPane('split');
  ShowSplitterArrowDown();
  globalSplitterSetting = "split";
}


// KGCommunityLinkControl JScript File

function KGAddCommunityLinkControlCallbackDone(_args, _context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  if (_args.indexOf("Exception") == -1)
  {
    // reload the communityTab
    window.setTimeout('LoadCommunityTab("ListView")', 1);
    
    // 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 + ')');
		
    var userMsg = '<p>Community Link successfully added';
    switch (retMessage.Context)
    {
      case 'KG':
        userMsg += ' to entire KG.';
        break;
      case 'Knowde':
        userMsg += ' to this Knowde only.';
        break;
      case 'Hows':
        userMsg += ' to this Knowde and Hows.';
        break;
    }
    userMsg += '</p>';
  	
    userMsg += '<input type="button" class="CommunityLinkControlBtn" value="Add another" onclick="m_AddCommunityLinkControl.Initialise();"/>'
    m_AddCommunityLinkControl.HideOrShowLoadingDiv(true, userMsg, true);
  }
  else
  {
    alert(_args);
  }
}

function KGAddCommunityLinkControlCallbackError(_args, _context)
{
  alert(_args);
}

function OpenKGAddCommunityLinkControl(e)
{
  if (isAuthenticated())
  {
    e = e || window.event;
    
    m_AddCommunityLinkControl.Initialise();
    ShowKGAddCommunityLinkControl();
    
    var x;
    var y;
    // Get cursor position with respect to the page.
    if (window.scrollX)
    {
      x = e.clientX + window.scrollX - 20;
      y = e.clientY + window.scrollY - 20;
    }
    else if (e)
    {
      x = e.clientX + document.documentElement.scrollLeft
        + document.body.scrollLeft - 80;
      y = e.clientY + document.documentElement.scrollTop
        + document.body.scrollTop - 50;
      
      if (x + m_AddCommunityLinkControl.ContentDiv.scrollWidth > document.documentElement.scrollWidth)
        x = document.documentElement.scrollWidth - m_AddCommunityLinkControl.ContentDiv.scrollWidth;
      
      if (y + m_AddCommunityLinkControl.ContentDiv.scrollHeight > document.documentElement.scrollHeight)
        y = document.documentElement.scrollHeight - m_AddCommunityLinkControl.ContentDiv.scrollHeight;
    }
    
    UpdateKGAddCommunityLinkControlPos('absolute', x, y);
  }
  else // user not signed in
  {
    m_AddCommunityLinkControl.HandleAnonymousUser();
  }
}

// AddCommunityLinkControl object definition
function AddCommunityLinkControl(_urlTxtBoxID, _nameTxtBoxID, _contextSelectorID, _contentDivID, _loadingDivID, _kgURLDivID, _callbackScript, _rootURL)
{
  this.UrlTxtBoxID = _urlTxtBoxID;
  this.NameTxtBoxID = _nameTxtBoxID;
  this.ContextSelectorID = _contextSelectorID;
  this.ContentDivID = _contentDivID;
  this.LoadingDivID = _loadingDivID;
  this.KGURLDivID = _kgURLDivID;
  
  this.UrlTxtBox;
  this.NameTxtBox;
  this.ContextSelector;
  this.ContentDiv;
  this.LoadingDiv;
  this.KGURLDiv;
  
  this.rootURL;
  
  this.CallbackScript = _callbackScript;
  
  this.Initialise = function()
  {
    if(this.UrlTxtBox == null)
      this.UrlTxtBox = document.getElementById(this.UrlTxtBoxID);
      
    if(this.NameTxtBox == null)
      this.NameTxtBox = document.getElementById(this.NameTxtBoxID);
      
    if(this.ContextSelector == null)
      this.ContextSelector = document.getElementById(this.ContextSelectorID);
    
    if(this.ContentDiv == null)
      this.ContentDiv = document.getElementById(this.ContentDivID);
    
    if(this.LoadingDiv == null)
      this.LoadingDiv = document.getElementById(this.LoadingDivID);
    
    if(this.KGURLDiv == null)
      this.KGURLDiv = document.getElementById(this.KGURLDivID);
    
    if(this.rootURL == null)
      this.rootURL = _rootURL;
    
    this.ResetInputFields();
    this.SetKGURL();
    this.HideOrShowLoadingDiv(false);
  };
  
  this.ResetInputFields = function()
  {
    this.UrlTxtBox.value = 'http://';
    this.NameTxtBox.value = '';
  };
  
  this.HideOrShowLoadingDiv = function(_show, _message, _messageOnly)
  {
    var div = this.LoadingDiv; 
    
    var message = _message;
    if(message == null)
      message = 'Adding Link...';
     
    if (div != null)
    {
      if(_show != null && _show == true)
      {
        // clear the div
        div.innerHTML = '';
        
        if (!_messageOnly)
          div.innerHTML = "<img src='Images/LoadingBar.gif' width='21px' height='21px'/>&nbsp;";
        
        div.innerHTML += message;
        div.style.display = 'block';
        
        // hide the content
        this.ContentDiv.style.display = 'none';
      }
      else if(div.style.display != 'none')
      {
        div.style.display = 'none';
        div.innerHTML = '';
        
        // reset the content display style
        this.ContentDiv.style.display = '';
      }
    }
  };

  this.CallbackTrigger = function(_args)
  {
    // Construct the callback arguments
    if(_args != null)
    { 
      var args = _args;
      
      if(args.length > 0)
      {
        // show the loading div
        this.HideOrShowLoadingDiv(true);
        
        // trigger the callback
        eval(this.CallbackScript);
      }
    }
  };
  
  this.LinkBtnClicked = function()
  {
    var validated = Page_ClientValidate('KGAddCommunityLinkValidation');
    if(validated)
    {
      var args = 'Action=AddLink';
      args += '|URL=' + encodeURIComponent(this.UrlTxtBox.value);
      args += '|Name=' + this.NameTxtBox.value;
      args += '|Context=' + this.ContextSelector.value;
      this.CallbackTrigger(args);
      
    }
  };
  
  this.HandleAnonymousUser = function()
  {
    var currentKnowdeID = returnKnowdeID(globalLastSelectedKnowde);
    // redirect to sign in sign up page
    redirectToSignInSignUpPage('AddCommunityLink', Active_KGID, currentKnowdeID);
  };
  
  this.SetKGURL = function()
  {
    // set the KGURL
    var queryString = '&#63;kgid&#61;'// html code for '?kgid='
    this.KGURLDiv.innerHTML = this.rootURL + queryString + Active_KGID;
  };
}

function KGDeleteCommunityLinkControlCallbackDone(_args, _context)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  if (_args.indexOf("Exception") == -1)
  {
    // reload the communityTab
    window.setTimeout('LoadCommunityTab("ListView")', 1);
    
	  // 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 + ')');
		
		HideKGDeleteCommunityLinkControl();
  }
  else
  {
    alert(_args);
  }
}

function KGDeleteCommunityLinkControlCallbackError(_args, _context)
{
  alert(_args);
}

function OpenKGDeleteCommunityLinkControl(e, _knowdeCommunityLinkID, _addedByCurrentUser)
{
  e = e || window.event;

  m_DeleteCommunityLinkControl.Initialise();
  // set the KnowdeCommunityLinkID
  m_DeleteCommunityLinkControl.KnowdeCommunityLinkID = _knowdeCommunityLinkID;
  
  // if the link wasn't added by the current user
  if (!_addedByCurrentUser)
    m_DeleteCommunityLinkControl.SetUserMsg('The user who added this link will be informed of its removal');
  
  ShowKGDeleteCommunityLinkControl();
  
  var x;
  var y;
  // Get cursor position with respect to the page.
  if (window.scrollX)
  {
    x = e.clientX + window.scrollX - 20;
    y = e.clientY + window.scrollY - 20;
  }
  else if (e)
  {
    x = e.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft - 400;
    y = e.clientY + document.documentElement.scrollTop
      + document.body.scrollTop - 50;
    
    if (x + m_DeleteCommunityLinkControl.ContentDiv.scrollWidth > document.documentElement.scrollWidth)
      x = document.documentElement.scrollWidth - m_DeleteCommunityLinkControl.ContentDiv.scrollWidth;
    
    if (y + m_DeleteCommunityLinkControl.ContentDiv.scrollHeight > document.documentElement.scrollHeight)
      y = document.documentElement.scrollHeight - m_DeleteCommunityLinkControl.ContentDiv.scrollHeight;
  }
  
  UpdateKGDeleteCommunityLinkControlPos('absolute', x, y);
}

// DeleteCommunityLinkControl object definition
function DeleteCommunityLinkControl(_contextSelectorID, _contentDivID, _loadingDivID, _userMsgID, _callbackScript)
{
  this.ContextSelectorID = _contextSelectorID;
  this.ContentDivID = _contentDivID;
  this.LoadingDivID = _loadingDivID;
  this.UserMsgID = _userMsgID;
  
  this.KnowdeCommunityLinkID;
  
  this.ContextSelector;
  this.ContentDiv;
  this.LoadingDiv;
  this.UserMsg;
  
  this.CallbackScript = _callbackScript;
  
  this.Initialise = function()
  {
    if(this.ContextSelector == null)
      this.ContextSelector = document.getElementById(this.ContextSelectorID);
    
    if(this.ContentDiv == null)
      this.ContentDiv = document.getElementById(this.ContentDivID);
    
    if(this.LoadingDiv == null)
      this.LoadingDiv = document.getElementById(this.LoadingDivID);
    
    if(this.UserMsg == null)
      this.UserMsg = document.getElementById(this.UserMsgID);

    this.KnowdeCommunityLinkID = null;
    this.HideOrShowLoadingDiv(false);
    // clear user message
    this.SetUserMsg('');
  };
  
  this.SetUserMsg = function(_message)
  {
    this.UserMsg.innerHTML = _message;
  };
  
  this.HideOrShowLoadingDiv = function(_show, _message, _messageOnly)
  {
    var div = this.LoadingDiv; 
    
    var message = _message;
    if(message == null)
      message = 'Deleting Link...';
    
    if (div != null)
    {
      if(_show != null && _show == true)
      {
        // clear the div
        div.innerHTML = '';
        
        if (!_messageOnly)
          div.innerHTML = "<img src='Images/LoadingBar.gif' width='21px' height='21px'/>&nbsp;";
        
        div.innerHTML += message;
        div.style.display = 'block';
        
        // hide the content
        this.ContentDiv.style.display = 'none';
      }
      else if(div.style.display != 'none')
      {
        div.style.display = 'none';
        div.innerHTML = '';
        
        // reset the content display style
        this.ContentDiv.style.display = '';
      }
    }
  };

  this.CallbackTrigger = function(_args)
  {
    // Construct the callback arguments
    if(_args != null)
    { 
      var args = _args;
      
      if(args.length > 0)
      {
        // show the loading div
        this.HideOrShowLoadingDiv(true);
        
        // trigger the callback
        eval(this.CallbackScript);
      }
    }
  };
  
  this.DeleteBtnClicked = function()
  {
    var args = 'Action=DeleteLink';
    args += '|KCLID=' + this.KnowdeCommunityLinkID;
    args += '|Context=' + this.ContextSelector.value;
    this.CallbackTrigger(args);
    
  };
}
// JScript File

function KGRatingControl_OnMouseOver(_star)
{
  var stars = _star.parentNode.getElementsByTagName('a');

  var hoverStarID = _star.getAttribute('starID'); // Get the selected star

  for (var index=0; index<stars.length; index++) // loop through all stars
  {
    var starID = stars[index].getAttribute('starID');
    if (starID > 0)
    {
      if (starID <= hoverStarID) // highlight the stars up to and including the one being mousedover
      {
        KGRatingControl_setStarStyle(stars[index], 'hover');
      }
      else // unhighlight the rest
      {
        if (stars[index].getAttribute('starRated') == 'true') // rated stars remain "on"
          KGRatingControl_setStarStyle(stars[index], 'on');
        else
          KGRatingControl_setStarStyle(stars[index], 'off');
      }
    }
  }
}

function KGRatingControl_UnrateMouseOver(_unrateDiv)
{
  var stars = _unrateDiv.parentNode.getElementsByTagName('a');
  for (var index=0; index<stars.length; index++) // loop through all stars
  {
    var starID = stars[index].getAttribute('starID');
    if (starID > 0) // unhighlight all stars
    {
      KGRatingControl_setStarStyle(stars[index], 'off');
    }
  }
}

function KGRatingControl_OnMouseOut(_star)
{
  var stars = _star.parentNode.getElementsByTagName('a');
  for (var index=0; index<stars.length; index++) // loop through all stars
  {
    var starID = stars[index].getAttribute('starID');
    if (starID > 0)
    {
      if (stars[index].getAttribute('starRated') == 'true') // rated stars remain "on"
        KGRatingControl_setStarStyle(stars[index], 'on');
      else
        KGRatingControl_setStarStyle(stars[index], 'off');
    }
  }
}

function KGRatingControl_StarClicked(_star)
{
  var stars = _star.parentNode.getElementsByTagName('a');
  
  var starRating = _star.getAttribute('starID'); // Get the selected star

  for (var index=0; index<stars.length; index++) // loop through all stars
  {
    var starID = stars[index].getAttribute('starID');
    if (starID > 0)
    {
      if (starID <= starRating) // set the starRated attribute for the stars up to and including the one clicked
      {
        KGRatingControl_setStarStyle(stars[index], 'hover');
        stars[index].setAttribute('starRated', 'true');
      }
      else // set to false for the rest
      {
        KGRatingControl_setStarStyle(stars[index], 'off');
        stars[index].setAttribute('starRated', 'false');
      }
    }
  }
  
  return starRating;
}

function KGRatingControl_setStarStyle(_star, _style)
{
  switch (_style)
  {
    case 'on':
      _star.className = 'KGRatingControl_StarOn';
      break;
    case 'off':
      _star.className = 'KGRatingControl_StarOff';
      break;
    case 'hover':
      _star.className = 'KGRatingControl_StarHover';
      break;
  }
}
var globalMyProfileTabLoaded;

function KGMyProfileTab_Activate()
{
  if (!globalMyProfileTabLoaded)
  {
    var args = "Action=Load";
    Pfl_KGMemberControl_CallbackTrigger(args);
    globalMyProfileTabLoaded = true; // doesn't need resetting until the page reloads
  }
}

function ShowUser_Wrapped(_personId, _pageLoad, _currentUserPersonId)
{
  if (_currentUserPersonId > 0 && _currentUserPersonId == _personId)
  {
    if(globalVisibleTab != 'TSC_myprofile')
      ChangeTab('myprofile');
  }
  else
  {
    if(globalVisibleTab != 'TSC_communities')
      ChangeTab('communities', 'Communities', false);
    
    // if this is from a page load, we need to setup the tab tool strip
    if(_pageLoad)
      ChangeTabToolStrip('communities');
    
    var extraRepopArgs = "PersonId=" + _personId;
    LoadCommunityTab("User", extraRepopArgs);
  }
}

function KGMemberControl_CallbackError(_args, _context)
{
  var alertMessage = "The KGMemberControl encountered an error. \n\n" + _args;
  alert(alertMessage);
}

function KGMemberControl_CallbackDone(_args, _context)
{
  // check for exceptions
  if (_args.indexOf("Exception") == 0 || _args.length == 0)
  {
    KGMemberControl_CallbackError(_args, _context);
    return;
    // looking for indexOf == 0 instead of > -1 incase it's genuine html that happens to contain 'Exception' in there
    // e.g. a user called "... Exceptional ..." 
  }

  // get the parameters
  var argsSplit = _args.split('[@|@]');
  var holderId = argsSplit[0];
  var javascripts = argsSplit[1];
  var htmlContent = argsSplit[2];
  
  //var retMsg = eval( '(' + json + ')' );
  //var holderId = retMsg.HolderId;
  
  var holder = document.getElementById(holderId);
  if (!holder)
  {
    KGCommunityControl_CallbackError('The holder doesn\'t exist ' + holderId);
    return;
  }
  
  // fill the control
  SetOuterHtml(holder, htmlContent);
  
  // eval any javascripts
  if (javascripts)
    eval(javascripts);
}

// KGSuggestionsControl JScript File
var global_SearchResult_ClickedItemID = 'none';


// CallbackTrigger Wapper for normal suggestion 
function KGSuggestionControl_CallbackTrigger_Wrapped(_searchPhrase, _searchPhraseKey, _cbreference, _srmIndex)
{
  //debugger;
  if(_searchPhrase != null && _searchPhrase.length)
  { 
    // filter special characters (number, leter and ')
    var iChars = "!@#$%^&*()+=-[]\\;,./{}|\":<>?";
    
    if(_searchPhrase=="\'")
       return;
    
    for (var si = 0; si < _searchPhrase.length; si++) 
    {
      var index1= iChars.indexOf(_searchPhrase.charAt(si));
  	  if (index1 != -1) 
  	    return;
  	}
  	
  }
  
  var args = _searchPhraseKey + '=' + _searchPhrase + '|SrmIndex=' + _srmIndex;
  
  if(_cbreference != null && _cbreference != "")
    eval(_cbreference);
}

// this will rerender table after call back
function KGSuggestionControl_CallbackDone_Wrapped(args, context, _suggestionTableID, _KGSuggestionControlDivId, _OverlaypositionCss, _ConceptTabbedViewHideOrShowControls)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
	HideBubble(false);
  var srmIndex;
  try
  {
    var argsSplit = args.split('[@|@]'); 
    srmIndex = argsSplit[1];
    args = argsSplit[0];
  }
  catch(e){}

  //debugger;
  if(args != '')
  {
    var holder = document.getElementById(_suggestionTableID)
    if(holder != null)
    {
      SetOuterHtml(holder, args);
	    document.getElementById(_KGSuggestionControlDivId).className= _OverlaypositionCss 
	    if(_ConceptTabbedViewHideOrShowControls != "" && _ConceptTabbedViewHideOrShowControls != null)
		    eval(_ConceptTabbedViewHideOrShowControls + '(0)');
	    try
	    {

		    SrmControl_RecordTimes(srmIndex);
	    }
	    catch(e){}
    }
    else
    {
      KGSuggestionControl_ProcessCallBackError('Suggestion Table not found in RegisterJavaScripts() of KGSuggestionControl.', '');
    }  
  }
}

// this will return message in case of error
function KGSuggestionControl_ProcessCallBackError_Wrapped(args, context, _thisClientID)
{
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    document.getElementById(_thisClientID).innerHTML = '<tr><td>An error has occurred in RegisterJavaScript() of KGSuggestionControl.</td></tr>';
  }
}

// CallbackTrigger Wapper for Knowde Suggestion
function KGSuggestionControl_CallbackTrigger_Knowde_Wrapped(_nounTerm, _verbTerm, _nounKey, _verbKey , _cbreference, _srmIndex)
{
  var args = _nounKey + '=' + _nounTerm + "|"+_verbKey + '=' + _verbTerm + '|SrmIndex=' + _srmIndex;
  
  if(_cbreference != null && _cbreference != "")
    eval(_cbreference);
}

// this will rerender table for knowde suggestion after call back
function KGSuggestionControl_CallbackDone_Knowde_Wrapped(args, context, _suggestionTableID, _KGSuggestionControlDivId, _OverlaypositionCss, _ConceptTabbedViewHideOrShowControls)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
  var srmIndex;
  var hasResult_Knowde = "0";
  try
  {
    var argsSplit = args.split('[@|@]'); 
    srmIndex = argsSplit[1];
    args = argsSplit[0];
    hasResult_Knowde = argsSplit[2];
  }
  catch(e){}

  //debugger;
  var holder = document.getElementById(_suggestionTableID)
  if(holder != null)
  {
	if(document.activeElement.id == "MapViewTextBox")
	{
		if((hasResult_Knowde != null && hasResult_Knowde == "1")) // TS: Fix bug 3088
		{
			SetOuterHtml(holder,args);
			document.getElementById(_KGSuggestionControlDivId).className= _OverlaypositionCss 
			if(_ConceptTabbedViewHideOrShowControls != "" && _ConceptTabbedViewHideOrShowControls != null)
				eval(_ConceptTabbedViewHideOrShowControls + '(0)');
			try
			{
      
				SrmControl_RecordTimes(srmIndex);
			}
			catch(e){}
		}
		else // need to hide the Suggestions Box
		{
			HideSuggestionsControl();
		}
	}
  }
  else
  {
    KGSuggestionControl_ProcessCallBackError('Suggestion Table not found in RegisterJavaScripts() of KGSuggestionControl.', '');
  }  
}

// this will return message for knowde suggestion in case of error
function KGSuggestionControl_ProcessCallBackError_Knowde_Wrapped(args, context, _thisClientID)
{
  // Here we are dealing with authentication timeout before callback, 
  // the message from the server is 'elogin' signify an error with 
  // authentication. The response will be trimmed to form the args 
  // 'login' here..... 
  if(args == 'login')
  {
    window.location='home.aspx';
  }
  else
  {
    document.getElementById(_thisClientID).innerHTML = '<tr><td>An error has occurred in RegisterJavaScript() of KGSuggestionControl for Knowde Suggestion.</td></tr>';
  }
}

// Hide SuggestionControl Java Script Handler
function HideSuggestionsControl_Wrapped(_KGSuggestionControlDivId, _overlayPositionHidden_CSSClass, _ConceptTabbedViewHideOrShowControls)
{
  //debugger;
  if(_KGSuggestionControlDivId != null && document.getElementById(_KGSuggestionControlDivId) != null)
  {
    if (document.getElementById(_KGSuggestionControlDivId).className !=_overlayPositionHidden_CSSClass)
    {  
			//Only need to hide it if it isn't already hidden?
			// hide the droplists for earlier IE versions
			if(navigator.appVersion.match("MSIE 7.0") != "MSIE 7.0")
			{
				ShowDropLists();
			}
      document.getElementById(_KGSuggestionControlDivId).className=_overlayPositionHidden_CSSClass;
      if (typeof SetFocusToDefaultElement != "undefined")
        eval(SetFocusToDefaultElement); //Bug 2234.
    }
    if (_ConceptTabbedViewHideOrShowControls != "" && _ConceptTabbedViewHideOrShowControls != null)
      eval(_ConceptTabbedViewHideOrShowControls + '(1)');
  }
}

// OnClick event handler in Table Row <tr>
function KGSuggestionControl_onTableRowClickHandler_Wrapped(_selectedConceptId, _highlightedConceptId, _ITEMCONTEXT_CSSCLASS, _CONTEXT_SEPARATOR, _PARENTCONTEXT_SEPARATOR, _thisCallBackMethod, _redirectUrl, _ConceptTabbedViewCallBack, _srmIndex, _rootConceptName, _domainName, e)
{
  if (window.CloseApplicationControl && m_applicationControlOpen && !m_appForceOpen)
  {
    CloseApplicationControl();
  }
	SetSessionProperty("SuggestionClick", "true");
	var el;
	if(e)
	{
		el = e.target || e.srcElement;
  }
  else
  {
		el = this.event.target || this.event.srcElement;
  }
  if(el != null && el.className == _ITEMCONTEXT_CSSCLASS)
  {
    el = el.parentNode;
  }
  if(el != null && el.innerHTML !=null)
  {
    // Fix Bug 3465
    // using title which holds the tooltip of table cell
    var rootPhraseName = '';
    var searchPhrase = el.title;
    SetSessionProperty('SearchContextTextBool', "true");
    SetSessionProperty('SearchContextText', el.innerText);
    if(searchPhrase != null && searchPhrase !='')
    {
        var index1 = searchPhrase.indexOf(_CONTEXT_SEPARATOR);
        var index2 = searchPhrase.lastIndexOf(_PARENTCONTEXT_SEPARATOR);
        if(index1 > 0)
        {
          var originalSearchPhrase = searchPhrase;
          var stringLength = originalSearchPhrase.length;
          searchPhrase = searchPhrase.substring(0, index1);
          if(index2 < 0) // word - word1
          {
             if(stringLength > index1+1)
               rootPhraseName = originalSearchPhrase.substring(index1+1, stringLength);
          }
          else // word - word1, word2
          {
             var startIndex2 = index2+_PARENTCONTEXT_SEPARATOR.length
             if(stringLength > startIndex2)
               rootPhraseName = originalSearchPhrase.substring(startIndex2, stringLength);
          }
        }
        else
        {
          // No contexts in searchPhrase
          rootPhraseName = searchPhrase;
        }
    }
    else // using inner html when title(tooltip) is null
    {
        searchPhrase = el.innerHTML;
        var index1 = searchPhrase.indexOf(_CONTEXT_SEPARATOR);
        if(index1 > 0)
        {
          searchPhrase = searchPhrase.substring(0, index1);
          // Get root display phrase for display as title and tab text
          rootPhraseName = el.innerHTML.substring(index1 + _CONTEXT_SEPARATOR.length);
          var indexc1 = rootPhraseName.lastIndexOf(_PARENTCONTEXT_SEPARATOR);
          var indexc2 = rootPhraseName.lastIndexOf('<');
          var indexc3 = rootPhraseName.indexOf('>');
          if(indexc1 > 0 && indexc2 > 0)
          {
            rootPhraseName = rootPhraseName.substring(indexc1 + _PARENTCONTEXT_SEPARATOR.length, indexc2);
          }
          else if(indexc1 <= 0 && indexc3 > 0 && indexc2 > 0 && indexc2 > indexc3)
          {
            rootPhraseName = rootPhraseName.substring(indexc3+1, indexc2);
          }else
          {
            rootPhraseName = searchPhrase;
          }
        }
        else
        {
          // No contexts in searchPhrase
          rootPhraseName = searchPhrase;
        }    
    }
    
    
    // store in session

    // test only 
    SetSessionProperty('SearchResult_SearchRootPhraseName', rootPhraseName);
    var keys = 'SearchResultTreeViewRootNode|SelectedKnowdeSiblingInfo|KGSuggestion_SearchKeywords';
	  var values = _selectedConceptId + '||';
    SetSessionProperty(keys, values, true);
    /*SetSessionProperty('SearchResultTreeViewRootNode', _selectedConceptId);
    // new default map will be load, clear old session
    SetSessionProperty('SelectedKnowdeSiblingInfo', '');	
    SetSessionProperty('KGSuggestion_SearchKeywords','');*/
    
    
    if (window.SearchResult_ResetTreeScrollingVariables)
      SearchResult_ResetTreeScrollingVariables();
        
		if(el.title == "Domains Table")
			searchPhrase = _rootConceptName;
			
    // Set searchPhrase of KGSearchTextBox by calling KGSearchTextBox Trigger
    // the searchphrase.replace(/\'/g, "\\" + "\'") replaces an apostrophe, with it's escape character ("'" becomes "\'")
    // the "g" ensures all occurances of the apostrophe are replaced rather than just the first.
    eval(_thisCallBackMethod + '(\'' + searchPhrase.replace(/'/g, "\\" + "\'") + '\');');
    
    // Call ConceptTabbedView CallBack Trigger
    var itemCellId = el.id;
    var itemKey = '0';
    var itemType = '0';
    var itemName = '';
    var hightlightedConceptId = '-1';
    var selectedConceptKnowdeId = '-1';
    
    // Get Hightlighted Concept Id
    if(_highlightedConceptId != null && _highlightedConceptId != '')
    {
      var kcindex = _highlightedConceptId.indexOf('-');
      if(kcindex != -1)
      {
        hightlightedConceptId = _highlightedConceptId.substring(0, kcindex);
        selectedConceptKnowdeId = _highlightedConceptId;
      }else{
        hightlightedConceptId = _highlightedConceptId;
        selectedConceptKnowdeId = _highlightedConceptId;
      }
    }
    
    if(itemCellId != null)
    {
      var itemValues = itemCellId.split(_CONTEXT_SEPARATOR);
      if(_selectedConceptId != null && _selectedConceptId !='' && _selectedConceptId != '-1')
        itemKey = _selectedConceptId;
      else if(itemValues!=null && itemValues[0]!=null)
        itemKey = itemValues[0];
      if(itemValues!=null && itemValues[1]!=null)
        itemType = itemValues[1];
      if(itemValues!=null && itemValues[2]!=null)
        itemName = itemValues[2];
    }
    if(itemName == "")
			itemName = _rootConceptName;
    var currentLocation = window.location.href;
    var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
    var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
    
    // add the new selected concept knowde id
    var selectedItemValueString = itemKey + '|' + itemName + '|' + selectedConceptKnowdeId; // rootId|itemName|conceptId-knowdeId

    var keys = 'PageSession_HighlightedConceptId|PageSession_KGSelectedConceptID|SearchResult_NewRootConceptID|HideSearchResultItemInfo|KGShowResultsTab|KGHideSemanticTreeCheckBox|SearchResult_ClickedItemID';
	  var values = hightlightedConceptId + '|' + selectedConceptKnowdeId + '|-1|false|true|false|' + itemKey;
    SetSessionProperty(keys, values, true);

    SetSessionProperty('SearchResultItemClickInfo', selectedItemValueString); 
    
    /*SetSessionProperty('PageSession_HighlightedConceptId', hightlightedConceptId);
    // Set the highlighted concept as the selected concept
    SetSessionProperty('PageSession_KGSelectedConceptID', selectedConceptKnowdeId);  
    SetSessionProperty('SearchResult_NewRootConceptID', -1); // clear tree focus status
    
    SetSessionProperty('HideSearchResultItemInfo', 'false');
    
    //SetSessionProperty('ConceptTabbedView_SelectedTab', 'Results');
    SetSessionProperty('KGShowResultsTab', 'true');
    SetSessionProperty('KGHideSemanticTreeCheckBox',false);
    SetSessionProperty('SearchResult_ClickedItemID', itemKey);*/
    SetSessionProperty('CurrentDomain', _domainName);  //For domain indicator (task 2865)*/
     
    global_SearchResult_ClickedItemID = itemKey;
    
    
    // switch tab
    if (window.KGNavigationControl_SwitchTabs)
      KGNavigationControl_SwitchTabs('Results', rootPhraseName);
    else
    {
      SetSessionProperty('ConceptTabbedView_SelectedTab', 'Results');
      global_ConceptTabbedControl_CurrentlySelectedTab = 'Results';
      SetSessionProperty('KGNavigationControl_SemanticTreeTitleSubFix', rootPhraseName.replace('&','%26'));
    }
    
    SetSessionProperty('IndexedDocListMode', 'IndexedDocuments');

    if (_redirectUrl != "" && _redirectUrl != null)
    {
      // need redirection

      SetSessionProperty('PageSession_LibrarySelectedItemID', itemKey);
      SetSessionProperty('PageSession_LibrarySelectedItemTypeID', itemType);
      SetSessionProperty('PageSession_LibrarySelectedItemName', itemName);
      try
      {
        if (m_srmGetTimes!= null && m_srmGetTimes == "True" && _srmIndex != null)
        {
          SetSessionProperty('Srm_T0', m_srmT0[_srmIndex]);
          SetSessionProperty('Srm_Action', m_srmAction[_srmIndex] + "," + currentPage + "," + searchPhrase + "," + _selectedConceptId);
          SetSessionProperty('Srm_Callbacks', 1);
        }
      } catch(ex){}
      window.location = hostURL + _redirectUrl;

    }
    else
    {
      // callback
      try
      {
        if (m_srmGetTimes!= null && m_srmGetTimes == "True" && _srmIndex != null)
        {
          m_srmCallbacks[_srmIndex] = 2;
          m_srmAction[_srmIndex] += "," + currentPage + "," + searchPhrase + "," + _selectedConceptId;
        }
      } catch(ex){}
        
      if (window.CancelEdit)
        CancelEdit(true);
      
      // escape all occurrences of apostrophe in item and rootPhraseNames
      rootPhraseName.replace(/'/g, "\\" + "\'");
      itemName.replace(/'/g, "\\" + "\'");
      rootPhraseName.replace(/'/g, "")
      eval(_ConceptTabbedViewCallBack + '(\'' + itemKey + '\',\'' + itemType + '\',\'' + itemName + '\', \'' + rootPhraseName + '\', _srmIndex);');
    }
  }
  else
  {
    alert('The searchPhrase is null!');
  }
}

function KGSuggestionControl_ExternalSearchClick_Wrapper(_thisCallBackMethod, _redirectUrl, _ConceptTabbedViewCallBack, _srmIndex)
{
		SetSessionProperty("SuggestionClick", "true");
    // new default map will be load, clear old session
    SetSessionProperty('SelectedKnowdeSiblingInfo', '');	

    if (window.SearchResult_ResetTreeScrollingVariables)
      SearchResult_ResetTreeScrollingVariables();
      
    SetSessionProperty('IndexedDocListMode', 'IndexedDocuments');
    // hide the semantic tree
    SetSessionProperty('KGNavigationControl_SemanticTreeVisible', false);

    var currentLocation = window.location.href;
    var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
    var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
   
    if (_redirectUrl != "" && _redirectUrl != null)
    {
      // need redirection
      SetSessionProperty('PageSession_KGSelectedConceptID', '0');
      SetSessionProperty('KGMapViewCollapsed',true);
      SetSessionProperty('KGHideSemanticTreeCheckBox',true);
      // set search phrase
      var searchBox = KGSearchControl1_GetSearchBox();
      var searchPhrase = '';
      if(searchBox != null && searchBox.value!=null && searchBox.value!='')
      {
         SetSessionProperty('KGSuggestion_SearchKeywords',searchBox.value);
         window.location = hostURL + _redirectUrl;
         
      }
      
    }

}

// OnClick event handler in Table Row for click on user <tr>
function KGSuggestionControl_onTableRowClickHandler_User_Wrapped(_userIdsString, _userName, _thisCallBackMethod, _redirectUrl)
{    
//debugger;
 
	 // new default map will be load, clear old session
	 var keys = 'SelectedKnowdeSiblingInfo|KGSuggestion_SearchKeywords';
	 var values = '|';
   SetSessionProperty(keys, values, true);

	 //SetSessionProperty('SelectedKnowdeSiblingInfo', '');	
	 //SetSessionProperty('KGSuggestion_SearchKeywords','');
    
  // Set searchPhrase of KGSearchTextBox by calling KGSearchTextBox Trigger
  // the searchphrase.replace(/\'/g, "\\" + "\'") replaces an apostrophe, with it's escape character ("'" becomes "\'")
  // the "g" ensures all occurances of the apostrophe are replaced rather than just the first.
  eval(_thisCallBackMethod + '(\'' + _userName.replace(/'/g, "\\" + "\'") + '\');');
  
  var currentLocation = window.location.href;
  var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
  var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
  
  if (_userIdsString.indexOf('|') < 0)
  {// there's only one user with that name
    var querystring = '?user=' + _userIdsString;
    window.location = hostURL + 'options.aspx' + querystring;
  }
  else
  {// more than one user share the name, go to multi user search page
    var keys = 'KG_RedirectFrom|KGMapViewCollapsed|RemoveSelectedConcept|IndexedDocListMode';
	  var values = 'KGSearchControl|true||IndexedDocuments';
    SetSessionProperty(keys, values, true);

    //SetSessionProperty('KG_RedirectFrom','KGSearchControl')
    SetSessionProperty('MultiUserSearchPage', _userName + '@' + _userIdsString);
    //SetSessionProperty('KGMapViewCollapsed', true);
    //SetSessionProperty('RemoveSelectedConcept', ''); // see SessionPropertiesAshxHandler.cs
    //SetSessionProperty('IndexedDocListMode', 'IndexedDocuments');
      
    /*if (window.KGTabbedWindowsControl_CallbackTrigger)//Check if we are on the map view page
    {//callback
      if (window.CancelEdit)
        CancelEdit(true);
      
      //DoCollapseMapViewPane();
      globalIndexedDocsPageLoaded = false;
      KGTabbedWindowsControl_CallbackTrigger('TabSelected, Indexed Documents');
      KGButtonToolbar_IndexedDocListLoaded(true);
    }
    else
    {//redirect to MapTabbedView page*/
      window.location = hostURL + _redirectUrl;
    //}
  }
}

// set up correct session variables so the result tree will auto expand the selected context
function KGSuggestionControl_PrepareTreeAutoExpand(_expandedNodes)
{
  // for result tree auto expansion
  SetSessionProperty('SearchResultsNodeStatus', _expandedNodes);
}

// OnClick event handler for seleting noun phrase of Knowde in MapView in Table Row <tr>
function KGSuggestionControl_onTableRowClickNounHandler_Wrapped(_CONTEXT_SEPARATOR, _CallBackMethod_KnowdeNoun, e)
{
  var el = e.target || e.srcElement;
  var itemCellId = null;
  var itemType = null;
  var nounTerm = null;
  var verbTerm = null;
  
  if(el != null )
    itemCellId = el.id;
    
  if(itemCellId != null)
  {
    var itemValues = itemCellId.split(_CONTEXT_SEPARATOR);
    // Cell ID: Key - Type - Noun - Verb
    if(itemValues != null && itemValues.length >= 4) 
    {
      if(itemValues!=null && itemValues[1]!=null)
        itemType = itemValues[1];
      if(itemValues!=null && itemValues[2]!=null)
        nounTerm = itemValues[2];
      if(itemValues!=null && itemValues[3]!=null)
        verbTerm = itemValues[3];
        
      if(itemType != null && itemType == "1"  && itemValues!=null && itemValues[2]!=null) 
      { // verb moved up because of noun is empty
        verbTerm = itemValues[2];
        nounTerm = null;
      }
        
    }
  }

  if(el != null)
  {
    if (itemType == null)
      itemType = '';
  
    if(nounTerm != null)
    {
      // to be continue..
      nounTerm = nounTerm.replace(/'/g, "\\" + "\'");
    }
    else
    {
      nounTerm = '';
    }
      
    if(verbTerm != null)
    {
      verbTerm = verbTerm.replace(/'/g, "\\" + "\'");
    }
    else
    {
      verbTerm = '';
    }
   
    if (itemType != null && (verbTerm != '' || nounTerm !='' ) )
    {
     // Set Noun Phrase of Selected Knowde in MapView by calling SetKnowdeNounMapView javascript
     eval(_CallBackMethod_KnowdeNoun + '(\'' + itemType +'\',\''+ nounTerm + '\',\'' + verbTerm + '\');');
    }
    
    // Hide Suggestion Control
    HideSuggestionsControl();
  }
  else
  {
    alert('The searchPhrase is null!');
  }
}

