// 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;  

// payment costs
var GlobalUSDCost = 3;
var GlobalEURCost = 2.2;
var GlobalGBPCost = 1.95;
var globalPreviousUserMonthCostOnIncreaseControl;
var globalGroupId = -1;
// 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;
// whether to use old-style verb-noun knowdes instead of new style free text
var Map_KnowdeTextStyle = "";

var globalHideDockButton = false;
var Active_KGID = ""; // must be predefined
var AnonEditLimitReached = false; // only an anonymous user can reach the anonymous edit limit
var AnonEditShowSignInWarningMsg = false; // whether to show the sign-in otherwise lose work warning message for anonymous user 
var HideAnonEditShowSignInWarningMsg = false; 
var MapViewJSLoaded = 0;

var mSignInControlDivId = "";
var mNewKGControlDivId = "";
var globalSplitterSetting = "single";
var globalFeaturedCategory;
var globalEditTimeOut = "";
var global_reloadApp = "true";
var _globalCookieTestResult = new Boolean(true);
var globalBrowserSessionSet = new Boolean(false);
var globalHideIndexedDocs = true;

var m_KGAuthorHelpLastStep = null;
var m_KGAuthorHelpAutoEnterStep = null;

var mvcCallbackTimeout;
var tabwinCallbackTimeout;

var m_catCookieExpiration = 8760; // cookie expiration date in hours from current time. 8760 = 1 year

var m_WHWSearchBoxDefaultText = 'Start WHY Coding';
var m_WHYCodingDefaultText = 'Start with an action';

var m_leftPaneBorderTop = 0; // this is used in JQuery UI javascript for the sortable portlet to work in IE when border top is set in our left pane container

/*********************************** Browser and Device Detection ***********************************************/
var global_agent = navigator.userAgent.toLowerCase();
var global_scrWidth = screen.width;
var global_scrHeight = screen.height;
// The document.documentElement dimensions seem to be identical to
// the screen dimensions on all the mobile browsers I've tested so far
var global_elemWidth = document.documentElement.clientWidth;
var global_elemHeight = document.documentElement.clientHeight;
// We need to eliminate Symbian, Series 60, Windows Mobile and Blackberry
// browsers for this quick and dirty check. This can be done with the user agent.
var global_otherBrowser = (global_agent.indexOf("series60") != -1) || (global_agent.indexOf("symbian") != -1) || (global_agent.indexOf("windows ce") != -1) || (global_agent.indexOf("blackberry") != -1);
// If the screen orientation is defined we are in a modern mobile OS
var global_mobileOS = typeof orientation != 'undefined' ? true : false;
// If touch events are defined we are in a modern touch screen OS
var global_touchOS = ('ontouchstart' in document.documentElement) ? true : false;
// iPhone and iPad can be reliably identified with the navigator.platform
// string, which is currently only available on these devices.
var global_iOS = (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPad") != -1) ? true : false;
// If the user agent string contains "android" then it's Android. If it
// doesn't but it's not another browser, not an iOS device and we're in
// a mobile and touch OS then we can be 99% certain that it's Android.
var global_android = (global_agent.indexOf("android") != -1) || (!global_iOS && !global_otherBrowser && global_touchOS && global_mobileOS) ? true : false;
if (IsXOOM() && window.location.href.toLowerCase().indexOf('welcome.aspx') != -1)
{
  var viewport = document.querySelector("meta[name=viewport]");
  viewport.setAttribute('content', 'width=device-width;');
}

function GetTouchX(e)
{
  var touchX = 0;
  if (global_touchOS == true)
  {
    e = (e || window.event);
    if (e != null)
    {
      if (e.type == 'touchend')
      {
        if (e.changedTouches)
        {
          var t = e.changedTouches[0];
          if (t != null)
            touchX = t.pageX;
        }
      } else
      {
        if (e.targetTouches)
        {
          var t = e.targetTouches[0];
          if (t != null)
            touchX = t.pageX;
        }
      }
    }
  }
  else
  {
    touchX = parseInt(YAHOO.util.Event.getPageX(e));
  }

  return touchX;
}

function GetTouchY(e)
{
  var touchY = 0;
  if (global_touchOS == true)
  {
    e = (e || window.event);
    if (e != null)
    {
      if (e.type == 'touchend')
      {
        if (e.changedTouches)
        {
          var t = e.changedTouches[0];
          if (t != null)
            touchY = t.pageY;
        }
      }
      else
      {
        if (e.targetTouches)
        {
          var t = e.targetTouches[0];
          if (t != null)
            touchY = t.pageY;
        }
      }
    }
  }
  else
  {
    touchY = parseInt(YAHOO.util.Event.getPageY(e));
  }

  return touchY;
}
/*----------------------------------------------------------------------------------------------------------------- */

var debugInfo = '';

function InitDebugInfo()
{
  debugInfo = '';
}

function LogDebugInfo(fnName, msg)
{
  // uncomment for debug
  // NOTE: Please make sure you reset the commentted out status back before you check in the code
  //debugInfo += ' | ' + fnName + ' ' + msg; 
}

function AlertDebugInfo(prefix, immediateAlert)
{
  if (prefix == null)
    prefix = ' ';
  // uncomment for debug
  // NOTE: Please make sure you reset the commentted out status back before you check in the code
  /*if (immediateAlert != null && immediateAlert == true)
    alert(prefix + debugInfo);
  else
    window.setTimeout('alert(' + prefix + debugInfo + ')', 2000);
  */
  debugInfo = '';

}
/*----------------------------------------------------------------------------------------------------------------- */

// 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 placeInVerbEdit = false;
var global_newKGCreated = false;
var global_NewKGCreatedEdited = false;
var global_newKGCreatedFromAnonymousEdit = false;
var global_newKGShowHelp = false;
var globalTempArgs = null;
var m_triggerMapCallbackOnload = false;
var m_triggerMapCallbackOnload_IsSet = false;
var m_mapViewCallBackWaitCount = 0;
var m_tabbedWindowCallBackWaitCount = 0;
var globalPreOpenLeftPane = false;
var globalHelpKG = null;

function Set_triggerMapCallbackOnload(_value)
{
  m_triggerMapCallbackOnload_IsSet = true;
  //m_triggerMapCallbackOnload = _value;
  if (_value == "true" || _value == true)
		m_triggerMapCallbackOnload = true;
	else
		m_triggerMapCallbackOnload = false;

}

function Set_CreateNewKGFromURL(_value)
{
  if (_value == "true" || _value == true)
		global_newKGCreated = true;
}

function PreOpenLeftPane(_value)
{
  if (_value == true || _value == "true")
	{
		// Open the Left Pane
		globalPreOpenLeftPane = true;
	}
}

function SetHelpKGJS(_helpKG)
{
	if(globalHelpKG == null)
		globalHelpKG = _helpKG;
}



// 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);", 300);

		if (window.howChainArrays && window.whyChainArrays && window.RecentreObjective && window.m_DragInProgress)
		{
		  if (m_DragInProgress == false && (howChainArrays.length == 1 && whyChainArrays.length == 1 && howChainArrays[0] == -1 && whyChainArrays[0] == -1))
		    setTimeout("RecentreObjective();", 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) {

  		//we are in here so we want to shut the right hand panel dont we?
  		if (SetMapPaneStatus != null)
  			SetMapPaneStatus("split");
  		// 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);
  		}
  	}
  	else {
  		if (SetMapPaneStatus !=null)
  			SetMapPaneStatus("applications");
  	}
  }
  
  
}

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(0);", 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 (keys[qsidx] == 'Topics_SelectedTopicGroupId') 
            {
                if (values[qsidx] != null && values[qsidx] > -1)
                {
                    if (globalGroupId != values[qsidx]) 
                    {
                        globalGroupId = values[qsidx];
                        if (typeof (globalVisibleTab) != "undefined" && globalVisibleTab != null && globalVisibleTab != '') 
                        {
                          var ajaxargs = 'CurrentSelectedTab=' + globalVisibleTab + '|' + 'GroupId=' + values[qsidx];
//                          AppOptionsNavigationControl_CallbackTrigger(ajaxargs);
                        }
                    }
                }
            }
            if(queryStrings.length > 0)
              queryStrings += '&';
            queryStrings += keys[qsidx] + '=' + values[qsidx];
          }
        }
      }
    }
    else {
        if (_strPropertyName == 'Topics_SelectedTopicGroupId')
        {
            if (_strValue != null && _strValue > -1) 
            {
                if (globalGroupId != _strValue) 
                {
                    globalGroupId = _strValue;
                    if (typeof(globalVisibleTab) != "undefined" && globalVisibleTab != null) 
                    {
                      var ajaxargs = 'CurrentSelectedTab=' + globalVisibleTab + '|' + 'GroupId=' + _strValue;
//                      AppOptionsNavigationControl_CallbackTrigger(ajaxargs);                      

                    }
                }
            }
        }    
    }      
    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)
{
  // append timestamp to prevent aggressive caching on certain browsers
  var localTime = new Date();
  var utc = localTime.getTime() + (localTime.getTimezoneOffset() * 60000);

  if (_url.indexOf('utc=') == -1)
  {
    if (_url.indexOf('?') == -1)
      _url += '?utc=' + utc;
    else
      _url += '&utc=' + utc;
  }

  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)
		{
			//SwitchToSplitView(false, true); //don't set the cookie 
			// the splitter is moved in Splitter1_onLoad
			// moving it twice fires two map view callbacks (performance, but also bugs due to global variables set incorrectly second time round)
			// Do I need to load and show the map view here
			
			ShowCorrectHomePageDiv();
			OpenKnowledgeTabPane(KnowledgePaneTab.KnowledgeGene);
			LoadInformationPaneContent();
			//if the pane is expanded and the map view is not editable, trigger map view callback
			if (m_bEditable == false && globalMapPaneOpen == true) {
				setTimeout('MapViewControl1_CallbackTrigger()', 1); // timeout for importScript
				globalMapViewControlLoaded = true;
			}
		}
		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 && globalMapPaneOpen == true)
			{
				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);
		  } 
		}
	}
  catch(e)
  {
		alert('LoadMapTabbedView() error');
  }
}

function TriggerMapViewCallBackTimeOut()
{
//  debugger;
  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;
//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")
  {
		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
    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();
          break;
        default:
          LoadMapTabbedView(); 
          initialiseOverlays();
          break;
      }
    }
    else
    {
      LoadMapTabbedView(); 
      initialiseOverlays(); 
    }
  }
  else
  {
    LoadMapTabbedView();
    initialiseOverlays();
  }
}

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 highlight_Link(e, _color, _id)
{
  if (!e) var e = window.event;
  var targ = e.target || e.srcElement;

  if (_id != null)
  	targ = document.getElementById(_id);

  if (_color)
  	targ.style.color = _color;
	targ.style.textDecoration = "underline";
}

function unhighlight_Link(e, _color, _id)
{
  if (!e) var e = window.event;
  var targ = e.target || e.srcElement;

  if (_id != null)
  	targ = document.getElementById(_id);

	if(_color)
		targ.style.color = _color; //back to css default
	targ.style.textDecoration = "none";
}

var globalHoverUpdateTimerDelay = 400;

