var ajaxReq;
var ssoWindow;
var ssoPostParms = new Object();

var sessionRenewal = new Object();

var preservedSessionRenewal = new Object();
var pageBody = document.body;
var hdrGlobalMouseOverMenu = false;
var hdrGlobalMouseOverMenuDelay = 875;   // ms


// Add client "session awareness tracking" for some pages:
//The following variable has to be defined on any page that wants to use sessionRenewal:
//<script LANGUAGE="JavaScript">window.sessionRenewalUsed = true;</script>
if (window.sessionRenewalUsed != undefined)
{
    if (window.sessionRenewalUsed)
    {
        if (pageBody.attachEvent != undefined)   // attachEvent is an IE method
        {
            pageBody.onload = appendToFunction(pageBody.onload, "initSessionRenewalProcess()");
        }
        else
        {
            addHtmlAttribute(pageBody, "onload", "initSessionRenewalProcess();");
        }
    }
}


function appendToFunction(eventFunction, newJavascript)
{
    var newFunctionString = "";
    if (eventFunction != null)
    {
        var oldFunctionString = eventFunction.toString();
        var firstCurlyBracePosition = oldFunctionString.indexOf("{");
        var lastCurlyBracePosition = oldFunctionString.indexOf("}");
        var oldStatementsString = oldFunctionString.substring(firstCurlyBracePosition + 1, lastCurlyBracePosition);
        newFunctionString += oldStatementsString;
    }
    return newFunction = new Function(newFunctionString + ";" + newJavascript);
}


function appendToFunctionPutNewJSFirst(eventFunction, newJavascript)
{
    var newFunctionString = "";
    if (eventFunction != null)
    {
        var oldFunctionString = eventFunction.toString();
        var firstCurlyBracePosition = oldFunctionString.indexOf("{");
        var lastCurlyBracePosition = oldFunctionString.indexOf("}");
        var oldStatementsString = oldFunctionString.substring(firstCurlyBracePosition + 1, lastCurlyBracePosition);
        newFunctionString += oldStatementsString;
    }
    return newFunction = new Function(newJavascript + ";" + newFunctionString);
}


function clearFrames()
{
    if (window.top.location != window.document.location)
    {
        window.top.location.replace(window.document.location.href); //replace keeps url out of browser history
    }
}

function initMenuBar(menuBarName)
{
    if (document.all && document.getElementById)
    {
        menuBar = document.getElementById(menuBarName);

        if (menuBar == null) { return; }

        for (i = 0; i < menuBar.childNodes.length; i++)
        {
            node = menuBar.childNodes[i];

            if (node.nodeName=="DIV")
            {
                node.onmouseover
                    = function()
                      {
                            if (this.className.indexOf(" edlMenuMouseOver") < 0)
                            {
                                // Clear all others first.
                                parNode = this.parentNode;
                                for (i = 0; i < parNode.childNodes.length; i++)
                                {
                                    sibling = parNode.childNodes[i];

                                    if (sibling.nodeName == "DIV" && sibling.className.indexOf(" edlMenuMouseOver") >= 0)
                                    {
                                        sibling.className = sibling.className.replace(" edlMenuMouseOver", "");
                                    }
                                }
                                this.className += " edlMenuMouseOver";
                            }
                      }

                for (j = 0; j < node.childNodes.length; j++)
                {
                    subNode = node.childNodes[j];

                    if (subNode.nodeName == "DIV")
                    {
                        subNode.onmouseout
                            = function()
                                {
                                    this.parentNode.className = this.parentNode.className.replace(" edlMenuMouseOver", "");
                                }
                    }
                }
            }
        }
    }
}

function initMainMenuBar()
{
    initMenuBar("mainMenuBar");
}

function doNothing(e)
{
    return true;
}

function openPopupWindow(theURL, winName, features)
{
  var pWin = window.open(theURL, winName, features);
  pWin.focus();
}

function touchSession()
{
    var theURL   = "\CourseDetails.page";
    var winName  = "_touchsession";
    var features = "toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=no,left=2000,top=2000,width=10,height=10"
    var pWin = window.open(theURL, winName, features);
    pWin.close();
}

function goToPage()
{
    var i, args=goToPage.arguments;
    for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function openHelpWin()
{
    // context sensitive help
    submitEvent('clickHelp', 'TCNK=headerComponent');
}

function invokeHelpLink(pageNm)
{
    submitEvent( 'clickHelpLink', 'TCNK=headerComponent;helpLinkPageName='+pageNm);
}

function openPopupHelpWin(pgRoot)
{
    var pwin;
    var pgName;

    pgName = 'HelpPop' + pgRoot + '.page';
    pwin = window.open(pgName,"edline_popup_help","toolbar=no,resizable=1,scrollbars=1,width=550,height=375");
    pwin.focus();
}

function closePopupWin()
{
    //Check both win and doc, since NS returns non-null for closed window.opener
    if ((window.opener && window.opener.document) && (window.opener.closed == false))
        { window.opener.focus(); }
    self.close();
    return;
}


function displayMessage(message)
{
    if (message != null && message != '')
    {
        alert(message);
    }
}


function linkSubmitForm(formName, message, isFatalErrorMessage)
{
    displayMessage(message);

    if (message != null && message.length > 0 && isFatalErrorMessage)
    {
        return;
    }

    formName.submit();
    // Nothing can be done after the submit is called.
}


function submitSsoForm(message, isFatalErrorMessage)
{
    if (isFatalErrorMessage)
    {
        ssoWindow.close();
    }

    displayMessage(message);

    if (message != null && message.length > 0 && isFatalErrorMessage)
    {
        return;
    }

    ssoWindow.processForm(ssoPostParms.originalForm);
    ssoWindow.focus();
}


function submitSsoLink(theURL, winName, features, message, isFatalErrorMessage)
{
    displayMessage(message);

    if (message != null && message.length > 0 && isFatalErrorMessage)
    {
        ssoWindow.close();
        return;
    }

    if (winName == null || winName == '' || winName.length == 0)
    {
        ssoWindow.close();
        window.location.href = theURL;
        // Nothing can be done after this line.
    }
    else
    {
        ssoWindow.location.href = theURL;
        ssoWindow.focus();
    }
}


function linkOpenUrl(theURL, winName, features, message, isFatalErrorMessage)
{
    displayMessage(message);

    if (message != null && message.length > 0 && isFatalErrorMessage)
    {
        return;
    }

    if (winName == null || winName == '' || winName.length == 0)
    {
        window.location.href = theURL;
        // Nothing can be done after this line.
    }
    else
    {
        openPopupWindow(theURL, winName, features);
    }
}


function changeLoginInfo(websiteid)
{
  //submitEvent('changeLoginInfo', 'TCNK=headerComponent;websiteid=' + websiteid + ';returnpage=');
    submitEvent('changeLoginInfo', 'websiteid=' + websiteid); // <%= AuthWebsite.WEBSITE_ID %>
}


function hdrViewUserRedisplay(user_entid)
{
    submitEvent( 'viewAs','TCNK=viewAsBoxComponent;targetUserEntid='+user_entid + ';menuRedisplay=true');
}


// My Shortcuts View User Item
function va_msViewUser(user_entid)
{
    submitEvent( 'viewAs','TCNK=viewAsBoxComponent;targetUserEntid='+user_entid);
}

function va_onVusrListChange(frm, vusrListComboBox)
{
    var queryStringUserValue = vusrListComboBox[vusrListComboBox.selectedIndex].value;
    va_msViewUser(queryStringUserValue);
}

// Used for MyClasses combox box pulldown menu
function mcViewItm(res_entid)
{
    submitEvent( 'myClassesResourceView', 'TCNK=headerComponent;targetResEntid='+res_entid)
}

// Used for MyClasses combox box pulldown menu
function mcViewItm(res_entid, user_entid)
{
    submitEvent( 'myClassesResourceView', 'TCNK=headerComponent;targetResEntid='+res_entid+';targetViewAsUserEntid='+user_entid)
}

// Used for MyForms combo box pulldown menu
function mfViewItm(res_entid)
{
    // submitEvent( 'myFormsResourceView', 'TCNK=myFormsBoxComponent;targetResEntid='+res_entid)
    submitEvent( 'myFormsResourceView', 'TCNK=headerComponent;targetResEntid='+res_entid)
}

// Used for MyForms combo box pulldown menu
function mfViewItm(res_entid, user_entid)
{
    // submitEvent( 'myFormsResourceView', 'TCNK=myFormsBoxComponent;targetResEntid='+res_entid)
    submitEvent( 'myFormsResourceView', 'TCNK=headerComponent;targetResEntid='+res_entid+';targetViewAsUserEntid='+user_entid)
}

function loginButtonClicked()
{
    submitEvent('login','TCNK=headerComponent');
}


function downloadPluginInstaller(installerUrl)
{
    window.location = installerUrl;
    alert('The plugin is about to be downloaded.\n\nAfter the download is complete, please:\n\n1. INSTALL the plugin.\n\n2. RESTART the web browser.');
}


function updateGuestLoginBoxScreenName()
{
  document.guestLoginBox.screenName.value = document.guestLoginScreenNameBox.screenName.value
}

function inactiveCheck()
{
    var RECHECK_INTERVAL_SECS = 5;
    secsTilMsg     = secsTilMsg - RECHECK_INTERVAL_SECS;
    if (secsTilMsg <= 0)
    {
        var startWait = new Date().getTime();
        alert("To confirm that you are still there, please click the OK button within the next minute (" + new Date().toLocaleString() + ") or you will be logged out for security reasons.");
        secsTilMsg = CONFIRM_MSG_SECS;

        var  endWait = new Date().getTime();
        if ((endWait - startWait) <= CLICK_OK_BUTTON_DURATION * 1000)
        {
            touchSession();
            secsTilMsg = CONFIRM_MSG_SECS; // reset countdown time
        }
        else
        {
            window.top.location.href = "/timeout.html";
        }
    }
    setTimeout( function() { inactiveCheck() }, RECHECK_INTERVAL_SECS * 1000);
}

function submitEvent(eventName)
{
    document.EventForm.invokeEvent.value = eventName;
    document.EventForm.submit();
}

function submitEvent(eventName, parms)
{
    document.EventForm.invokeEvent.value = eventName;
    document.EventForm.eventParms.value = parms;
    document.EventForm.submit();
}

function rfop1(tar)
{
    document.Rd1Form.rdUrl.value = tar;
    document.Rd1Form.submit();
}

function rfop2(tar)
{
    document.Rd2Form.rdUrl.value = tar;
    document.Rd2Form.submit();
}

function handleSubmitOnEnterHeaderIncluded(e)
{
    var keyPressed = '';
    var eventTarget = null;
    var isMSIE = navigator.userAgent.indexOf ('MSIE') != -1;

    if (isMSIE)
    {
        keyPressed  = String.fromCharCode (window.event.keyCode);
    }
    else
    {
        keyPressed = String.fromCharCode(e.which);
    }
    var eventTarget = e ? e.target : window.event.srcElement;
    var isTextArea = (eventTarget.type == 'textarea');

    if (!isTextArea && (keyPressed == "\r" || keyPressed == "\n"))
    {
        if (HAS_DEFAULT_ENTER_KEY)
        {
            if (HAS_PAGE_VALIDATION)
            {
                pageValidationSucceeded = eval(PAGE_VALIDATION);
            }
            else
            {
                pageValidationSucceeded = true;
            }

            if (pageValidationSucceeded)
            {
                try
                {
                    eval(DEFAULT_ENTER_KEY_NAME).click();
                }
                catch(ex)
                {
                }
                window.document.onkeypress = doNothing;
            }
            return false;
        }
        else
        {
            return isTextArea;
        }
    }

    return true;
}


function isAjaxSupported()
{
    return initAjaxRequest();
}


function initAjaxRequest()
{
    var result = "yes";

    try
    {
         // Firefox, Opera 8.0+, Safari
         ajaxReq = new XMLHttpRequest();
    }
    catch (e)
    {
         // Internet Explorer
         try
         {
              ajaxReq = new ActiveXObject("Msxml2.XMLHTTP");
         }
         catch (e)
         {
              try
              {
                  ajaxReq = new ActiveXObject("Microsoft.XMLHTTP");
              }
              catch (e)
              {
                  result = "no";
              }
         }
    }

    return result;
}


function refer(target)
{
    var theUrl = "http://www.edline.net/tr.html?tr=" + target;
    openPopupWindow(theURL, "_blank", "");
}


function requestAjaxSsoData(docEntid)
{
   ssoWindow = window.open("/LinkSsoWindow.html", "_" + docEntid);

   // Initialize ajaxReq variable
   var ignoreAnswer = initAjaxRequest();

   ajaxReq.onreadystatechange = receiveAjaxSsoData;  // <-- set callback function to process response

   // The framework prefers Ajax POST requests (vs GET)
   var url = "/UserSsoData.page";
   var key = "" + docEntid + "" + document.EventForm.ajaxRequestKeySuffix.value;
   var parameters = "key=" + key;

   ajaxReq.open('POST', url, true);
   ajaxReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   ajaxReq.setRequestHeader("Content-length", parameters.length);
   ajaxReq.setRequestHeader("Connection", "close");
   ajaxReq.send(parameters);
}


function receiveAjaxSsoData()
{
  if (ajaxReq.readyState == 4)
  {
    if (ajaxReq.status == 200)
    {
      var entries = ajaxReq.responseXML.getElementsByTagName("entry");

      // Grab the first entry (there is only one)
      var entry = entries[0];

      var method              = entry.getElementsByTagName("method")[0].firstChild.data;
      var originalJavascript  = entry.getElementsByTagName("originalJavascript")[0].firstChild.data;
      var originalForm        = entry.getElementsByTagName("originalForm")[0].firstChild.data;
      var message             = entry.getElementsByTagName("message")[0].firstChild.data;
      var isFatalErrorMessage = entry.getElementsByTagName("isFatalErrorMessage")[0].firstChild.data == 'true';

      // Safari needed non-blank values for the 5 fields above.  Trim message field.
      if (message == " ")
      {
          message = "";
      }

      // We have retrieved all the variables we need to null it out as soon as possible in case a post/submit
      // occurs which exits the page.
      ajaxReq = null;

      // Handle the GET method (url with query string parameters):
      if (method == 'GET')
      {
        var myFunction = new Function("" + originalJavascript);
        myFunction.call();
      }

      // Handle the POST method:
      if (method == 'POST')
      {
        if (isFatalErrorMessage)
        {
            submitSsoForm(message, isFatalErrorMessage);
        }
        else
        {
            // Safari needs a slight delay (1 sec)
            ssoPostParms.originalForm = originalForm;
            ssoPostParms.message = message;
            ssoPostParms.isFatalErrorMessage = isFatalErrorMessage;
            setTimeout( function() { submitSsoForm(ssoPostParms.message, ssoPostParms.isFatalErrorMessage) }, 1000);
        }
      }   // if POST

    }   // ajaxReq.status
  }   // ajaxReq.readyState
}   // function receiveAjaxSsoData


function requestAjaxSessionRenewal()
{
   sessionRenewal.sessionLastAccessTime = new Date();

   var url = "/SessionRenewal.page";
   var parameters = "key=" + document.EventForm.ajaxRequestKeySuffix.value;

   // Initialize ajaxReq variable
   var ignoreAnswer = isAjaxSupported();   // already tested at login time

   ajaxReq.onreadystatechange = receiveAjaxSessionRenewal;  // <-- function to process response
   ajaxReq.open('POST', url, true);  // The framework prefers Ajax POST requests (vs GET)
   ajaxReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   ajaxReq.setRequestHeader("Content-length", parameters.length);
   ajaxReq.setRequestHeader("Connection", "close");
   ajaxReq.send(parameters);
}


function receiveAjaxSessionRenewal()
{
  if (ajaxReq.readyState == 4)
  {
    if (ajaxReq.status == 200)
    {
	  // Do nothing with response
      ajaxReq = null;
    }
  }
}


function addHtmlAttribute(element, attributeName, attributeValue)
{
    var tempVar = "";
    if (element.hasAttribute(attributeName) == true)
    {
       tempVar = element.getAttribute(attributeName);
    }
    element.setAttribute(attributeName, attributeValue + tempVar);
}


function renewSessionWithAutoRefresh()
{
    return (   window.sessionRenewalAutoRefresh === true
            && window.sessionRenewalAutoRefreshIntervalSeconds !== null
            && window.sessionRenewalAutoRefreshLimit !== null)
}


function initSessionRenewalProcess()
{
    if (renewSessionWithAutoRefresh())
    {
        initSessionRenewalProcessByAutoRefresh();
    }
    else
    {
        initSessionRenewalProcessByUserActivity();
    }
}


function initSessionRenewalProcessByAutoRefresh()
{
    sessionRenewal.enabled = document.EventForm.sessionRenewalEnabled.value;

    if ((sessionRenewal.enabled == "yes") && (isAjaxSupported() == "yes"))
    {
        sessionRenewal.autoRefreshIntervalSeconds = window.sessionRenewalAutoRefreshIntervalSeconds;
        sessionRenewal.autoRefreshCount = 0;
        sessionRenewal.autoRefreshLimit = window.sessionRenewalAutoRefreshLimit;

        setTimeout( function() { autoRenewSession() }, 1000 * sessionRenewal.autoRefreshIntervalSeconds)
    }
}


function initSessionRenewalProcessByUserActivity()
{
   var form = document.EventForm;

   sessionRenewal.sessionLastAccessTime = new Date();
   sessionRenewal.timeoutId = null;
   sessionRenewal.enabled = form.sessionRenewalEnabled.value;

   if ((sessionRenewal.enabled == "yes") && (isAjaxSupported() == "yes"))
   {
      if (pageBody.attachEvent != undefined)   // attachEvent is an IE method that does not work correctly but does exist.
      {
          pageBody.onunload    = appendToFunction(pageBody.onunload,    "finalizeSessionRenewalProcess()");
          pageBody.onmouseup   = appendToFunction(pageBody.onmouseup,   "registerClientActivity()");
          pageBody.onkeyup     = appendToFunction(pageBody.onkeyup,     "registerClientActivity()");
          pageBody.onmouseover = appendToFunction(pageBody.onmouseover, "registerClientActivity()");
      }
      else
      {
          addHtmlAttribute(pageBody, "onunload",    "finalizeSessionRenewalProcess();");
          addHtmlAttribute(pageBody, "onmouseup",   "registerClientActivity();");
          addHtmlAttribute(pageBody, "onkeyup",     "registerClientActivity();");
          addHtmlAttribute(pageBody, "onmouseover", "registerClientActivity();");
      }

      sessionRenewal.hardTimeoutSeconds           = form.sessionHardTimeoutSeconds.value;
      sessionRenewal.intervalSeconds              = form.sessionRenewalIntervalSeconds.value;
      var initialCheckIntervalSeconds             = Math.max(15, Math.min(form.sessionIgnoreInitialActivitySeconds.value,
                                                                          form.sessionRenewalIntervalSeconds.value)); 
      sessionRenewal.ignoreInitialActivitySeconds = initialCheckIntervalSeconds; 
      sessionRenewal.maxNumberOfRenewals          = form.sessionRenewalMaxNumberOfRenewals.value;
      sessionRenewal.sessionHardTimeoutSeconds    = form.sessionHardTimeoutSeconds.value;
      sessionRenewal.count                        = 0;
      sessionRenewal.clientActivityOccurred       = false;

      sessionRenewal.timeoutId                    = setTimeout( function() { renewSession() }, 1000 * initialCheckIntervalSeconds);
   }
}


function finalizeSessionRenewalProcess()
{
  if (sessionRenewal.timeoutId != null)
  {
     clearTimeout(sessionRenewal.timeoutId);
  }
}


var timeFudgeSeconds       = 10;  // 10 or 15 seconds are the best values to pick between.
var timeFudgeSecondsOffset =  5;  // MUST be less than timeFudgeSeconds.

function renewSession()
{
  var currentTime = new Date();

  var sessionRenewed = false;
  sessionRenewal.timeoutId = null;

  var isFirstRenewalCheck = sessionRenewal.count <= 0; 
  var sessionAgeInSeconds = Math.round(((currentTime - sessionRenewal.sessionLastAccessTime) / 1000)); 
  var isSessionTimedOut   = sessionAgeInSeconds >= sessionRenewal.hardTimeoutSeconds; 
  var secondsUntilTimeOut = 0; 

  preservedSessionRenewal.enabled                      = sessionRenewal.enabled;
  preservedSessionRenewal.intervalSeconds              = sessionRenewal.intervalSeconds;
  preservedSessionRenewal.maxNumberOfRenewals          = sessionRenewal.maxNumberOfRenewals;
  preservedSessionRenewal.count                        = sessionRenewal.count;
  preservedSessionRenewal.clientActivityOccurred       = sessionRenewal.clientActivityOccurred;
  preservedSessionRenewal.hardTimeoutSeconds           = sessionRenewal.hardTimeoutSeconds;
  preservedSessionRenewal.ignoreInitialActivitySeconds = sessionRenewal.ignoreInitialActivitySeconds; 
  preservedSessionRenewal.sessionLastAccessTime        = sessionRenewal.sessionLastAccessTime;

  if (!isSessionTimedOut)
  {
    if (sessionRenewal.clientActivityOccurred == true)
    {
      // Do NOT renew session on the first check.
      // Also be aware that the first check interval is 60 seconds. The reason is that we
      // want to ignore any user activity for the first 60 seconds that the page is viewed
      // because almost every page will have some activity when it is first displayed and
      // we do not want to renew the session if they used it less than a minute and then
      // did nothing else.
      if (!isFirstRenewalCheck)  
      {
        requestAjaxSessionRenewal();
        sessionRenewed = true;
        sessionRenewal.sessionLastAccessTime = new Date();
      }

      sessionRenewal.clientActivityOccurred = false;
    }

    sessionRenewal.count = sessionRenewal.count + 1;

    sessionAgeInSeconds = Math.round(((currentTime - sessionRenewal.sessionLastAccessTime) / 1000)); // Need to recalc in case sessionLastAccessTime changed. 
    secondsUntilTimeOut = Math.max(0, sessionRenewal.hardTimeoutSeconds - sessionAgeInSeconds); 

    // If max number of renewal intervals not reached, set timer to check again later:
    if (sessionRenewal.count < sessionRenewal.maxNumberOfRenewals)
    {
      var nextCheckIntervalSeconds = sessionRenewal.intervalSeconds;

      if (isFirstRenewalCheck)
      {
          var remainingCheckIntervalSeconds = sessionRenewal.intervalSeconds - sessionRenewal.ignoreInitialActivitySeconds;

          // If less than 12 seconds to the next check, then simply do the full next check and skip this special block.
          if (remainingCheckIntervalSeconds > timeFudgeSeconds) 
          {
              // After the ignore initial activity time period passes, we want to check again
              // when we would have checked if we had waited sessionRenewal.intervalSeconds,
              // so set the check interval to the remaining number of seconds. 
              nextCheckIntervalSeconds = remainingCheckIntervalSeconds;
          }
      } 

      if (secondsUntilTimeOut < (timeFudgeSeconds + timeFudgeSecondsOffset))
      {
        // Check again right AFTER the session times out so we can display javascript alert that session timed out.
        nextCheckIntervalSeconds = secondsUntilTimeOut + Math.max(5, (timeFudgeSeconds - timeFudgeSecondsOffset)); 
      }
      else if (secondsUntilTimeOut < (nextCheckIntervalSeconds + timeFudgeSeconds))
      {
        // Check for activity and be able to renew the session 10 seconds before the session times out.
        nextCheckIntervalSeconds = secondsUntilTimeOut - timeFudgeSeconds; 
      } 

      sessionRenewal.timeoutId = setTimeout( function() { renewSession() }, 1000 * nextCheckIntervalSeconds);
    }
  }

  preservedSessionRenewal.sessionRenewed = sessionRenewed;
  preservedSessionRenewal.sessionAgeInSeconds = sessionAgeInSeconds;
  preservedSessionRenewal.secondsUntilTimeOut = secondsUntilTimeOut;

  if (isSessionTimedOut)
  {
    sessionRenewal.maxNumberOfRenewals = 0;
    preservedSessionRenewal.maxNumberOfRenewals = sessionRenewal.maxNumberOfRenewals;
  }

// This line is used for testing that the session renewal is working correctly.
//var w = window.open("/SessionRenewalTraceWindow.html", "traceWindow");

  if (isSessionTimedOut)
  {
    alert('Due to inactivity, your Edline session has timed out.');
  }
}


function autoRenewSession()
{
    if (sessionRenewal.autoRefreshCount < sessionRenewal.autoRefreshLimit)
    {
        requestAjaxSessionRenewal();
        sessionRenewal.autoRefreshCount++;
        setTimeout( function() { autoRenewSession() }, 1000 * sessionRenewal.autoRefreshIntervalSeconds);
    }
    else 
    {
        initSessionRenewalProcessByUserActivity();
    }
}


function registerClientActivity()
{
    sessionRenewal.clientActivityOccurred = true;
}


// Added function mdss 4/1/08
function setElementHeight(pElementId, pHeight)
{
    var elem = document.getElementById(pElementId);
    if (  (elem != null) && (elem != undefined)  )
    {
        elem.style.height = pHeight;
    }
}


// Added function mdss 11/2/07
function setElementWidth(pElementId, pWidth)
{
    var elem = document.getElementById(pElementId);
    if (  (elem != null) && (elem != undefined)  )
    {
        elem.style.width = pWidth;
    }
}


function hdrGetWindowWidth(myWindow)
{
    if (myWindow.innerWidth)
        return myWindow.innerWidth;
    else if (myWindow.document.compatMode=='CSS1Compat')
        return myWindow.document.documentElement.clientWidth;
    else
        return myWindow.document.body.clientWidth;
}


function hdrGetWindowHeight(myWindow)
{
    if (myWindow.innerHeight)
        return myWindow.innerHeight;
    else if (myWindow.document.compatMode=='CSS1Compat')
        return myWindow.document.documentElement.clientHeight;
    else
        return myWindow.document.body.clientHeight;
}


/* Two remarks:
    1. In function below, wouldn't work if function calls made to hdrSetMouseEnteredMenu() and
        hdrSetMouseLeftMenu().
    2. For anchor tags, hdrAddMouseEnterLeaveTracking couldn't be called directly; their onmouseover and 
        onmouseout events had to be coded.
 */
function hdrAddMouseEnterLeaveTracking(pMenuId)
{
    // Track when mouse enters and leaves:
    $("#" + pMenuId).mouseenter(
            function() { hdrGlobalMouseOverMenu = true; }
            ).
            mouseleave(
            function() { hdrGlobalMouseOverMenu = false; setTimeout( function() { hdrMouseOverMenuCheck() }, hdrGlobalMouseOverMenuDelay); }
            );
}


function hdrSetMouseEnteredMenu()
{
    hdrGlobalMouseOverMenu = true;
}


function hdrSetMouseLeftMenu()
{
    hdrGlobalMouseOverMenu = false; setTimeout( function() { hdrMouseOverMenuCheck() }, hdrGlobalMouseOverMenuDelay);
}


function hdrMouseOverMenuCheck()
{
    if (!hdrGlobalMouseOverMenu)
    {
        hideAllMenus();
        if (window.hideMenuBarMenus != undefined && window.hideMenuBarMenus != null)
        {
            hideMenuBarMenus();
        }
    }
}


function hdrIsSafari_1_3_2()
{
    return navigator.userAgent.indexOf("Safari/312") >= 0;
}


function hdrLaunchDvbGoToLink(pDocEntid, pLinkHref, pLinkInternalImported)
{
    // If NOT called from group home, make call using a doc view reference
    if (window.ghPinnedDocsToLoad == undefined)
    {
        docViewBody.dvbGoToLink(pLinkHref,pLinkInternalImported);
    }

    // If called from group home, make call using pinned doc reference
    else
    {
        window.frames["iFrame_edlElement_" + pDocEntid + "_document"].dvbGoToLink(pLinkHref,pLinkInternalImported);
    }
}