function importScript(_fileName)
{

  var folderPath = 'JavaScript/';
  var scripts;
  var headerEle = document.getElementsByTagName("head");
  if (headerEle != null && headerEle.length > 0)
    scripts = headerEle[0].getElementsByTagName("script");
  if (scripts != null && scripts.length > 0)
  {
    for (var idx = 0; idx < scripts.length; idx++)
    {
      if (scripts[idx].src.length > 0
        && (scripts[idx].src.toLowerCase().indexOf('/javascript') != -1 || scripts[idx].src.toLowerCase().indexOf('javascript') == 0)
        && scripts[idx].src.toLowerCase().lastIndexOf('.js') == (scripts[idx].src.length - 3))
      {
        var currentLocation = scripts[idx].src;
        folderPath = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
        break;
      }
    }
  }
  //alert(folderPath);
  
  var tag = document.createElement("script");
  tag.type="text/javascript";
  tag.src = folderPath + _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



// 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();
  }
}

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)
{
  var success = false;
  if (!_el)
    return;
  
  if (_el.outerHTML)
  {
    try
    {
      _el.outerHTML = _html;
      success = true;
    }
    catch(ex)
    {
      success = false;
    }
  }
  
  if (!success)
  {
    if (!_el.parentNode)
      return;
    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)
  {
    //debugger;
    // clear cookies
    // path must be set to erase it - '/' means all pages, and matches what was set with the cookie at the server
    // setting a blank cookie isn't right - it adds another one with a blank value, 
    //    then if the session times out again, set the cookie to true at the server - but the blank one is still there
    //    and we read the blank one here (check document.cookie)
    
    // WM_killCookie('SignedIn', '/');  // should only remove this cookie if we also sign out the user, otherwise you get odd bugs later on
                                        // if they have remember me set then the user stays signed in (or rather is re-signed in) 
    WM_killCookie('sessionExpired', '/'); // remove it so it doesn't get read again later
    
    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)
{
//debugger;
  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 = !globalMapPaneOpen; //if false or null then map is visible
//	    if (!mapCollapsed) 
//	      mapVisible = true;
//	  }
		//

		mapVisible = globalMapPaneOpen;
		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.indexOf("myprofile") != -1)
      profileTab = "Profile";
    else if (globalVisibleTab.indexOf("communities") != -1 && 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;
//        }
    	//      }
    	profileVisible = (globalVisibleTab.indexOf("myprofile") != -1);
    }
	}
	
	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.indexOf("communities") != -1 && window.Com_KGProfileHeaderControl_GetMemberNameControlId)
          memberNameCtlId = Com_KGProfileHeaderControl_GetMemberNameControlId();
        else if (globalVisibleTab.indexOf("myprofile") != -1 && 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.indexOf("communities") != -1 && window.Com_GetSelectedProfileId)
    selectedProfileID = Com_GetSelectedProfileId();
  else if (globalVisibleTab.indexOf("myprofile") != -1 && 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/////////////////////////////////////////////////////////////////////////////////////////////////////

function showMore(_type)
{
	switch(_type)
	{
		case "Lead":
			document.getElementById("ShowMoreLeadership").style.display = "none";
			document.getElementById("MoreLeadership").style.display = "block";
			break;
		case "Info":
			document.getElementById("ShowMoreInfo").style.display = "none";
			document.getElementById("MoreInfo").style.display = "block";
			break;
		case "Ops":
			document.getElementById("ShowMoreOps").style.display = "none";
			document.getElementById("MoreOps").style.display = "block";
			break;
		case "Proj":
			document.getElementById("ShowMoreProj").style.display = "none";
			document.getElementById("MoreProj").style.display = "block";
			break;
	}
}

function showLess(_type)
{
	switch(_type)
	{
		case "Lead":
			document.getElementById("ShowMoreLeadership").style.display = "block";
			document.getElementById("MoreLeadership").style.display = "none";
			break;
		case "Info":
			document.getElementById("ShowMoreInfo").style.display = "block";
			document.getElementById("MoreInfo").style.display = "none";
			break;
		case "Ops":
			document.getElementById("ShowMoreOps").style.display = "block";
			document.getElementById("MoreOps").style.display = "none";
			break;
		case "Proj":
			document.getElementById("ShowMoreProj").style.display = "block";
			document.getElementById("MoreProj").style.display = "none";
			break;
	}
}

function PreSignOutCheck()
{
  // set this cookie so we know that the user has clicked 'sign out'
  //    written over in MembershipLeftHandHeader LoginStatus_LoggedOut (if it makes it that far - might not do if the session has timed out)
  //    read in global.asax.cs Session_Start to test the logging out status, related to session timeout
  WM_setCookie("HKLoggingOut", "Clicked", null, '/'); // set path = '/' so it can be used at the server as well

  return true;
}

/////////////////// CATEGORIES CODE /////////////////////////

var globalCatDelayTime = 600;
var globalCatHoverDelayList;
var globalCatHoverDelayLead;
var globalCatHoverDelayInfo;
var globalCatHoverDelayOps;
var globalCatHoverDelayProj;

function showCategory(_type)
{
	clearTimeout(globalCatHoverDelayList);

  var inWelcome = false;
  /*if ( window.location.href.toLowerCase().indexOf("welcome.aspx") != -1 )
    inWelcome = true;*/
  
  var examplesDivPos = null;
  
  if ( inWelcome == true )
  {
    examplesDivPos = findElementCoords(document.getElementById("ExamplesDiv"));
    
    if ( globalLeftPaneOpen == true )
    {
			document.getElementById("CategoriesList").style.top = examplesDivPos[1] - 86
			document.getElementById("CategoriesList").style.left = examplesDivPos[0]+ 64 - 275;  
		}
		else
		{
			document.getElementById("CategoriesList").style.top = examplesDivPos[1] - 86;
			document.getElementById("CategoriesList").style.left = examplesDivPos[0] + 64;  		
		}

	}


	$(".list_item_category").hover(function ()
	{
		$(this).css("background-color", "#E9EFF9");
		$(this).css("text-decoration", "none");
	},
    function ()
    {
    		$(this).css("background-color", "white");
    }
    );

  
	switch(_type)
	{
		case "Process":
			clearTimeout(globalCatHoverDelayLead);
			if(document.getElementById("CategoriesList") != null)
				document.getElementById("CategoriesList").style.display = "block";

			document.getElementById("ProcessCat").style.display = "block";			

			document.getElementById("LeadershipCat").style.display = "none";
			document.getElementById("ComplianceCat").style.display = "none";
			document.getElementById("LearningCat").style.display = "none";
			document.getElementById("WorkCat").style.display = "none";
			document.getElementById("LifeCat").style.display = "none";
			document.getElementById("MapsCat").style.display = "none";
			document.getElementById("ITCat").style.display = "none";
			
			if ( inWelcome == true )
			{
				if ( globalLeftPaneOpen == false )
				{
					document.getElementById("ProcessCat").style.top = examplesDivPos[1] - 190;  	
  				document.getElementById("ProcessCat").style.left = examplesDivPos[0] + 210;  			
  			}
  			else
  			{
					document.getElementById("ProcessCat").style.top = examplesDivPos[1] - 190;  	
  				document.getElementById("ProcessCat").style.left = examplesDivPos[0] + 210 - 273;  			  			
  			}
  	  }

  		break;
  	case "Leadership":
  		//debugger;
  		clearTimeout(globalCatHoverDelayLead);
  		if (document.getElementById("CategoriesList") != null)
  			document.getElementById("CategoriesList").style.display = "block";

  		document.getElementById("LeadershipCat").style.display = "block";
  		document.getElementById("ProcessCat").style.display = "none";
  		document.getElementById("ComplianceCat").style.display = "none";
  		document.getElementById("LearningCat").style.display = "none";
  		document.getElementById("WorkCat").style.display = "none";
  		document.getElementById("LifeCat").style.display = "none";
  		document.getElementById("MapsCat").style.display = "none";
  		document.getElementById("ITCat").style.display = "none";

  		if (inWelcome == true)
  		{
  			if (globalLeftPaneOpen == false)
  			{
  				document.getElementById("LeadershipCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("LeadershipCat").style.left = examplesDivPos[0] + 210;
  			}
  			else
  			{
  				document.getElementById("LeadershipCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("LeadershipCat").style.left = examplesDivPos[0] + 210 - 273;
  			}
  		}

  		break;

  	case "Compliance":
  		//debugger;
  		clearTimeout(globalCatHoverDelayLead);
  		if (document.getElementById("CategoriesList") != null)
  			document.getElementById("CategoriesList").style.display = "block";

  		document.getElementById("ComplianceCat").style.display = "block";
  		document.getElementById("ProcessCat").style.display = "none";
  		document.getElementById("LeadershipCat").style.display = "none";
  		document.getElementById("LearningCat").style.display = "none";
  		document.getElementById("WorkCat").style.display = "none";
  		document.getElementById("LifeCat").style.display = "none";
  		document.getElementById("MapsCat").style.display = "none";
  		document.getElementById("ITCat").style.display = "none";

  		if (inWelcome == true)
  		{
  			if (globalLeftPaneOpen == false)
  			{
  				document.getElementById("ComplianceCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("ComplianceCat").style.left = examplesDivPos[0] + 210;
  			}
  			else
  			{
  				document.getElementById("ComplianceCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("ComplianceCat").style.left = examplesDivPos[0] + 210 - 273;
  			}
  		}

  		break;


  	case "Learning":
  		//debugger;
  		clearTimeout(globalCatHoverDelayLead);
  		if (document.getElementById("CategoriesList") != null)
  			document.getElementById("CategoriesList").style.display = "block";

  		document.getElementById("LearningCat").style.display = "block";
  		document.getElementById("ProcessCat").style.display = "none";
  		document.getElementById("LeadershipCat").style.display = "none";
  		document.getElementById("ComplianceCat").style.display = "none";
  		document.getElementById("WorkCat").style.display = "none";
  		document.getElementById("LifeCat").style.display = "none";
  		document.getElementById("MapsCat").style.display = "none";
  		document.getElementById("ITCat").style.display = "none";

  		if (inWelcome == true)
  		{
  			if (globalLeftPaneOpen == false)
  			{
  				document.getElementById("LearningCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("LearningCat").style.left = examplesDivPos[0] + 210;
  			}
  			else
  			{
  				document.getElementById("LearningCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("LearningCat").style.left = examplesDivPos[0] + 210 - 273;
  			}
  		}

  		break;

  	case "Work":
  		//debugger;
  		clearTimeout(globalCatHoverDelayLead);
  		if (document.getElementById("CategoriesList") != null)
  			document.getElementById("CategoriesList").style.display = "block";

  		document.getElementById("WorkCat").style.display = "block";
  		document.getElementById("ProcessCat").style.display = "none";
  		document.getElementById("LeadershipCat").style.display = "none";
  		document.getElementById("ComplianceCat").style.display = "none";
  		document.getElementById("LearningCat").style.display = "none";
  		document.getElementById("LifeCat").style.display = "none";
  		document.getElementById("MapsCat").style.display = "none";
  		document.getElementById("ITCat").style.display = "none";

  		if (inWelcome == true)
  		{
  			if (globalLeftPaneOpen == false)
  			{
  				document.getElementById("WorkCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("WorkCat").style.left = examplesDivPos[0] + 210;
  			}
  			else
  			{
  				document.getElementById("WorkCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("WorkCat").style.left = examplesDivPos[0] + 210 - 273;
  			}
  		}

  		break;


  	case "Life":
  		//debugger;
  		clearTimeout(globalCatHoverDelayLead);
  		if (document.getElementById("CategoriesList") != null)
  			document.getElementById("CategoriesList").style.display = "block";

  		document.getElementById("LifeCat").style.display = "block";
  		document.getElementById("ProcessCat").style.display = "none";
  		document.getElementById("LeadershipCat").style.display = "none";
  		document.getElementById("ComplianceCat").style.display = "none";
  		document.getElementById("LearningCat").style.display = "none";
  		document.getElementById("WorkCat").style.display = "none";
  		document.getElementById("MapsCat").style.display = "none";
  		document.getElementById("ITCat").style.display = "none";

  		if (inWelcome == true)
  		{
  			if (globalLeftPaneOpen == false)
  			{
  				document.getElementById("LifeCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("LifeCat").style.left = examplesDivPos[0] + 210;
  			}
  			else
  			{
  				document.getElementById("LifeCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("LifeCat").style.left = examplesDivPos[0] + 210 - 273;
  			}
  		}

  		break;
  	case "Maps":
  		//debugger;
  		clearTimeout(globalCatHoverDelayLead);
  		if (document.getElementById("CategoriesList") != null)
  			document.getElementById("CategoriesList").style.display = "block";

  		document.getElementById("MapsCat").style.display = "block";
  		document.getElementById("ProcessCat").style.display = "none";
  		document.getElementById("LeadershipCat").style.display = "none";
  		document.getElementById("ComplianceCat").style.display = "none";
  		document.getElementById("LearningCat").style.display = "none";
  		document.getElementById("WorkCat").style.display = "none";
  		document.getElementById("LifeCat").style.display = "none";
  		document.getElementById("ITCat").style.display = "none";

  		if (inWelcome == true)
  		{
  			if (globalLeftPaneOpen == false)
  			{
  				document.getElementById("MapsCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("MapsCat").style.left = examplesDivPos[0] + 210;
  			}
  			else
  			{
  				document.getElementById("MapsCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("MapsCat").style.left = examplesDivPos[0] + 210 - 273;
  			}
  		}

  		break;

  	case "IT":
  		//debugger;
  		clearTimeout(globalCatHoverDelayLead);
  		if (document.getElementById("CategoriesList") != null)
  			document.getElementById("CategoriesList").style.display = "block";

  		document.getElementById("ITCat").style.display = "block";
  		document.getElementById("ProcessCat").style.display = "none";
  		document.getElementById("LeadershipCat").style.display = "none";
  		document.getElementById("ComplianceCat").style.display = "none";
  		document.getElementById("LearningCat").style.display = "none";
  		document.getElementById("WorkCat").style.display = "none";
  		document.getElementById("LifeCat").style.display = "none";
  		document.getElementById("MapsCat").style.display = "none";

  		if (inWelcome == true)
  		{
  			if (globalLeftPaneOpen == false)
  			{
  				document.getElementById("ITCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("ITCat").style.left = examplesDivPos[0] + 210;
  			}
  			else
  			{
  				document.getElementById("ITCat").style.top = examplesDivPos[1] - 190;
  				document.getElementById("ITCat").style.left = examplesDivPos[0] + 210 - 273;
  			}
  		}

  		break;


		case "Info":
			clearTimeout(globalCatHoverDelayInfo);
			if(document.getElementById("CategoriesList") != null)
				document.getElementById("CategoriesList").style.display = "block";
				
			document.getElementById("LeadershipCat").style.display = "none";
			document.getElementById("OperationsCat").style.display = "none";
			document.getElementById("InfoSystemsCat").style.display = "block";
			document.getElementById("LifeCat").style.display = "none";
			
			if ( inWelcome == true )
			{

				if ( globalLeftPaneOpen == false )
				{
					document.getElementById("InfoSystemsCat").style.top = examplesDivPos[1] - 130;
  				document.getElementById("InfoSystemsCat").style.left = examplesDivPos[0] + 210;
  		  }
  		  else
  		  {  		  
					document.getElementById("InfoSystemsCat").style.top = examplesDivPos[1] - 130;
  				document.getElementById("InfoSystemsCat").style.left = examplesDivPos[0] + 210 - 273;
  		  }  			
  
  	  }			
			
			break;
		case "Ops":
			clearTimeout(globalCatHoverDelayOps);
			if(document.getElementById("CategoriesList") != null)
				document.getElementById("CategoriesList").style.display = "block";
								
			document.getElementById("LeadershipCat").style.display = "none";
			document.getElementById("OperationsCat").style.display = "block";
			document.getElementById("InfoSystemsCat").style.display = "none";
			document.getElementById("LifeCat").style.display = "none";
			
			if ( inWelcome == true )
			{
				if ( globalLeftPaneOpen == false )
				{
					document.getElementById("OperationsCat").style.top = examplesDivPos[1] - 170;		
  				document.getElementById("OperationsCat").style.left = examplesDivPos[0] + 210;			
  			}
  			else
  			{
					document.getElementById("OperationsCat").style.top = examplesDivPos[1] - 170;		
  				document.getElementById("OperationsCat").style.left = examplesDivPos[0] + 210 - 273;			
  			}
  	  }  			
			
			break;
		case "Proj":
			clearTimeout(globalCatHoverDelayProj);
			if(document.getElementById("CategoriesList") != null)
				document.getElementById("CategoriesList").style.display = "block";
								
			document.getElementById("LeadershipCat").style.display = "none";
			document.getElementById("OperationsCat").style.display = "none";
			document.getElementById("InfoSystemsCat").style.display = "none";
			document.getElementById("LifeCat").style.display = "block";
			
			if ( inWelcome == true )
			{
				if ( globalLeftPaneOpen == false )
				{
					document.getElementById("LifeCat").style.top = examplesDivPos[1] - 150; 
  				document.getElementById("LifeCat").style.left = examplesDivPos[0] + 210; 			
  			}
  			else
  			{
					document.getElementById("LifeCat").style.top = examplesDivPos[1] - 150; 
  				document.getElementById("LifeCat").style.left = examplesDivPos[0] + 210 - 273; 			
  			}
  	  } 			
			
			break;
		case "LearnMore":
			document.getElementById("LearnMore").style.display = "block";
			$('.KGMapToolbar').css('height', '130px');
			break;
		case "List":
			document.getElementById("CategoriesList").style.display = "block";
			break;
	}
}

function hideCategory(_type)
{
	clearTimeout(globalCatHoverDelayList);
	switch(_type)
	{

		case "Process":
			globalCatHoverDelayLead = setTimeout("document.getElementById('ProcessCat').style.display = 'none';", globalCatDelayTime);
			if (document.getElementById('CategoriesList') != null)
			{
				globalCatHoverDelayList = setTimeout("document.getElementById('CategoriesList').style.display = 'none';", globalCatDelayTime);
			}
			break;

		case "Leadership":
			globalCatHoverDelayLead = setTimeout("document.getElementById('LeadershipCat').style.display = 'none';", globalCatDelayTime);
			if (document.getElementById('CategoriesList') != null)
			{
				globalCatHoverDelayList = setTimeout("document.getElementById('CategoriesList').style.display = 'none';", globalCatDelayTime);
			}
			break;

		case "Compliance":
			globalCatHoverDelayLead = setTimeout("document.getElementById('ComplianceCat').style.display = 'none';", globalCatDelayTime);
			if (document.getElementById('CategoriesList') != null)
			{
				globalCatHoverDelayList = setTimeout("document.getElementById('CategoriesList').style.display = 'none';", globalCatDelayTime);
			}
			break;

		case "Learning":
			globalCatHoverDelayLead = setTimeout("document.getElementById('LearningCat').style.display = 'none';", globalCatDelayTime);
			if (document.getElementById('CategoriesList') != null)
			{
				globalCatHoverDelayList = setTimeout("document.getElementById('CategoriesList').style.display = 'none';", globalCatDelayTime);
			}
			break;

		case "Work":
			globalCatHoverDelayLead = setTimeout("document.getElementById('WorkCat').style.display = 'none';", globalCatDelayTime);
			if (document.getElementById('CategoriesList') != null)
			{
				globalCatHoverDelayList = setTimeout("document.getElementById('CategoriesList').style.display = 'none';", globalCatDelayTime);
			}
			break;

		case "Life":
			globalCatHoverDelayLead = setTimeout("document.getElementById('LifeCat').style.display = 'none';", globalCatDelayTime);
			if (document.getElementById('CategoriesList') != null)
			{
				globalCatHoverDelayList = setTimeout("document.getElementById('CategoriesList').style.display = 'none';", globalCatDelayTime);
			}
			break;

		case "Maps":
			globalCatHoverDelayLead = setTimeout("document.getElementById('MapsCat').style.display = 'none';", globalCatDelayTime);
			if (document.getElementById('CategoriesList') != null)
			{
				globalCatHoverDelayList = setTimeout("document.getElementById('CategoriesList').style.display = 'none';", globalCatDelayTime);
			}
			break;

		case "IT":
			globalCatHoverDelayLead = setTimeout("document.getElementById('ITCat').style.display = 'none';", globalCatDelayTime);
			if (document.getElementById('CategoriesList') != null)
			{
				globalCatHoverDelayList = setTimeout("document.getElementById('CategoriesList').style.display = 'none';", globalCatDelayTime);
			}
			break;


		case "Lead":
			globalCatHoverDelayLead = setTimeout("document.getElementById('LeadershipCat').style.display = 'none';", globalCatDelayTime);
			if(document.getElementById('CategoriesList') != null)
			{
				globalCatHoverDelayList = setTimeout("document.getElementById('CategoriesList').style.display = 'none';", globalCatDelayTime);
			}
			break;
		case "Info":
			globalCatHoverDelayInfo = setTimeout("document.getElementById('InfoSystemsCat').style.display = 'none';", globalCatDelayTime);
			if(document.getElementById('CategoriesList') != null)
			{
				globalCatHoverDelayList = setTimeout("document.getElementById('CategoriesList').style.display = 'none';", globalCatDelayTime);
			}
			break;
		case "Ops":
			globalCatHoverDelayOps = setTimeout("document.getElementById('OperationsCat').style.display = 'none';", globalCatDelayTime);
			if(document.getElementById('CategoriesList') != null)
			{
				globalCatHoverDelayList = setTimeout("document.getElementById('CategoriesList').style.display = 'none';", globalCatDelayTime);
			}
			break;
		case "Proj":
			globalCatHoverDelayProj = setTimeout("document.getElementById('LifeCat').style.display = 'none';", globalCatDelayTime);
			if(document.getElementById('CategoriesList') != null)
			{
				globalCatHoverDelayList = setTimeout("document.getElementById('CategoriesList').style.display = 'none';", globalCatDelayTime);
			}
			break;
		case "LearnMore":
			document.getElementById('LearnMore').style.display = 'none';
			$('.KGMapToolbar').css('height', '30px');
			break;
		case "List":
			globalCatHoverDelayList = setTimeout("document.getElementById('CategoriesList').style.display = 'none';", globalCatDelayTime);
			break;
	}
}

function showMoreKGs(_type)
{
	switch(_type)
	{
				case "Process": 
					document.getElementById("ShowMoreProcessKGs").style.display = "none"; 
					document.getElementById("MoreProcessKGs").style.display = "block"; 
					break; 
				case "Leadership": 
					document.getElementById("ShowMoreLeadershipKGs").style.display = "none";
					document.getElementById("MoreLeadershipKGs").style.display = "block"; 
					break; 
				case "Compliance":
					document.getElementById("ShowMoreComplianceKGs").style.display = "none";
					document.getElementById("MoreComplianceKGs").style.display = "block"; 
					break; 
				case "Learning":
					document.getElementById("ShowMoreLearningKGs").style.display = "none";
					document.getElementById("MoreLearningKGs").style.display = "block";
				case "Work":
					document.getElementById("ShowMoreWorkKGs").style.display = "none";
					document.getElementById("MoreWorkKGs").style.display = "block";
					break;
				case "Life":
					document.getElementById("ShowMoreLifeKGs").style.display = "none";
					document.getElementById("MoreLifeKGs").style.display = "block";
					break;
				case "Maps":
					document.getElementById("ShowMoreMapsKGs").style.display = "none";
					document.getElementById("MoreMapsKGs").style.display = "block";
					break;
				case "IT":
					document.getElementById("ShowMoreITKGs").style.display = "none";
					document.getElementById("MoreITKGs").style.display = "block"; 
					break; 
	}
}

function showLessKGs(_type)
{
	switch(_type)
	{
		case "Process":
			document.getElementById("ShowMoreProcessKGs").style.display = "block";
			document.getElementById("MoreProcessKGs").style.display = "none";
			break;
		case "Leadership":
			document.getElementById("ShowMoreLeadershipKGs").style.display = "block";
			document.getElementById("MoreLeadershipKGs").style.display = "none";
			break;
		case "Compliance":
			document.getElementById("ShowMoreComplianceKGs").style.display = "block";
			document.getElementById("MoreComplianceKGs").style.display = "none";
			break;
		case "Learning":
			document.getElementById("ShowMoreLearningKGs").style.display = "block";
			document.getElementById("MoreLearningKGs").style.display = "none";
		case "Work":
			document.getElementById("ShowMoreWorkKGs").style.display = "block";
			document.getElementById("MoreWorkKGs").style.display = "none";
			break;
		case "Life":
			document.getElementById("ShowMoreLifeKGs").style.display = "block";
			document.getElementById("MoreLifeKGs").style.display = "none";
			break;
		case "Maps":
			document.getElementById("ShowMoreMapsKGs").style.display = "block";
			document.getElementById("MoreMapsKGs").style.display = "none";
			break;
		case "IT":
			document.getElementById("ShowMoreITKGs").style.display = "block";
			document.getElementById("MoreITKGs").style.display = "none";
			break; 
	}
}

function hideBottomPane()
{
	var bottomPane = document.getElementById("BottomPaneMessage_BottomPaneMessage");
	if(bottomPane != null)
		bottomPane.style.display = "none";
}

/*********************** Video JS ****************************/

var globalVideoLoaded = false;
var globalVideoLocation = "";
function ShowTheVideoContainer()
{
	// hide the overlay and stop the video.
	var container = document.getElementById("VideoContainer");
	var container2 = document.getElementById("VideoContainer1");
	if(container != null)
	{
		container.style.display = "block";
		container2.style.display = "block";
		container.style.zIndex = "999";
		container.style.position = "absolute";
		container.style.top = "100px";
		container.style.left = "50px";
	}
	
	var videoPlayer = document.getElementById("VideoContainer1_VideoContainerDiv")
	if(videoPlayer != null)
	{
		if(globalVideoLoaded == false)
		{
		// Dynamically create the video link etc... 
		var dynamicDiv = document.createElement("div");
		dynamicDiv.innerHTML = "<a href='" + globalVideoLocation + "' style='display:block;width:425px;height:300px;' id='player'></a>";
		videoPlayer.innerHTML = dynamicDiv.innerHTML;

		flowplayer("player", "flowplayer/flowplayer-3.1.5.swf", {clip: {autoPlay: false, autoBuffering: true}});
		globalVideoLoaded = true;
		}
		else
		{
			// don't load it again.
		}
	}
}

function HideTheVideoContainer()
{
	// hide the overlay and stop the video.
	var container = document.getElementById("VideoContainer")
	var container2 = document.getElementById("VideoContainer1");
	if(container != null)
	{
		container.style.display = "none";
		container2.style.display = "none";
		flowplayer().pause();
	}
}


/************************** Popup Keep KG control *************************************/

function KeepKGPopupControl_CheckAll(_checkAllBox)
{
//debugger;
  var frm = document.getElementById('KeepKGPopupControl_Grid');//KeepKGPopupControl_ListViewGridContainer;
  var chkState = _checkAllBox.checked;
  
  if(chkState == true)
		CheckAllStatus = 'All';
	else
		CheckAllStatus = 'None';
  
  for(var k=0;k< frm.getElementsByTagName("input").length;k++)
  {
		if(frm.getElementsByTagName("input").item(k).type == "checkbox" && frm.getElementsByTagName("input").item(k).name.indexOf('Id') != -1)
		{
		  frm.getElementsByTagName("input").item(k).checked = chkState;
		}
	}
}
  
function KeepKGPopupControl_CheckChanged(e)
{
//debugger;
	var frm = document.getElementById('KeepKGPopupControl_Grid');//document.KeepKGPopupControl_ListViewGridContainer;
	var bAllChecked = true;
	
	for(var k=0;k< frm.getElementsByTagName("input").length;k++)
  {
    if(frm.getElementsByTagName("input").item(k).type == "checkbox")
    {
			if(frm.getElementsByTagName("input").item(k).checked == false)
			{
				bAllChecked = false;
				break;
			}
    }
  }
  
  for (k=0;k< frm.getElementsByTagName("input").length;k++)
  {    
    if(frm.getElementsByTagName("input").item(k).type == "checkbox" && frm.getElementsByTagName("input").item(k).name.indexOf('CheckAll') != -1)
    {
			if(bAllChecked == false)
			{
				frm.getElementsByTagName("input").item(k).checked = false;
				CheckAllStatus = 'Mix';
			}
			else
			{
				frm.getElementsByTagName("input").item(k).checked = true;
				CheckAllStatus = 'Mix';
			}
			break;
		}
	}
}

var CHECKBOXARRAY = null;
var CheckAllStatus = 'All';
function KeepKGPopupControl_CheckBoxClick(_chkBox, _KGID)
{
  //debugger;  
  try
  {
    //set up the array
    if(CHECKBOXARRAY == null)
    {
      CHECKBOXARRAY = new Array();
      //USERPERMISSIONRBTNARRAY = new Array();
    }     
    
    // Add user and permission to array
    CHECKBOXARRAY[_KGID] = _chkBox.checked;   
    //USERPERMISSIONRBTNARRAY[_KGID] = _radioButton.id;
    return true;
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    //debugger;
  }       
}

function KeepKGPopupControl_Submit(_mode, _callbackTriggerName, _redirect, _genesTabClicked)
{
  //debugger;
  try
  {     
    //SetSessionProperty('ConfigureCommunitySpace_User_InputMode', _mode);               
    var kgs = '';
    switch(_mode)
    {
      case "Sign-In":                   
          //ShowUsersLoadingIcon('Loading Users');
          break;
      case "Register":             
          //window.location = "examples.aspx"              
          break;
      case "save":
          
         // ShowUsersLoadingIcon('Saving');
          
          // Do save stuff              
          //var kgs = '';
          if(CHECKBOXARRAY != null && CHECKBOXARRAY.length > 0)
          {          
            for ( var i in CHECKBOXARRAY )
            {
              kgs += i + "_" + CHECKBOXARRAY[i] + ':';
            } 
          }
          break;
      case "delete": //this is actually remove i.e. when prompted to keep the logged in user clicks 'no'
				kgs = Active_KGID;
				break;
			case "save2": //'save' is reserved for when we have lists of kgs.  at the moment it just saves a single KG i.e. when prompted to keep the logged in user clicks 'yes'
				kgs = Active_KGID;
				break;
    }                
    
    CHECKBOXARRAY = null;    
        
    SetSessionProperty("KeepKGControl_CallbackMode", "leave");      
    var args = 'ACTION=' + _mode + '|CHECKALL=' + CheckAllStatus + '|kgs=' + kgs + '|REDIRECT=' + _redirect + '|GENESTABCLICK=' + _genesTabClicked;     
    //eval(_cbreference);    
		eval(_callbackTriggerName + "('" + args + "')");
  }
  catch (e) 
  {
    alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message); 
    //debugger;
  }          
}

function KeepKGPopupControl_CallbackTrigger_Wrapped(_args, _cbReference)
{ 
//debugger;
  CallbackTrigger_Wrapped(_args, _cbReference);
}

function KeepKGPopupControl_CallbackDone_Wrapped(_args, _context)
{ 
  // Check for a session time out before completing the callback and before checking for exceptions
  if (CheckSessionTimeout())
    return;

  //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);
//debugger;
  //show the KeepKGPopup if required.  This code is only used for signed in users.....
  if (isAuthenticated() == true)
	{
		var showPopup = retMsg.ShowPopup;
		//debugger;
		if(showPopup == 'True')
		{
			//lets show the popup then
			SetShowKeepKGPromptStyle();
		}
		else if (showPopup == 'False')
		{
			if(retMsg.GenesTabClicked == 'True')
			{
				// just redirect them to where they were going....
				if(retMsg.RedirectUrl != '')
					setTimeout(retMsg.RedirectUrl, 1);
			}
			else
			{
				if(retMsg.RedirectUrl != '')
					window.location = retMsg.RedirectUrl;
			}
		}
		
//		if(retMsg.RefreshLeftPane == 'True')
//		{
//			LeftPaneMyKnowledgeControl_CallbackTrigger('Action:repopulate');//"), 500);
//		}
  }
}

// disable the Keep KG Prompt
var globalShowKeepKGPrompt = false;

function ShowKeepKGPrompt(_redirect, _geneTabClick)
{ 
//debugger;
  // disable the Keep KG Prompt
  globalShowKeepKGPrompt = false;

   var currentLocation = window.location.href;
  var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
  if (currentPage.indexOf('home') > -1 || currentPage.length == 0)
  {
		//signed out user logic
		if ((isAuthenticated() == false && globalShowKeepKGPrompt == true))// || (isAuthenticated() == true && globalShowKeepKGPrompt == true))
		{
			SetShowKeepKGPromptStyle();			
		  
		  if(m_bEditable)
				SetSessionProperty("KeepKGControl_CallbackMode", "create");
			else
				SetSessionProperty("KeepKGControl_CallbackMode", "leave");
			
			var args = 'ACTION=repopulate|REDIRECT=' + _redirect + "|GENESTABCLICK=" + _geneTabClick;        
			eval("KeepKGPopupControl_CallbackTrigger('" + args + "')");
			
		}
		else if (isAuthenticated() == true && globalShowKeepKGPrompt == true) // signed in user
		{
			// this is a little less straightforward.  I've put it into an 'else if' just to make the code clearer.
			// we only want to show the popup if the user is viewing a KG not currently in their list.
			SetSessionProperty("KeepKGControl_CallbackMode", "leave");
			var args = 'ACTION=SignedInUser|REDIRECT=' + _redirect + "|GENESTABCLICK=" + _geneTabClick;        
			eval("KeepKGPopupControl_CallbackTrigger('" + args + "')");
		}
		else
		{
			if(_geneTabClick)
				eval(_redirect);
			else
				window.location=_redirect;
		}
	}
	else
	{
		if(_geneTabClick)
		  eval(_redirect);
		else		    
		  window.location=_redirect;
	}
	
	//globalShowKeepKGPrompt = true;
	
}

function SetShowKeepKGPromptStyle()
{
  if (window.HideKGForceRegisterControl)
  {
    HideKGForceRegisterControl(); // only need one of these messages at once
  }
  
	  document.getElementById('KeepKGPopupControlOverlay').style.display='block';
	  var kgPopupContainer = document.getElementById('KeepKGContainer');
	  kgPopupContainer.style.display='block';
	  kgPopupContainer.style.zIndex = "999";
		kgPopupContainer.style.position = "absolute";
		kgPopupContainer.style.top = "150px";
		kgPopupContainer.style.left = "30%";
}


function HideKeepKGPrompt()
{
	// hide the overlay and stop the video.
	document.getElementById('KeepKGPopupControlOverlay').style.display='none';
	document.getElementById('KeepKGContainer').style.display='none';
}

function KGForceRegisterControl_SignIn(e)
{
  HideKGForceRegisterControl();
  KGSignInControl_Show(e);
}

function ClickProfileLink() {
	globalShowKeepKGPrompt=false; 
	//returnFromEditView(); -- remove this to fix 10460
	var currentLocation = window.location.href;
  var hostURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1);
  window.location = hostURL + 'home.aspx?t=profile';
}

/********************* Author & Navigate Help *********************/

function ShowTheNavigateHelp()
{
	HideTheAuthorHelp("true");
	// show the Navigate Help
	var container = document.getElementById("SiteOverlays_NavigateHelp");
	if(container == null)
		container = document.getElementById("NavigateHelp");
	var container2 = document.getElementById("NavigateHelp1");
	if(container2 == null)
		container2 = document.getElementById("SiteOverlays_NavigateHelp1")
	if(container != null)
	{
		container.style.display = "block";
		container2.style.display = "block";
		container.style.zIndex = "999";
		container.style.position = "absolute";
		
		container.style.top = window.document.body.clientHeight - 450; // 220 is hardcoded box height
		container.style.left = window.document.body.clientWidth - 380; // 220 is hardcoded box width
	}	
}

function HideTheNavigateHelp(_forceClose)
{
	// Check for a cookie on this browser.
	if(WM_readCookie('NavigateHelp') == "true" || _forceClose == "true")
	{
		HideTheNavigateHelpBox();
	}
	else
	{
		// If no cookie exists, make one
		WM_setCookie('NavigateHelp', true, 720);
				
		var msgBoxNavigatePopup = document.getElementById("msgBoxNavigatePopup");
		if(msgBoxNavigatePopup == null)
			msgBoxNavigatePopup = document.getElementById("Site_Overlays_msgBoxNavigatePopup");
		var container = document.getElementById("NavigateHelp");
		if(container == null)
			container = document.getElementById("SiteOverlays_NavigateHelp");
		
		if(msgBoxNavigatePopup != null)
		{
			var leftPos = container.style.left.replace("px","");
			if(leftPos < 400)
				msgBoxNavigatePopup.style.left = "100";
			else
				msgBoxNavigatePopup.style.left = "-250";
			msgBoxNavigatePopup.style.display = "block";
		}
	}
}

function HideTheNavigateHelpBox()
{
	var msgBoxNavigatePopup = document.getElementById("msgBoxNavigatePopup");
	if(msgBoxNavigatePopup == null)
		msgBoxNavigatePopup = document.getElementById("SiteOverlays_msgBoxNavigatePopup");
		
	if(msgBoxNavigatePopup != null)
	{
		msgBoxNavigatePopup.style.display = "none";
	}
	// hide the overlay
	var container = document.getElementById("NavigateHelp")
	if(container == null)
		container = document.getElementById("SiteOverlays_NavigateHelp")
	var container2 = document.getElementById("NavigateHelp1");
	if(container2 == null)
		container2 = document.getElementById("SiteOverlays_NavigateHelp1")
	if(container != null)
	{
		container.style.display = "none";
		container2.style.display = "none";
	}
}

function ShowTheCodeOfKnowledgeHelp()
{
  window.open('codeofknowledge.aspx', 'CodeofKnowledge', 'width=1000,height=600,resizable=yes');
}

function ShowTheAuthorHelp()
{
	HideTheNavigateHelp("true");
	// Show the Author Help
	var container = document.getElementById("SiteOverlays_AuthorHelp");
	if(container == null)
		container = document.getElementById("AuthorHelp");
	var container2 = document.getElementById("AuthorHelp1");
	if(container2 == null)
		container2 = document.getElementById("SiteOverlays_AuthorHelp1")
	if(container != null)
	{
		container.style.display = "block";
		container2.style.display = "block";
		container.style.zIndex = "999";
		container.style.position = "absolute";

		container.style.top = Math.round(window.document.body.clientHeight / 3.0);
		container.style.left = window.document.body.clientWidth - 450;
	}	
}

function HideTheAuthorHelp(_forceClose)
{
	// Check for a cookie on this browser.
	if(WM_readCookie('AuthorHelp') == "true" || _forceClose == "true")
	{
		HideTheAuthorHelpBox();
	}
	else
	{
		// If no cookie exists, make one
		WM_setCookie('AuthorHelp', true, 720);
				
		var msgBoxAuthorPopup = document.getElementById("msgBoxAuthorPopup");
		if(msgBoxAuthorPopup == null)
			msgBoxAuthorPopup = document.getElementById("Site_Overlays_msgBoxAuthorPopup");
		var container = document.getElementById("AuthorHelp");
		if(container == null)
			container = document.getElementById("SiteOverlays_AuthorHelp");
		
		if(msgBoxAuthorPopup != null)
		{
			var leftPos = container.style.left.replace("px","");
			if(leftPos < 400)
				msgBoxAuthorPopup.style.left = "100";
			else
				msgBoxAuthorPopup.style.left = "-130";
			msgBoxAuthorPopup.style.display = "block";
		}
	}
}

function HideTheAuthorHelpBox()
{
	var msgBoxAuthorPopup = document.getElementById("msgBoxAuthorPopup");
	if(msgBoxAuthorPopup == null)
		msgBoxAuthorPopup = document.getElementById("SiteOverlays_msgBoxAuthorPopup");
		
	if(msgBoxAuthorPopup != null)
	{
		msgBoxAuthorPopup.style.display = "none";
	}
	// hide the overlay
	var container = document.getElementById("AuthorHelp")
	if(container == null)
		container = document.getElementById("SiteOverlays_AuthorHelp")
	var container2 = document.getElementById("AuthorHelp1");
	if(container2 == null)
		container2 = document.getElementById("SiteOverlays_AuthorHelp1")
	if(container != null)
	{
		container.style.display = "none";
		container2.style.display = "none";
	}
}

/********************* END Author & Navigate Help *********************/

/********************* Example Scrolling *******************/

var globalExampleList;
var globalExampleCurrentIndex = 0;
var globalExampleClientId;

function ScrollExamples_Wrapped(interval, ExampleString, ClientID)
{
	// Create a List from the JSON object
	globalExampleList = ExampleString.split('@@');
		
	// Store the ClientID
	globalExampleClientId = ClientID;
	
	// Create the Interval if the list is big enough.
	if(globalExampleList.length > 2)
		setInterval("ScrollThroughExamples()", interval);
}

function ScrollThroughExamples()
{
	// Scroll throught the elements.
	var element = document.getElementById(globalExampleClientId);

	if(globalExampleCurrentIndex < (globalExampleList.length - 2))
	{
		element.innerText = globalExampleList[globalExampleCurrentIndex];
		globalExampleCurrentIndex++;
	}
	else
	{
		element.innerText = globalExampleList[globalExampleCurrentIndex];
		globalExampleCurrentIndex = 0
	}
}

/********************* End of Example Scrolling *******************/


////addEvent() by John Resig
//function addEvent( obj, type, fn ){if (obj.addEventListener){obj.addEventListener( type, fn, false );}else if (obj.attachEvent){ obj["e"+type+fn] = fn; obj[type+fn] = function(){ obj["e"+type+fn]( window.event ); } obj.attachEvent( "on"+type, obj[type+fn] ); } } 

////Run dynamicLayout function when page loads and when it resizes.
//addEvent(window, 'load', dynamicLayout);
//addEvent(window, 'resize', dynamicLayout);


function getBrowserWidth()
{//debugger;
  if (window.innerWidth)
  {
    return window.innerWidth;
  }  
  else if (document.documentElement && document.documentElement.clientWidth != 0)
  {
    return document.documentElement.clientWidth;    
  }
  else if (document.body)
  {
		return document.body.clientWidth;
	}      
  return 0;
}

function dynamicLayout()
{//debugger;
		// this calcualtes the width of the homepage content.  
		// (width of the browser window) - (width of the lefthandpane myMaps) - 5
		// the 5 just covers the eroneous gap the left pane and map content.
    //document.getElementById("HomePageCentralContainer").parentNode.style.width = getBrowserWidth() - document.getElementById("LeftHandPane").style.width.replace('px', '') - 5;
}


/********************* End of Example Scrolling *******************/

function setBoolAtt(_el, _attName, _value)
{
  // _value should be true or false (boolean)
  // use with function getBoolAtt to handle booleans <--> strings (attributes are strings in at least some browsers)
  if (_value == true)
    _el.setAttribute(_attName, "true");
  else if (_value == false)
    _el.setAttribute(_attName, "false");
  //else?
}

function getBoolAtt(_el, _attName)
{
  // returns true or false (boolean)
  // use with function setBoolAtt to handle booleans <--> strings (attributes are strings in at least some browsers)
  var strAtt = _el.getAttribute(_attName);
  
  if (!strAtt)
    return false;
  
  strAtt = strAtt.toLowerCase();
  if (strAtt == "true")
    return true;
  else if (strAtt == "false")
    return false;
  //else?
}

//////////
// ensures the first character of the string is upper case
function FirstLetterToUpper(_string)
{
  // get the first letter
  var substr1 = _string.substring(0, 1);
  // and get the rest of the string
  var substr2 = _string.substring(1, _string.length);
  
  var string = substr1.toUpperCase() + substr2;
  
  return string;
}

//////////////////////////
// trims whitespace off the front and end of a string
function TrimString(_string) 
{
  return _string.replace(/^\s+|\s+$/g,"");
}

/********************* New KG *******************/
function NewKGTextBox_ClientClick(_txtBox)
{
  if (getBoolAtt(_txtBox, "IsDefault"))
    NewKGTextBox_ClearDefault(_txtBox);
}

function NewKGTextBox_KeyPress(e, _txtBox)
{
//debugger;
  e = e || window.event; 
  
  if (getBoolAtt(_txtBox, "IsDefault")) // incase we arrived without clicking the textbox (e.g. tab)
    NewKGTextBox_ClearDefault(_txtBox);
  
  var key = (e.which) ? e.which : e.keyCode;
  if (key == 13) // Enter
  {
    NewKGButton_ClientClick1();
    e.returnValue = false;
    if (e.preventDefault) e.preventDefault();
    return false;
  }
  else if (key == 27) // Escape
  {
    NewKGTextBox_BackToDefault(_txtBox);
    _txtBox.blur();
  }
}

function NewKGTextBox_ClearDefault(_txtBox)
{
  // clear the default text, ready to start typing
  _txtBox.value = "";
  
  // restyle
  _txtBox.style.color = "Black";
  _txtBox.style.textAlign = "left";
  
  setBoolAtt(_txtBox, "IsDefault", false);
}

function NewKGTextBox_BackToDefault(_txtBox)
{
	// Don't think this is needed anymore... Since no box in site header?
  // can call without _txtBox param - then get it here (but if you've already got it you may aswell pass it in)
 /* if (!_txtBox)
  {
    var txtBoxId = NewKGControl_GetTextBoxID();
    _txtBox = document.getElementById(txtBoxId);
  }

  // put the text box back to its default state
  _txtBox.value = _txtBox.getAttribute("NewKGDefaultText");
  
  // set styling back to css class
  _txtBox.style.color = "";
  _txtBox.style.textAlign = "";
  
  setBoolAtt(_txtBox, "IsDefault", true);*/
}


function NewKGButton_ClientClick1()
{
    // call ShowKeepKGPrompt from here not onclick, because it may be fired from something else like enter in the text box
    ShowKeepKGPrompt("NewKGButton_CreateNewKG()", true);
}

function NewKGButton_ClientClick()
{
  // call ShowKeepKGPrompt from here not onclick, because it may be fired from something else like enter in the text box
  ShowKeepKGPrompt("NewKGFakeKnowde_CreateNewKG()", true);
}


function ChangeFYOImage()
{
		/*var currentLocation = window.location.href;
		var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
		if(currentPage.indexOf('foryourorganization'))
			WM_setCookie('MapBackground', 'MM', 720);
		else if(currentPage.indexOf('intelligentmindmapping'))
			WM_setCookie('MapBackground', 'FYO', 720);
		else*/

    // Default to no background
 		WM_setCookie('MapBackground', 'None', 720);
    window.location = "home.aspx?action=CreateNewKg";
		return;
    
    var image = document.getElementById("ImgFYODimensions");
    image.style.backgroundPositionX = "0";
    image.style.backgroundPositionY = "-484";
    document.getElementById("BeginWhyCodingLink").style.visibility = "hidden";    
    var FYOImageAreaToLoad = document.getElementById("FYOImageAreaID");
    //debugger;
    var FakeKnowde = document.createElement("input")
    FakeKnowde.className = "FakeKnowdeVisible";
    FakeKnowde.value = m_WHYCodingDefaultText; 
    FakeKnowde.setAttribute("id", "FakeKnowdeID");
    FakeKnowde.setAttribute("type", "text");
    FakeKnowde.setAttribute("IsDefault", "false");
    FakeKnowde.onclick = function () { if (this.value == m_WHYCodingDefaultText) { this.value = ""; this.style.fontStyle = "normal"; this.style.color = "#222222"; } };
    
//    FakeKnowde.onblur = function() {CreateKnowledgeGeneFYO();};
    FakeKnowde.onkeypress = function(event) {FakeKnowde_KeyPress(event,this)};
        
    FYOImageAreaToLoad.appendChild(FakeKnowde);
    FakeKnowde.focus();

}



function FakeKnowde_KeyPress(e, _txtBox)
{
//debugger;
  e = e || window.event; 
  
    var key;
  
    if(window.event)
        key = window.event.keyCode;     //IE
    else
        key = e.which;     //firefox
  
  
    if (key == 13) // Enter
    {
      if (_txtBox.value == m_WHYCodingDefaultText)
			{
				// Do nothing if they havent entered anything yet?
			}
			else
			{
				var currentLocation = window.location.href;
				var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/')+1, currentLocation.length).toLowerCase();
        
        // Default to no background
				SwitchMapBackground('None');
					
        var text = document.getElementById('FakeKnowdeID').value;
        NewKGButton_ClientClick();
        e.returnValue = false;
        if (e.preventDefault) e.preventDefault();
        return false;
      }
    }
    else if(key == 27)
    {
      _txtBox.value = m_WHYCodingDefaultText; 
				_txtBox.style.fontStyle = "italic"; 
				_txtBox.style.color = "gray";
    }
    else
    {
      if (_txtBox.value == m_WHYCodingDefaultText)
			{
				_txtBox.value = ""; 
				_txtBox.style.fontStyle = "normal"; 
				_txtBox.style.color = "#222222";
			}
    }
}




function CreateKnowledgeGeneFYO()
{    
    ShowKeepKGPrompt("NewKGFakeKnowde_CreateNewKG()", true);
}

function CreateNewKG_Redirect(_source)
{
  if (_source == null)
    _source = 'unknown';
  // first, set an ashx session variable to say we've come from a UI action to create a new KG
  SetSessionProperty('KGCreatedFromRedirect', _source);

  window.location = GetCreateNewKGUrl('test') + '&source=' + _source;

}

function AutoCreateNewKG(_newKGText, _showHelp) {
//	// Make sure when creating new KG from welcome page the mapediting.js is imported otherwise the map will not load
	//	LoadMapTabbedView();
	if (window.CreateNewKG != null) {
//		AlertDebugInfo('AutoCreateNewKG1');
		CreateNewKG(_newKGText, _showHelp);
	}
	else {
//		AlertDebugInfo('AutoCreateNewKG2');
		//    // first, set an ashx session variable to say we've come from a UI action to create a new KG
		if (!_newKGText)
			SetSessionProperty('KGCreatedFromUIAction', 'valid knowde');
		else
			SetSessionProperty('KGCreatedFromUIAction', 'blank knowde');

		window.location = GetCreateNewKGUrl(_newKGText, _showHelp);
	}
}

function NewKGFakeKnowde_CreateNewKG()
{     

  var newKGText = NewKGFakeKnowde_ReadTextBox();
  AutoCreateNewKG(newKGText);
}

function NewKGFakeKnowde_ReadTextBox()
{
  var txtBoxId = "FakeKnowdeID";
  var txtBox = document.getElementById(txtBoxId);

  if (txtBox && !getBoolAtt(txtBox, "IsDefault"))
    return FirstLetterToUpper(TrimString(txtBox.value));
}


function NewKGFromSearch_CreateNewKG()
{

  var newKGText = NewKGKnowdeFromSearch_ReadTextBox();

  AutoCreateNewKG(newKGText);
}

function NewKGKnowdeFromSearch_ReadTextBox()
{
  var txtBoxId = "WHWSearchBox";
  var txtBox = document.getElementById(txtBoxId);

  if (txtBox && txtBox.value != '' && txtBox.value != m_WHWSearchBoxDefaultText)
    return FirstLetterToUpper(TrimString(txtBox.value));
}


function NewKGButton_CreateNewKG()
{ 
    
  var newKndTxt = NewKGTextBox_ReadTextBox();

  AutoCreateNewKG(newKndTxt);
}

function NewKGTextBox_ReadTextBox()
{
	// Don't think this is needed anymore... Since no box in site header?
 /* var txtBoxId = NewKGControl_GetTextBoxID();
  var txtBox = document.getElementById(txtBoxId);

  if (txtBox && !getBoolAtt(txtBox, "IsDefault"))
    return FirstLetterToUpper(TrimString(txtBox.value));*/
}



function GetCreateNewKGUrl(_newKndTxt, _showHelp)
{
  // in a little function so it's easier to change in future
  var newLoc = "home.aspx?action=CreateNewKg";
  
  if (_newKndTxt)
    newLoc += "&kndTxt=" + encodeURIComponent(_newKndTxt); //need to encode, especially for '&'  
  // seems encodeURIComponent is more appropriate here than escape: http://xkr.us/articles/javascript/encode-compare/
  if (_showHelp != null && _showHelp == false)
    newLoc += "&showHelp=n"; //won't auto popup author help

  return newLoc; 
}
/********************* End of New KG *******************/

/********************* Service Popups *******************/
function PremiumServiceMouseOver(service, e)
{
	e = e || window.event;
	var hoveredOverElement = e.target || e.srcElement;
	var elemCoords = findElementCoords(hoveredOverElement);
	
	HideAllServicePopups();
	var ElementToPopup = null;

	var horizontalOffset;
	var verticalOffset;
	if (navigator.userAgent.indexOf('Firefox') != -1 || navigator.userAgent.indexOf('Opera') != -1)
	{
		verticalOffset = 0;
		horizontalOffset = 435;
	}
	else
	{
		verticalOffset = 60;
		if (navigator.userAgent.indexOf('Safari') != -1)
			horizontalOffset = 435;
		else
			horizontalOffset = 420;
	}

	if(service.indexOf("WHY Organization") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYOrganization");
		if(ElementToPopup != null)
		{
			// Position and show
			ElementToPopup.style.left = elemCoords[0] - horizontalOffset; ;
			ElementToPopup.style.top = elemCoords[1] + verticalOffset;
			ElementToPopup.style.display = "block";
		}
		return;
	}
	if (service.indexOf("WHY Compliance") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYCompliance");
		if(ElementToPopup != null)
		{
			// Position and show
			ElementToPopup.style.left = elemCoords[0] - horizontalOffset; ;
			ElementToPopup.style.top = elemCoords[1] + verticalOffset;
			ElementToPopup.style.display = "block";
		}
		return;
	}
	if (service.indexOf("WHY Process") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYProcess");
		if(ElementToPopup != null)
		{
			// Position and show
			ElementToPopup.style.left = elemCoords[0] - horizontalOffset; ;
			ElementToPopup.style.top = elemCoords[1] + verticalOffset;
			ElementToPopup.style.display = "block";
		}
		return;
	}
	if (service.indexOf("WHY Work") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYWork");
		if(ElementToPopup != null)
		{
			// Position and show
			ElementToPopup.style.left = elemCoords[0] - horizontalOffset; ;
			ElementToPopup.style.top = elemCoords[1] + verticalOffset;
			ElementToPopup.style.display = "block";
		}
		return;
	}
	if(service.indexOf("WHY Learning") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYLearning");
		if(ElementToPopup != null)
		{
			// Position and show
			ElementToPopup.style.left = elemCoords[0] - horizontalOffset; ;
			ElementToPopup.style.top = elemCoords[1] + verticalOffset;
			ElementToPopup.style.display = "block";
		}
		return;
	}
	if (service.indexOf("WHY Maps") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYMaps");
		if(ElementToPopup != null)
		{
			// Position and show
			ElementToPopup.style.left = elemCoords[0] - horizontalOffset; ;
			ElementToPopup.style.top = elemCoords[1] + verticalOffset;
			ElementToPopup.style.display = "block";
		}
		return;
	}
	if (service.indexOf("WHY IT") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYIT");
		if(ElementToPopup != null)
		{
			// Position and show
			ElementToPopup.style.left = elemCoords[0] - horizontalOffset; ;
			ElementToPopup.style.top = elemCoords[1] + verticalOffset;
			ElementToPopup.style.display = "block";
		}
		return;
	}
}

function PremiumServiceMouseOut(service)
{

	var ElementToPopup = null;

	if (service.indexOf("WHY Organization") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYOrganization");
		if(ElementToPopup != null)
				ElementToPopup.style.display = "none";
		return;
	}
	if(service.indexOf("Why Compliance") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYCompliance");
		if(ElementToPopup != null)
			ElementToPopup.style.display = "none";
		return;
	}
	if(service.indexOf("WHY Learning") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYLearning");
		if(ElementToPopup != null)
			ElementToPopup.style.display = "none";
		return;
	}
	if(service.indexOf("WHY Work") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYWork");
		if(ElementToPopup != null)
			ElementToPopup.style.display = "none";
		return;
	}
	if(service.indexOf("WHY Process") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYProcess");
		if(ElementToPopup != null)
			ElementToPopup.style.display = "none";
		return;
	}
	if (service.indexOf("WHY Maps") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYMaps");
		if(ElementToPopup != null)
			ElementToPopup.style.display = "none";
		return;
	}
	if(service.indexOf("WHY IT") != -1)
	{
		ElementToPopup = document.getElementById("PopupWHYIT");
		if(ElementToPopup != null)
			ElementToPopup.style.display = "none";
		return;
	}
}

function HideAllServicePopups()
{
	try
	{
		document.getElementById("PopupWHYOrganization").style.display = "none";
		document.getElementById("PopupWHYCompliance").style.display = "none";
		document.getElementById("PopupWHYLearning").style.display = "none";
		document.getElementById("PopupWHYWork").style.display = "none";
		document.getElementById("PopupWHYProcess").style.display = "none";
		document.getElementById("PopupWHYMaps").style.display = "none";
		document.getElementById("PopupWHYIT").style.display = "none";
	}
	catch(e)
	{
		// failed to hide Service Popup
		alert("Couldn't hide popup");
	}
}
/********************* Service Popups *******************/

function closeAskToRegister()
{
	var GreyBG = document.getElementById("GreyBG");
	var DialogHolder = document.getElementById("DialogHolder");
	try
	{
		var page = document.getElementById("Form1");
		page.removeChild(GreyBG);
		page.removeChild(DialogHolder);
	}
	catch(e)
	{
		GreyBG.style.display = "none";
		DialogHolder.style.display = "none";
	}
}

function AskToRegister()
{
  if ( isAuthenticated() == true )
    return;
        
	var GreyBG = document.createElement("span");
	var width = screen.availWidth;
	var height = screen.availHeight;
	GreyBG.id = "GreyBG";
	GreyBG.style.width = width;
	GreyBG.style.height = height;
	GreyBG.className = "BrowserDiv";
	
	var DialogHolder = document.createElement("div");
	var Dialog = document.createElement("div");
	var DialogText = document.createElement("div");
	var DialogButton = document.createElement("div");
	var DialogClose = document.createElement("div");
	
	DialogText.className = "DialogText";
	DialogText.innerHTML = "Please sign in or register to access the Enterprise</br> Community that you have been invited to... It's free!";
	DialogButton.className = "DialogButton";
	DialogButton.onclick = function(){closeAskToRegister();};
	DialogClose.className = "DialogClose";
	DialogClose.onclick = function(){closeAskToRegister();};

	Dialog.appendChild(DialogClose);
	Dialog.appendChild(DialogText);
	Dialog.appendChild(DialogButton);
	
	Dialog.style.width = 381;
	Dialog.style.height = 191;
	Dialog.className = "AskToRegister";
	
	DialogHolder.id = "DialogHolder";
	DialogHolder.style.width = width;
	DialogHolder.style.height = height;
	DialogHolder.className = "CookieContainerDiv";
	DialogHolder.appendChild(Dialog);
	
	var page = document.getElementById("Form1");
	page.appendChild(GreyBG);
	page.appendChild(DialogHolder);
}

function CloseQuickConfigure()
{
	var QuickConfigure = document.getElementById("QuickConfigure");
	if(QuickConfigure != null)
		QuickConfigure.style.display = "none";
}

function ShowQuickConfigure()
{
	var QuickConfigure = document.getElementById("QuickConfigure");
	if(QuickConfigure != null)
		QuickConfigure.style.display = "block";
}

function TriggerQuickConfigure()
{
	var QuickConfigure = document.getElementById("QuickConfigure");
	var args = "Name=";
	var list = QuickConfigure.getElementsByTagName("INPUT");
	var Name = list[0].value;
	args += Name;
	args += '|';
	list = QuickConfigure.getElementsByTagName("TEXTAREA");
	var Emails = "Emails=";
	Emails += list[0].value;
	Emails = Emails.replace(/(\r\n|\n|\r)/gm,";");
	Emails = Emails.replace(";;",";");
	Emails = Emails.replace(";;",";");
	Emails = Emails.replace(";;",";");
	Emails = Emails.replace(";;",";");
	Emails = Emails.replace(";;",";");
	Emails = Emails.replace(";;",";");
	// send it to server
	args += Emails;
	QuickConfigure_CallbackTrigger(args);
}
function QuickConfigure_CallbackTrigger_Wrapped(_cbReference, _args)
{
	var args = _args;
  if(_cbReference != null && _cbReference != "")
    eval(_cbReference);
}

function QuickConfigure_CallbackDone_Wrapped(_args, _context)
{
	// callback the category control
	setTimeout("HorizontalCategoriesControl_Reload();",1);
	
	// close the quick configure popup
	CloseQuickConfigure();
}

function QuickConfigure_ProcessCallBackError_Wrapped(_args, _context, _ClientID)
{
}

function ClearTextArea()
{
	//debugger;
	if(this.event.srcElement.value == 'Please add 1 email address per line')
	{
		this.event.srcElement.value = '';
	}
}

/********************* Service Popups *******************/

function redirectToPurchasePage(_repurchase)
{
  var errormsg = document.getElementById("UsersErrorMessage");
  var purchaseLink = document.getElementById("PurchaseLink");
  var purchaseProceedImage = document.getElementById("PaymentProceedImage");    
  var numUsersLabel = document.getElementById("CurrentUsersTotal");
  var textbox = document.getElementById("UsersTextBox");
  var costLabel = document.getElementById("TotalCostText");
  var currDropList = document.getElementById("CurrencyDropList");
  
  errormsg.innerText = "";
  
  
  if ( purchaseProceedImage.src.indexOf('Grey') == -1 )
  {  
    if ( numUsersLabel && numUsersLabel.innerText != "[USERS]" )
    {
      var numUsers = parseInt(numUsersLabel.innerText);
      var numUsersInput = parseInt(textbox.value);
      
      if ( numUsersInput < numUsers )
      {
        errormsg.innerText = "You currently have " + numUsers + " users in this Enterprise Space.  Please increase the number of users above or click the (configure) link at the top to remove users before continuing with this subscription.";
        return;
      }          
    }
  }
  
  if ( purchaseProceedImage.src.indexOf('Grey') == -1 )
  {
    // need to setup the redirect url with the necessary details
    var numUsersInput = parseInt(textbox.value);  
    
    var groupIDLabel = document.getElementById("GroupID");
    var groupID = parseInt(groupIDLabel.innerText); 
    
    var costText = costLabel.innerText;       
          
    var currValue = currDropList.value;

    if ( _repurchase == true )
    {          
      window.location = "EnterpriseSpaceSubscriptionPurchase.aspx?numUsers=" + numUsersInput + "&groupID=" + groupID + "&cost=" + costText + "&currency=" + currValue + "&repurchase=true";
    }
    else
    {
      window.location = "EnterpriseSpaceSubscriptionPurchase.aspx?numUsers=" + numUsersInput + "&groupID=" + groupID + "&cost=" + costText + "&currency=" + currValue + "&repurchase=false";    
    }
  }
}

function redirectToNewPurchasePage()
{
  var errormsg = document.getElementById("LoginView_EnterpriseNewPurchase_UsersErrorMessage");
  var purchaseLink = document.getElementById("PurchaseLink");
  var purchaseProceedImage = document.getElementById("PaymentProceedImage");  
  var textbox = document.getElementById("LoginView_EnterpriseNewPurchase_UsersTextBox");
  var costLabel = document.getElementById("LoginView_EnterpriseNewPurchase_TotalCostText");
  var nameTextbox = document.getElementById("LoginView_EnterpriseNewPurchase_SpaceNameTextBox");
  var currDropList = document.getElementById("LoginView_EnterpriseNewPurchase_CurrencyDropList");
  
  errormsg.innerText = "";
  
  if ( purchaseProceedImage.src.indexOf('Grey') == -1 )
  {    
    if ( nameTextbox.value == "" )
    {
      errormsg.innerText = "Please enter a name for the Enterprise Space."
      return;
    }
  }
 
  if ( purchaseProceedImage.src.indexOf('Grey') == -1 )
  {
    // need to setup the redirect url with the necessary details
    var numUsersInput = parseInt(textbox.value);  
    
    var costText = costLabel.innerText;
    
    var currValue = currDropList.value;
           
    
    // set the name via the session not the url below in case of non-url-friendly characters
    SetSessionProperty("NewEnterpriseSpaceName", nameTextbox.value);
          
    window.location = "EnterpriseSpaceSubscriptionPurchase.aspx?numUsers=" + numUsersInput + "&groupID=-1&cost=" + costText + "&currency=" + currValue + "&repurchase=true";
  }
}

function confirmIncreaseSubscriptionTotal()
{
  var res = confirm('Please confirm you wish to proceed with the change.  Your payments will be changed immediately.');
  if ( res )
  {
    increaseSubscriptionTotal();
  }
  else
  {
    // nothing to do
  }
}

function increaseSubscriptionTotal()
{
  var upgradeLink = document.getElementById("UpgradeLink");
  var currentMembersLabel = document.getElementById("CurrentMembersTotal");
  var errormsg = document.getElementById("UsersErrorMessage");

  if ( upgradeLink.style.color != "Gray" && upgradeLink.style.color != "gray" )
  {
    // Check first if there's more physical members than than they're asking for
    var numMembers = parseInt(currentMembersLabel.innerText);
  
    // perform the user increase - go via an ashx call
    var existingUsersLabel = document.getElementById("CurrentUsersTotal");
    var currencyPayment = document.getElementById("NextPaymentCurrency");                 
    var newUsersTextBox = document.getElementById("UsersTextBox");
    var groupIDLabel = document.getElementById("GroupID");
    
    var newUsersValue = parseInt(newUsersTextBox.value);
    
    if ( numMembers > newUsersValue )
    {
        errormsg.innerText = "You currently have " + numMembers + " users in this Enterprise Space.  Please increase the number of users above or click the (configure) link at the top to remove users before continuing with this subscription.";
        return;
    }
    
    var ashxValueString = existingUsersLabel.innerText;
    ashxValueString += "#";
    ashxValueString += currencyPayment.innerText;
    ashxValueString += "#";
    ashxValueString += newUsersTextBox.value;
    ashxValueString += "#";
    ashxValueString += groupIDLabel.innerText;
    
    SetSessionProperty("HandleEnterpriseSpaceIncrease", ashxValueString);    
    
    // then hide the increase link and show the success message, e.space and home links
    var increaseLink = document.getElementById("UpgradeLink");
    var successMessage = document.getElementById("IncreaseSubscriptionSuccessMessage");
    var spaceLink = document.getElementById("IncreaseSubscriptionEnterpriseSpaceLink");
    var homeLink = document.getElementById("IncreaseSubscriptionHomeLink");

    increaseLink.style.display = "none";  
    successMessage.style.display = "block";
    spaceLink.style.display = "block";
    homeLink.style.display = "block";
  }
}

function newPurchaseUsersChange()
{
  var purchaseLink = document.getElementById("PurchaseLink");
  var purchaseProceedImage = document.getElementById("PaymentProceedImage");
  
  purchaseProceedImage.setAttribute('src', 'images/PaymentProceedGrey.png');  
  purchaseLink.setAttribute('title', 'Please enter a valid number of users first and click \'update price\'');
}

function trialEndedUsersChange()
{
  var purchaseLink = document.getElementById("PurchaseLink");
  var purchaseProceedImage = document.getElementById("PaymentProceedImage");
  
  purchaseProceedImage.setAttribute('src', 'images/PaymentProceedGrey.png');  
  purchaseLink.setAttribute('title', 'Please enter a valid number of users first and click \'update price\'');
}

function increaseSubscriptionUsersChange()
{
  var purchaseLink = document.getElementById("UpgradeLink");
  var purchaseProceedImage = document.getElementById("PaymentProceedImage");
  
  purchaseProceedImage.setAttribute('src', 'images/PaymentProceedGrey.png');  
  purchaseLink.setAttribute('title', 'Please enter a valid number of users first and click \'update price\'');
}

function updateSubscriptionTotal()
{
  try
  {
    // clear any errors first
    var errormsg = document.getElementById("CostErrorMessage");
    errormsg.innerText = "";
    
    var purchaseLink = document.getElementById("PurchaseLink");
    var purchaseProceedImage = document.getElementById("PaymentProceedImage");
    purchaseProceedImage.setAttribute('src', 'images/PaymentProceedGrey.png');
    purchaseLink.setAttribute('title', 'Please enter a valid number of users first');
        
    var textbox = document.getElementById("UsersTextBox");
    if ( textbox )
    {
      // parse the value in the text box
      try
      {
        var numUsers = parseInt(textbox.value);
        
        if (numUsers > 0)
        {
          var dropList = document.getElementById("CurrencyDropList");
          var totalCost;
        
          if ( dropList.value == "USD" )
          {
            totalCost = GlobalUSDCost * numUsers;
          }
          else if ( dropList.value == "EUR" )
          {
            totalCost = GlobalEURCost * numUsers;
          }
          else if ( dropList.value == "GBP" )
          {
            totalCost = GlobalGBPCost * numUsers;
          }
          
          var totalCostLabel = document.getElementById("TotalCostText");
          
          totalCostLabel.innerText = totalCost.toFixed(2);
          
          // activate the purchase link
          purchaseLink.setAttribute('title', 'Click to purchase the subscription');
          purchaseProceedImage.setAttribute('src', 'images/PaymentProceed.png');
          
        }
        else
        {
          errormsg.innerText = "  Please use a numerical value above zero";
        }
      
      }
      catch(e1)
      {
        // parse failed - put a message out to get them to put a number in
        errormsg.innerText = "  Please use a numerical value above zero";
      }    
    }      
  }
  catch(e2)
  {
    errormsg.innerText = "  Please use a numerical value above zero";  
  }
}

function updateNewPurchaseSubscriptionTotal()
{
  try
  {
    // clear any errors first
    var errormsg = document.getElementById("LoginView_EnterpriseNewPurchase_CostErrorMessage");
    errormsg.innerText = "";
    
    var purchaseLink = document.getElementById("PurchaseLink");
    var purchaseProceedImage = document.getElementById("PaymentProceedImage");
    purchaseProceedImage.setAttribute('src', 'images/PaymentProceedGrey.png');
    purchaseLink.setAttribute('title', 'Please enter a valid number of users first');
        
    var textbox = document.getElementById("LoginView_EnterpriseNewPurchase_UsersTextBox");
    if ( textbox )
    {
      // parse the value in the text box
      try
      {
        var numUsers = parseInt(textbox.value);
        
        if (numUsers > 0)
        {
          var totalCost;
          var dropList = document.getElementById("LoginView_EnterpriseNewPurchase_CurrencyDropList");        
        
          if ( dropList.value == "USD" )
          {
            totalCost = GlobalUSDCost * numUsers;
          }
          else if ( dropList.value == "EUR" )
          {
            totalCost = GlobalEURCost * numUsers;
          }
          else if ( dropList.value == "GBP" )
          {
            totalCost = GlobalGBPCost * numUsers;
          }
          
          var totalCostLabel = document.getElementById("LoginView_EnterpriseNewPurchase_TotalCostText");
          
          totalCostLabel.innerText = totalCost.toFixed(2);
          
          // activate the purchase link
          purchaseProceedImage.setAttribute('src', 'images/PaymentProceed.png');
          purchaseLink.setAttribute('title', 'Click to purchase the subscription');
          
          
          var i = 0;
        }
        else
        {
          errormsg.innerText = "  Please use a numerical value above zero";
        }
      
      }
      catch(e1)
      {
        // parse failed - put a message out to get them to put a number in
        errormsg.innerText = "  Please use a numerical value above zero";
      }    
    }      
  }
  catch(e2)
  {
    errormsg.innerText = "  Please use a numerical value above zero";  
  }
}

function updateIncreaseSubscriptionTotal()
{ 
  try
  {
    // clear any errors first
    //debugger;
    var errormsg = document.getElementById("CostErrorMessage");
    errormsg.innerText = "";
    
    var upgradeLink = document.getElementById("UpgradeLink");
    var purchaseProceedImage = document.getElementById("PaymentProceedImage");
    purchaseProceedImage.setAttribute('src', 'images/PaymentProceedGrey.png');
    upgradeLink.setAttribute('title', 'Please enter a valid number of users first');
    
    var existingUsers = document.getElementById("CurrentUsersTotal");
     
    var immediateNextPaymentLabel = document.getElementById("ImmediateNextPayment");     

    var currentNextPaymentLabel = document.getElementById("NextPaymentAmount");     

    var currentNextPaymentCurrencyLabel = document.getElementById("NextPaymentCurrency");
    
    var currentCostPerUserMonth = 0;
    
    if ( currentNextPaymentCurrencyLabel.innerText == "USD" )
      currentCostPerUserMonth = GlobalUSDCost;
    else if ( currentNextPaymentCurrencyLabel.innerText == "EUR" )
      currentCostPerUserMonth = GlobalEURCost;
    else if ( currentNextPaymentCurrencyLabel.innerText == "GBP" )
      currentCostPerUserMonth = GlobalGBPCost;     

    var daysLeftLabel = document.getElementById("DaysLeft");     
        
    var textbox = document.getElementById("UsersTextBox");
    if ( textbox )
    {
      // parse the value in the text box
      try
      {
        var numUsers = parseInt(textbox.value);
        var numExistingUsers = parseInt(existingUsers.innerText);

        var currentNextPayment = parseFloat(currentNextPaymentLabel.innerText);
        
        var daysLeft = parseInt(daysLeftLabel.innerText);                                                
        
        // calculate the next payment - then put it in the chosen currency
        var dailyRate = currentCostPerUserMonth / 30;
        var totalCostLabel = document.getElementById("TotalCostText");
        
        if ( numUsers <= 0 )
        {
          errormsg.innerText = " Please enter a number greater than zero";                        
        }
        if ( numUsers == numExistingUsers )
        {
          errormsg.innerText = " Please enter a number different to your current total";                
        }
        else if ( numUsers < numExistingUsers )
        {
          // calculate the next payment for the decrease for the days left
          var lessCost  = daysLeft * dailyRate * (numExistingUsers - numUsers);
          
          var normalMonthlyDifference = currentCostPerUserMonth * (numExistingUsers - numUsers);
          
          var nextMonthCost = currentNextPayment - lessCost - normalMonthlyDifference;
          
          var totalCost = currentCostPerUserMonth * numUsers;
      
          if ( nextMonthCost > 0 )
          {          
            immediateNextPaymentLabel.innerText = nextMonthCost.toFixed(2);
          }
          else
          {
            immediateNextPaymentLabel.innerText = nextMonthCost.toFixed(2) + ".  (note - if the amount shown here is negative then your account will be in credit against future monthly payments)";          
          }
          totalCostLabel.innerText = totalCost.toFixed(2);

          // activate the purchase link
          purchaseProceedImage.setAttribute('src', 'images/PaymentProceed.png');
          upgradeLink.setAttribute('title', 'Click to upgrade the subscription');
        }        
        else if (numUsers > numExistingUsers)
        {
          // calculate the next payment for the increase
          var extraCost = daysLeft * dailyRate * (numUsers - numExistingUsers);
          
          var normalMonthlyDifference = currentCostPerUserMonth * (numUsers - numExistingUsers);
          
          var nextMonthCost = currentNextPayment + extraCost + normalMonthlyDifference;
                    
          var totalCost = currentCostPerUserMonth * numUsers;        

          if ( nextMonthCost > 0 )
          {          
            immediateNextPaymentLabel.innerText = nextMonthCost.toFixed(2);
          }
          else
          {
            immediateNextPaymentLabel.innerText = nextMonthCost.toFixed(2) + ".  (note - if the amount shown here is negative then your account will be in credit against future monthly payments)";          
          }


          totalCostLabel.innerText = totalCost.toFixed(2);
          
          // activate the purchase link
          purchaseProceedImage.setAttribute('src', 'images/PaymentProceed.png');
          upgradeLink.setAttribute('title', 'Click to upgrade the subscription');
        }
        else
        {
          errormsg.innerText = "  Please use a numerical value above zero";
        }
      
      }
      catch(e1)
      {
        // parse failed - put a message out to get them to put a number in
        errormsg.innerText = "  Please use a numerical value above zero";
      }    
    }      
  }
  catch(e2)
  {
    errormsg.innerText = "  Please use a numerical value above zero";  
  }

}

function CurrencyChanged(_increaseControl)
{
  var dropList = document.getElementById("CurrencyDropList");
  if ( dropList == null )
    dropList = document.getElementById("LoginView_EnterpriseNewPurchase_CurrencyDropList");
  
  var userCostLabel = document.getElementById("UserCost");
  if ( userCostLabel == null )
    userCostLabel = document.getElementById("LoginView_EnterpriseNewPurchase_UserCost");
  
  var totalCostLabel = document.getElementById("TotalCostText");
  if ( totalCostLabel == null )
    totalCostLabel = document.getElementById("LoginView_EnterpriseNewPurchase_TotalCostText");
  
  var currencyLabel = document.getElementById("CurrencyLabel");
  if ( currencyLabel == null )
    currencyLabel = document.getElementById("LoginView_EnterpriseNewPurchase_CurrencyLabel");

  var currencyLabel2 = document.getElementById("CurrencyLabel2");
  if ( currencyLabel2 == null )
    currencyLabel2 = document.getElementById("LoginView_EnterpriseNewPurchase_CurrencyLabel2");

  var numUsersTextBox = document.getElementById("UsersTextBox");
  if ( numUsersTextBox == null )
    numUsersTextBox = document.getElementById("LoginView_EnterpriseNewPurchase_UsersTextBox");
    
  var immediateNextPaymentLabel = document.getElementById("ImmediateNextPayment");
  if ( immediateNextPaymentLabel == null )
    immediateNextPaymentLabel = document.getElementById("LoginView_EnterpriseNewPurchase_ImmediateNextPayment");
    
  var selectedValue = dropList.value;
  
  // set the appropriate values
  if ( selectedValue == "USD" )
  {
    if ( userCostLabel != null )
      userCostLabel.innerText = "$" + GlobalUSDCost;
    currencyLabel.innerText = "$";
    if ( currencyLabel2 != null )
      currencyLabel2.innerText = "$";    
    
    if ( totalCostLabel.innerText != "0" )
    {
      var numUsers = parseInt(numUsersTextBox.value);
      var totalCost = numUsers * GlobalUSDCost;
      totalCostLabel.innerText = "" + totalCost.toFixed(2);
      
      if ( _increaseControl == true )
      {
        // recalculate the next immediate payment
        var nextPayment = parseFloat(immediateNextPaymentLabel.innerText);        
        var baseCost = nextPayment / globalPreviousUserMonthCostOnIncreaseControl;
        
        var newNextCost = baseCost.toFixed(2) * GlobalUSDCost;
        immediateNextPaymentLabel.innerText = newNextCost.toFixed(2);
        globalPreviousUserMonthCostOnIncreaseControl = GlobalUSDCost;
      }
    }    
  }
  else if ( selectedValue == "EUR" )
  {
    if ( userCostLabel != null )
      userCostLabel.innerText = "\u20AC" + GlobalEURCost;      
    currencyLabel.innerText = "\u20AC";  
    if ( currencyLabel2 != null )
      currencyLabel2.innerText = "\u20AC";    
    
    if ( totalCostLabel.innerText != "0" )
    {
      var numUsers = parseInt(numUsersTextBox.value);
      var totalCost = numUsers * GlobalEURCost;
      totalCostLabel.innerText = "" + totalCost.toFixed(2);

      if ( _increaseControl == true )
      {
        // recalculate the next immediate payment
        var nextPayment = parseFloat(immediateNextPaymentLabel.innerText);        
        var baseCost = nextPayment / globalPreviousUserMonthCostOnIncreaseControl;
        
        var newNextCost = baseCost.toFixed(2) * GlobalEURCost;
        immediateNextPaymentLabel.innerText = newNextCost.toFixed(2);
        globalPreviousUserMonthCostOnIncreaseControl = GlobalEURCost;
      }
    }        
  }
  else if ( selectedValue == "GBP" )
  {
    if ( userCostLabel != null )
      userCostLabel.innerText = "\u00A3" + GlobalGBPCost;  
    currencyLabel.innerText = "\u00A3";  
    if ( currencyLabel2 != null )
      currencyLabel2.innerText = "\u00A3";    
    
    if ( totalCostLabel.innerText != "0" )
    {
      var numUsers = parseInt(numUsersTextBox.value);
      var totalCost = numUsers * GlobalGBPCost;
      totalCostLabel.innerText = "" + totalCost.toFixed(2);
 
      if ( _increaseControl == true )
      {
        // recalculate the next immediate payment
        var nextPayment = parseFloat(immediateNextPaymentLabel.innerText);        
        var baseCost = nextPayment / globalPreviousUserMonthCostOnIncreaseControl;
        
        var newNextCost = baseCost.toFixed(2) * GlobalGBPCost;
        immediateNextPaymentLabel.innerText = newNextCost.toFixed(2);
        globalPreviousUserMonthCostOnIncreaseControl = GlobalGBPCost;
      }
    }        
  }
}


// Quotations Slideshow that works in Firefox
// Temporarily create quotation array here and move logic to KGCoreControls when ready
var Quotations = new Array();
Quotations[0] = "&ldquo;The first question is... <span class='staticWHYWelcome'>WHY</span> do it at all?&rdquo;";
Quotations[1] = "&ldquo;Insecure managers create complexity&rdquo;";
Quotations[2] = "&ldquo;Simplicity is the ultimate sophistication&rdquo;";
Quotations[3] = "&ldquo;If you can't explain simply, you don't understand&rdquo;";
//Quotations[4] = "Nothing in life is to be feared, it is only to be understood";

var QuotationAuthors = new Array();
QuotationAuthors[0] = "Peter Drucker -";
QuotationAuthors[1] = "Jack Welch -";
QuotationAuthors[2] = "Leonardo Da Vinci -";
QuotationAuthors[3] = "Albert Einstein -";
//QuotationAuthors[4] = "Marie Curie";

var noOfQuotes = Quotations.length;
var QuoteCounter=0;
var timeInMS = 4000;

function ShowQuotationSlideShow()
{
    if (QuoteCounter < noOfQuotes)
    {        
        document.getElementById('KGQuote').innerHTML = Quotations[QuoteCounter];
        document.getElementById('KGQuoteAuthor').innerHTML = QuotationAuthors[QuoteCounter];
        QuoteCounter++;
    }
    else
    {
        QuoteCounter=0;  
    }    
    setTimeout("ShowQuotationSlideShow()",timeInMS);
}

function FileExporterControl_Handler(_pageUrl)
{
  var iframe = document.getElementById("KGFileExportIframe");
  if(iframe == null)
  {
    // Create an iFrame to prepare the way to generate and download the file
    iframe = document.createElement("iframe");
    iframe.id = "KGFileExportIframe";
    iframe.src = _pageUrl;
    // 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);
  }
  else
  {
    iframe.src = _pageUrl;
  }
}

function DailyWHY_CallbackTrigger_Wrapped(cbreference)
{
	var date = "";
	var lead = "";
	var main = "";
	var kgid = "";
	var param = "";
	var url = "";
	var errorMessage = "Please fix the following: <br/>";
	
	// Grab Elements
	for(digit=0; (tb = document.getElementsByTagName("input")[digit]); digit++) 
	{
		switch(tb.name)
		{
			case "Date": 
				date = tb.value;
				if(date == "")
					errorMessage += "&#149; No date set <br/>"
				break
			case "Lead": 
				lead = tb.value;
				if(lead == "")
					errorMessage += "&#149; No lead text set <br/>"
				break
			case "Main": 
				main = tb.value;
				if(main == "")
					errorMessage += "&#149; No main text set <br/>"
				break
			case "KGID": 
				kgid = tb.value;
				break
			case "Param": 
				param = tb.value;
				break
			case "URL": 
				url = tb.value;
				if(url == "" && kgid == "")
					errorMessage += "&#149; Both the KGID & URL cannot be empty at the same time <br/>"
				break
		}
	}
	
		// Error Check them
	if(errorMessage != "Please fix the following: <br/>")
	{
		var FeedbackMessage = document.getElementById("FeedbackMessage");
		FeedbackMessage.innerHTML = errorMessage;
	}
	else
	{
		// build the args string to handle in the C# ProcessAJAXCallback function
		var args = 'date='+date+'|lead='+lead+'|main='+main+'|kgid='+kgid+'|param='+param+'|url='+url;	
		eval(cbreference);
	}
}

function DailyWHY_CallbackDone_Wrapped(_args, _context)
{
	var FeedbackMessage = document.getElementById("FeedbackMessage");
	FeedbackMessage.innerHTML = _args;
}

function DailyWHY_ProcessCallBackError_Wrapped(_args, _context)
{
}

function PreviewDailyWHY()
{

	var FeedbackMessage = document.getElementById("FeedbackMessage");
	FeedbackMessage.innerHTML = "";

	var date = "";
	var lead = "";
	var main = "";
	var kgid = "";
	var param = "";
	var url = "";
	var errorMessage = "Please fix the following: <br/>";

	// Grab Elements
	for(digit=0; (tb = document.getElementsByTagName("input")[digit]); digit++) 
	{
		switch(tb.name)
		{
			case "Date": 
				date = tb.value;
				if(date == "")
					errorMessage += "&#149; No date set <br/>"
				break
			case "Lead": 
				lead = tb.value;
				lead = AddDailyWHYColour(lead);
				if(lead == "")
					errorMessage += "&#149; No lead text set <br/>"
				break
			case "Main": 
				main = tb.value;
				main = AddDailyWHYColour(main);
				if(main == "")
					errorMessage += "&#149; No main text set <br/>"
				break
			case "KGID": 
				kgid = tb.value;
				break
			case "Param": 
				param = tb.value;
				break
			case "URL": 
				url = tb.value;
				if(url == "" && kgid == "")
					errorMessage += "&#149; Both the KGID & URL cannot be empty at the same time <br/>"
				break
		}
	}
	
	// Error Check them
	if(errorMessage != "Please fix the following: <br/>")
	{
		FeedbackMessage.innerHTML = errorMessage;
	}
	else
	{
		// Update the Daily WHY Preview
		var whyDate = document.getElementById("WHYDate");
		whyDate.innerText = date;
		
		var LeadText = document.getElementById("DailyWHYPreviewLead");
		LeadText.innerHTML = lead;
		
		var MainText = document.getElementById("DailyWHYPreviewMain");
		MainText.innerHTML = main;
		
		//Add URL & PARAM
		if(kgid != "")
		{
			var home = "home.aspx?kgid=" + kgid;
			if(param != "")
				home += "&" + param;
			LeadText.href = home;
			MainText.href = home;
		}
		else
		{
			LeadText.href = url;
			MainText.href = url;
		}
	}
}

function AddDailyWHYColour(_string)
{
	_string = _string.replace("#WHY","<span class='StaticWHAT'>W</span><span class='StaticHOW'>H</span><span class='StaticWHY'>Y</span>");
	_string = _string.replace("#What","<span class='StaticWHAT'>What</span>");
	_string = _string.replace("#How","<span class='StaticHOW'>How</span>");
	_string = _string.replace("#Why","<span class='StaticWHY'>Why</span>");
	_string = _string.replace("#what","<span class='StaticWHAT'>what</span>");
	_string = _string.replace("#how","<span class='StaticHOW'>how</span>");
	_string = _string.replace("#why","<span class='StaticWHY'>why</span>");
	return _string;
}

function ChangeStyleClass(_element, _className)
{
  if(_element != null)
  {
    if(_className != null)
      _element.className = _className;
    else
      _element.className = '';
  }
}


function PrepareSignIn()
{
  if (m_KGAuthorHelpLastStep != null && WM_readCookie('AuthorHelp') == "true")
    SetSessionProperty('KGAuthorHelpLastStep', m_KGAuthorHelpLastStep);
}


function AuthorHelpStep(_targetStep)
{
	// Hide all Steps
	HideAuthorSteps();
	
	switch(_targetStep)
	{
		case "AuthorStep4":
			// Relocate the popup box.
			break;
	}
	
	// Show step
	document.getElementById(_targetStep).style.display = "block";

	m_KGAuthorHelpLastStep = _targetStep;
	// SetCookie ?
}


function HideAuthorSteps()
{
	document.getElementById("AuthorStep1").style.display = "none";
	document.getElementById("AuthorStep2").style.display = "none";
	document.getElementById("AuthorStep3").style.display = "none";
	document.getElementById("AuthorStep4").style.display = "none";
	document.getElementById("AuthorStep5").style.display = "none";
	document.getElementById("AuthorStep6").style.display = "none";
	document.getElementById("AuthorStep7").style.display = "none";
}

function AuthorStepRefocus()
{
	if(document.getElementById("AuthorStep3").style.display == "block" && document.getElementById("AuthorHelp").style.display == "block")
	{
		AuthorHelpStep("AuthorStep4");
	}
}

function AuthorStepCommitObjective()
{
	if(document.getElementById("AuthorStep1").style.display == "block" && document.getElementById("AuthorHelp").style.display == "block")
	{
		AuthorHelpStep("AuthorStep2");
	}
}

function ChangeHomeImage(image)
{
	var Img = document.getElementById("MainHomeImage");
	if(Img != null)
	{
		switch(image)
		{
			case 1: 
				Img.src = "Images/WhyCodeTestHighlighted2.png";
				break;
			case 2:
				Img.src = "Images/WhyCode.png";
				break;
		}
	}
}

function ShowHideOverflow(_controlID, _show, _applyToY, _applyToX)
{
  var container = document.getElementById(_controlID);
  if (container != null)
  {
    if (_show == true)
    {
      if (_applyToY == true)
        container.style.overflowY = 'auto';
      if (_applyToX == true)
        container.style.overflowX = 'auto';
    }
    else
    {
      if (_applyToY == true)
        container.style.overflowY = 'hidden';
      if (_applyToX == true)
        container.style.overflowX = 'hidden';
    }
  }
}

/******************* ContentSlides Navigation ****************************************/
var m_NavCotentSlidesDefault = 0;
var m_NavContentSlidesPath = new Array();
// JQuery Cycle
function NavContentSlides_Init()
{
  $.fn.cycle.defaults.timeout = 0;

  $('#ContentSlidesContainer')
      .cycle({
        fx: 'scrollLeft',
        speed: 500,
        timeout: 0,
        startingSlide: m_NavCotentSlidesDefault
      });

  $('#ContentSlidesContainer').cycle('pause');

  if (m_NavCotentSlidesDefault == 2)
  {
//    $('#WHWSearchBox').focus();
    ShowQuotationSlideShow();
  }

}

function WelcomePageMapsInit() {
	if (window.LeftPaneMyKnowledgeControl_CallbackTrigger)
		setTimeout("LeftPaneMyKnowledgeControl_CallbackTrigger('Action=repopulate');", 500);

	//document.getElementById("RightPaneStyle").style.width = getBrowserWidth() - parseInt(m_leftPaneWidth.replace('px', '')) +180;

}

function MapOfTheWeekInit() {

	$("#MapOfTheWeekTabs").tabs();
	$(".tabs-bottom .ui-tabs-nav, .tabs-bottom .ui-tabs-nav > *")
			.removeClass("ui-corner-all ui-corner-top")
			.addClass("ui-corner-bottom");

	$('#MapOfTheWeekTabs').css('display', 'block');
	$('#WelcomeTableList').css('display', 'block');

	
}

function SelectWelcomePageTab(_tabID) {

	$('#' + _tabID).css('display', 'block');

}


function ContentSlides_SearchBoxOnClick()
{
  if ($('#WHWSearchBox').val() == m_WHWSearchBoxDefaultText)
  {
    $('#WHWSearchBox').val(''); // clear default text
    $('#WHWSearchBox').css('color', 'black');
   }
   $('#StartWHYCodingHelp').css('display', 'block');
}


function ContentSlides_SearchBoxOnBlur()
{
  if ($('#WHWSearchBox').val() == '')
  {
    $('#WHWSearchBox').val(m_WHWSearchBoxDefaultText); // set default text
    $('#WHWSearchBox').css('color', 'gray');
   }
   $('#StartWHYCodingHelp').css('display', 'none');
}

var m_WHWSearchBoxCleared = false;
function ContentSlides_SearchBoxOnChange(e)
{
  e = e || window.event;
  var key = e.keyCode;

  // If the user has pressed enter
  if (key == 13)
  {
    var kndText = $('#WHWSearchBox').val();
    //alert(kndText);

    AutoCreateNewKG(kndText, true);
    return false;
  }
  else
  {
    if (m_WHWSearchBoxCleared == false)
    {
      $('#WHWSearchBox').val(''); // clear default text
      $('#WHWSearchBox').css('color', 'black');
      m_WHWSearchBoxCleared = true;
    }
    return true;
  }
}

function ContentSlides_SearchBoxGoButton() 
{
  var kndText = $('#WHWSearchBox').val();
  if (kndText == m_WHWSearchBoxDefaultText)
  	kndText = "";

  AutoCreateNewKG(kndText, true);

}

// _slideNum is 0 based index
function ContentSlides_GOTO(_slideNum)
{
  //if (IsXOOM())
    //ContentSlides_SetVisible(_slideNum);
  //else
    $('#ContentSlidesContainer').cycle(_slideNum);

  return false;
}

// Show or Hide for non cycle effect
// _slideNum is 0 based index
function ContentSlides_SetVisible(_slideNum)
{
  // hide all
  $('#ContentSlidesContainer').children().each(
    function ()
    {
      $(this).css("display", "none");
    }
  );

  // show selected slide
  if (_slideNum != null)
  {
    $('#ContentSlidesContainer').children('#Page' + _slideNum).css("display", "block");
  }

}

function OpenSiteHeaderLink(_page, _target) {
  DeselectHeaderLinks();

  /*if (!e) var e = window.event;
  if (e.target) targ = e.target;
  else if (e.srcElement) targ = e.srcElement;
  if (targ.nodeType == 3) // defeat Safari bug
    targ = targ.parentNode;*/

  if (_target == null)
  {
    _target = document.getElementById('NavBoxContentDiv' + _page);
  }

  SelectHeaderLink(_target);

  ContentSlideLink_OnClick(_page);
}

function ContentSlideLink_OnClick(_page, _showBackLink) {
  if (_showBackLink == null || _showBackLink == false)
  {
    m_NavContentSlidesPath = new Array(); //reset the value
    ShowHideBackLink(_page, false);
  }
  else
  {
    ShowHideBackLink(_page, true);
  }

  m_NavContentSlidesPath[m_NavContentSlidesPath.length] = _page;

  OpenLinkFromCorrectSourcePage(_page);
}

function ContentSlideLink_BackOnClick()
{
  if (m_NavContentSlidesPath.length > 1)
  {
    m_NavContentSlidesPath.pop(); // remove last item which is the current page
    var pageNum = m_NavContentSlidesPath[m_NavContentSlidesPath.length - 1];
    if (pageNum != null) {

      OpenLinkFromCorrectSourcePage(pageNum);

      if (m_NavContentSlidesPath.length > 1)
      {
        // display back link if exists
        ShowHideBackLink(pageNum, true);
      } else
      {
        ShowHideBackLink(pageNum, false);
      }
    }
  }
}


function OpenLinkFromCorrectSourcePage(_pageNum) {

  // First we need to check which page we are on
  var currentLocation = window.location.href;
  var currentPage = currentLocation.substring(currentLocation.lastIndexOf('/') + 1, currentLocation.length).toLowerCase();
  // If we are on home page open the popup
  if (currentPage.indexOf('home') > -1) {
    OpenDetailsOverlay(_pageNum);
    //    $('.DetailsOverlayContainer').css("border", "4px groove #ddd");
    $('.DetailsOverlayPageHolder').css("border", "medium groove #ddd");
  }
   else if (currentPage.indexOf('whycodeyourorganization') > -1) {
    // If we on the welcome page
    ContentSlides_GOTO(_pageNum);
    $('.DetailsOverlayPageHolder').css("border", "0");
  }
  else {
    // Otherwise redirect to the link on welcome page
    var redirectURL = currentLocation.substring(0, currentLocation.lastIndexOf('/') + 1) + 'Welcome.aspx?link=' + _pageNum;
    window.location = redirectURL;
  }
}

function ShowHideBackLink(_page, _show)
{

  var link = document.getElementById('ContentSlidePageBackLink_' + _page);
  if (link != null)
  {
    if (_show != null && _show == true)
      link.style.display = 'inline';
    else
      link.style.display = 'none';
  }
}

function SelectHeaderLink(_target) {
  $(_target).css("background-color", "#FDFDFD");
  if ($(_target).hasClass("NavGradientBG")) {
    $(_target).removeClass("NavGradientBG");
    $(_target).addClass("NavGradientBGSelected");
  }

}

function DeselectHeaderLinks() {
  $('.NavBoxContent').each(function () {
    $(this).css("background-color", "#EEEEEE");
    if ($(this).hasClass("NavGradientBGSelected")) {
      $(this).removeClass("NavGradientBGSelected");
      $(this).addClass("NavGradientBG");
    } 
  });
}



function OpenDetailsOverlay(_page) {
  // Change the content slide page
  ContentSlides_SetVisible(_page);

  // Show the control
  $('#DetailsOverlayPageHolder').css('left', Math.round((window.document.body.clientWidth / 2.0) * 0.23));
  $('#DetailsOverlay1').css('display', 'block');
}


function CloseDetailsOverlay() {
  // Hide the control
  var DetailsOverlay = document.getElementById("DetailsOverlay1");
  DetailsOverlay.style.display = "none";
  DeselectHeaderLinks();
}

function SignUpConfirmBackToKG()
{
  SetSessionForHomeClick();
  ShowKeepKGPrompt('welcome.aspx', false);
  return false;
}

// Demo slides javascript functions
function DemoSlides_GOTO(_pageNum)
{
	var numberOfSlides = $('.DemoSlideHeaderText').length;

	var nextPage = _pageNum % numberOfSlides;
	nextPage += 1;

	// Reset link for first slide
	if (_pageNum == (numberOfSlides - 1))
		nextPage = 0;

	// Change styling for the pager control
	$('.DemoPagerButton').toggleClass('DemoPagerButtonSelected', false);
	$('.DemoPagerButton' + nextPage).toggleClass('DemoPagerButtonSelected', true);


	// Hide the main map for certain pages - at the moment first and last
	if (_pageNum == (numberOfSlides - 2) || nextPage==0)
		$('.DemoSlideMainMap').css('display', 'none');
	else
		$('.DemoSlideMainMap').css('display', 'block');


	// Show the correct header text
	$('.DemoSlideHeaderText').css('display', 'none');
	$('#DemoSlideHeaderText' + nextPage).css('display', 'block');

	var nextLink = document.getElementById('DemoSlideLink');
	nextLink.onclick = function () { DemoSlides_GOTO(nextPage); };

	// Show restart on last page
	if (_pageNum == (numberOfSlides - 2))
		nextLink.innerHTML = 'Restart';
	else
		nextLink.innerHTML = 'Next';

	// Show any additional images
	$('.AdditionalImages').css('display', 'none');
	var additionalImageClass = 'AdditionalImage' + nextPage;	
	$('.' + additionalImageClass).css('display', 'block');
	$('.' + additionalImageClass).css('visibility', 'visible');


	// Do anything specific to a page
	clearInterval(flashElementHandle);
	switch (nextPage)
	{
		case 4:
			flashElementHandle = setInterval('FlashingElement("' + additionalImageClass + '")', 600);
			break;
	}

	// Here we want to control which content within the user control to show
	$('.DemoSlidePage').css('display', 'none');
	var DemoContentDiv = 'DemoContent' + nextPage;
	$('#' + DemoContentDiv).css('display', 'block');

}


var flashElementHandle;
function FlashingElement(_elementID)
{
	var element = document.getElementById(_elementID);
	if ( element && (element.style.visibility == 'hidden' || element.style.visibility == ''))
		element.style.visibility = 'visible';
	else
		element.style.visibility = 'hidden';
}

function ChangeHoverStyle(_fromClass, _toClass) {
	$('.' + _fromClass).attr('class', _toClass);
}

// Start new ui
function SetMapPaneStatus(_state) {

  if (window.SwitchDockingSide)
  {
    // This function is written so that _state can be any one of split, map or applications - how about none?
    if (!_state)
      _state = 'split'; // I will make the split view the default view

    switch (_state)
    {
      case 'split':
        SwitchDockingSide('split');
        break;
      case 'map':
        SwitchDockingSide('right');
        break;
      case 'applications':
        SwitchDockingSide('left');
        break;
    }
  }
}


function RedirectUserToStartJS() {
	var redirectURL = "home.aspx?LoadLastViewedMap=true";
	window.location = redirectURL;
}


/******** Touch Devices, please keep this block in the end of this js file ********/

function IsMobileAndTabletDevice()
{
  if (global_android == true || global_iOS == true || global_mobileOS == true || global_touchOS == true)
    return true;
  else
    return false;
}

function IsXOOM()
{
  if (global_agent.indexOf("mz604") != -1)
    return true;
  else
    return false;
}


function BlockMove(event)
{
  if (IsMobileAndTabletDevice())
  {
    if (event.touches.length == 1)
    {
      // Tell Safari not to move the window.
      event.preventDefault();
    }

    //alert(event.targetTouches.length + ' ' + event.touches.length);
  }
}

/******** End of Touch Devices, please keep this block in the end of this js file ********/

