
  // Set some global values
  gcCHAT_LOGIN_URL = "http://intelliwave.com/support/client.php";
  gcCSR_CHECK_URL = "/chat-status-check.php";
  gcPROMPT_CHAT_SECS = 90;   // How long user needs to be browsing before we display the pop-up
  gcSET_TIMEOUT_MS = 3000;    // How often to call the callback function for updating
  gcPOPUP_ELEMENT_ID = "styledPopup";

  // Cookie value names
  gcCOOKIE_TEST = "TestCookie";
  gcCOOKIE_SECS_ONLINE = "SecondsOnline";
  gcCOOKIE_SEMAPHORE = "AJAXSemaphore";

  // Some global vars
  gSecsOnline = 0;
  gLastUpdated = Math.round(new Date().getTime() / 1000);
  gXmlHttp = null;

  // Kick things off when the document has completed loading
  window.setTimeout("init()", 1000);
  
  //---------------------------------------------------------------------------
  //
  //
  function debugOutput(msg) {
    var debugElement = document.getElementById("debug");
    
    if (debugElement) {
      debugElement.innerHTML = msg;
    }

  }

  //---------------------------------------------------------------------------
  // Set things up
  //
  function init() {
  
    // Nothing to do but bail if cookies are disabled
    if (!cookiesEnabled()) {
debugOutput("Cookies are disabled in this browser.  Cookies must be enabled for the popup code to function.");
      return;
    }
    
    // No reason to continue if the semaphore has been set previously
    if (getCookie(gcCOOKIE_SEMAPHORE) != null) {
debugOutput("Either another window has initiated the popup or the user has been prompted previously.  We will not continue to prompt the user after the first time, so the pop-up code is now disabled. <a href='javascript:resetAll(); window.location.reload();'>Click here to reset the cookies to test again</a>");
      return;
    }
    
    // Grab the number of seconds the user has been online from the cookie, if it exists
    secsOnline = parseInt(getCookie(gcCOOKIE_SECS_ONLINE), 10);
    gSecsOnline = ((secsOnline == null) || isNaN(secsOnline)) ? 0 : secsOnline;
    
    // Setup a callback
    window.setTimeout("timeoutCallback()", gcSET_TIMEOUT_MS);
  }

  //---------------------------------------------------------------------------
  // Callback function to update the amount of time spent browsing on the site
  //
  function timeoutCallback() {
  
    // No use continuing timing if the semaphore has been acquired by another window
    if (getCookie(gcCOOKIE_SEMAPHORE) != null) {
debugOutput("Either another window has initiated the popup or the user has been prompted previously.  We will not continue to prompt the user after the first time, so the pop-up code is now disabled. <a href='javascript:resetAll(); window.location.reload();'>Click here to reset the cookies to test again</a>");
      return;
    }
    
    // Update the timer and save the value back to the cookie
    var curTime = Math.round(new Date().getTime() / 1000);
    gSecsOnline += (curTime - gLastUpdated);
    gLastUpdated = curTime;
    setCookie(gcCOOKIE_SECS_ONLINE, gSecsOnline, 60*60*24*365, "/");

var promptIn = gcPROMPT_CHAT_SECS - gSecsOnline;
var output = (promptIn <= 0) ? "checking now..." : "Will check in " + promptIn + " seconds.";
debugOutput("Counting down to check for a live CSR. " + output);
    
    // Have they been on the site long enough to prompt to join the chat?
    if (gSecsOnline >= gcPROMPT_CHAT_SECS) {

      // Is the semaphore cleared?
      if (getCookie(gcCOOKIE_SEMAPHORE) == null) {
      
        // Set it, helps ensure only one window or tab goes through this stage
        setCookie(gcCOOKIE_SEMAPHORE, "Semaphore", 60*60*24*365, "/");
        
        // We'll check for a CSR online asynchonously via AJAX, so just exit after the call
        checkForCsr();
        return;
      }
      
      // The semaphore was set previously, so exit without setting another callback
      else {
        return;
      }
    }
    
    // Set the timeout to call this function again
    window.setTimeout("timeoutCallback()", gcSET_TIMEOUT_MS);
  }

  //---------------------------------------------------------------------------
  // Redirect the browser to the live chat URL
  //
  function loadChat() {
    window.location = gcCHAT_LOGIN_URL;
  }

  //---------------------------------------------------------------------------
  // Test if cookies are enabled.
  //
  function cookiesEnabled() {

    setCookie(gcCOOKIE_TEST, "OK", 60);
    return (getCookie(gcCOOKIE_TEST) == "OK");
  }
  
  //---------------------------------------------------------------------------
  //
  // expires should be specified in seconds
  //
  function setCookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());


    // if the expires variable is set, make the correct
    // expires time by multiplying by 1000 to get milliseconds
    if (expires) {
      expires = expires * 1000;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" +escape( value ) +
      ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
      ((path) ? ";path=" + path : "") +
      ((domain) ? ";domain=" + domain : "") +
      ((secure) ? ";secure" : "");
  }

  //---------------------------------------------------------------------------
  // Returns the value of a cookie corresponding to the name
  // Returns null if the cookie can't be found
  //
  function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
      var j = i + alen;
      if (document.cookie.substring(i, j) == arg) {
        return getCookieVal (j);
      }
      i = document.cookie.indexOf(" ", i) + 1;
      if (i == 0) {
        break;
      }
    }

    return null;
  }
  
  //---------------------------------------------------------------------------
  // Utility function to get the cookie's value
  //
  function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) {
      endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
  }


  //---------------------------------------------------------------------------
  //
  //
  function checkForCsr() {

    // Attempt to create an XMLHTTP object
    gXmlHttp = GetXmlHttpObject();
    if (gXmlHttp == null) {
      return;
    }
    
    // Setup the asynchonous call to check if a CSR is currently online
    gXmlHttp.onreadystatechange = stateChanged;
    gXmlHttp.open("GET", gcCSR_CHECK_URL+"?sid="+Math.random(), true);
    gXmlHttp.send(null);
    
debugOutput("Checking if a CSR is online...");
  }

  //---------------------------------------------------------------------------
  //
  //
  function stateChanged() {
    if (gXmlHttp.readyState == 4 || gXmlHttp.readyState == "complete") {

      // Is a CSR online at the moment?
      if (gXmlHttp.responseText == "1") {
debugOutput("A CSR is online, prompting now.");
      
        // Prompt the user
        showPopup(gcPOPUP_ELEMENT_ID);
      }
      
      // CSR is currently offline
      else {
      
        // Reset the semaphore and counter and we'll try again later
debugOutput("CSR is offline, resetting...");
        resetAll();
      }
    }
  }
  
  //---------------------------------------------------------------------------
  //
  //
  function resetAll() {
    setCookie(gcCOOKIE_SEMAPHORE, "", -1000, "/");
    gSecsOnline = 0;
    gLastUpdated = Math.round(new Date().getTime() / 1000);
    setCookie(gcCOOKIE_SECS_ONLINE, gSecsOnline, 60*60*24*365, "/");
    window.setTimeout("timeoutCallback()", gcSET_TIMEOUT_MS);
  }

  //---------------------------------------------------------------------------
  //
  //
  function GetXmlHttpObject() {
    var xmlHttp = null;

    try {
      // Firefox, Opera 8.0+, Safari
      xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
      // Internet Explorer
      try {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
    return xmlHttp;
  }

  //---------------------------------------------------------------------------
  //
  // Sloppy stuff left over from incorporating the popup window code.  Would
  // be nice to clean things up and encapsulate these globals
  //
  var isdrag = false;
  var x, y;
  var dobj;
  document.onmousedown = selectmouse;
  document.onmouseup = function() {isdrag=false;};


  //---------------------------------------------------------------------------
  //
  //
  function showPopup(elementId) {
    var element = document.getElementById(elementId);
    var pageOffset = findPosX(document.getElementById("content_main"));
    
    // Due to different browser naming of certain key global variables,
    // we need to do three different tests to determine their values

    // Determine how much the visitor had scrolled
    var scrolledX, scrolledY;
    if (self.pageYOffset) {
      scrolledX = self.pageXOffset;
      scrolledY = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) {
      scrolledX = document.documentElement.scrollLeft;
      scrolledY = document.documentElement.scrollTop;
    }
    else if (document.body) {
      scrolledX = document.body.scrollLeft;
      scrolledY = document.body.scrollTop;
    }

    // Determine the coordinates of the center of browser's window
    var centerX, centerY;
    if (self.innerHeight) {
      centerX = self.innerWidth;
      centerY = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) {
      centerX = document.documentElement.clientWidth;
      centerY = document.documentElement.clientHeight;
    }
    else if (document.body) {
      centerX = document.body.clientWidth;
      centerY = document.body.clientHeight;
    }

    //var leftOffset = scrolledX + (centerX - 226) / 2 - pageOffset;
    var leftOffset = scrolledX + 25;
    var topOffset = scrolledY + (centerY - 400) / 2;

    // Set the style attribs
    element.style.top = topOffset + "px";
    element.style.left = leftOffset + "px";
    element.style.display = "block";
  }
  
  //---------------------------------------------------------------------------
  //
  //
  function findPosX(obj) {
    var curleft = 0;
    
    if(obj.offsetParent) {
      while(1) {
        curleft += obj.offsetLeft;
        if (!obj.offsetParent) {
          break;
        }

        obj = obj.offsetParent;
      }
    }
    else if(obj.x) {
        curleft += obj.x;
    }
    
    return curleft;
  }

  //---------------------------------------------------------------------------
  //
  //
  function findPosY(obj) {
    var curtop = 0;
    
    if(obj.offsetParent) {
      while(1) {
        curtop += obj.offsetTop;
        if (!obj.offsetParent) {
          break;
        }

        obj = obj.offsetParent;
      }
    }
    else if (obj.y) {
      curtop += obj.y;
    }
    
    return curtop;
  }


  //---------------------------------------------------------------------------
  //
  //
  function hidePopup() {
    document.getElementById(gcPOPUP_ELEMENT_ID).style.display = "none";
  }

  //---------------------------------------------------------------------------
  //
  //
  function movemouse(e) {
    if (!e) e = window.event;
    
    if (isdrag) {
      dobj.style.left = tx + e.clientX - x + "px";
      dobj.style.top  = ty + e.clientY - y + "px";
      return false;
    }
  }

  //---------------------------------------------------------------------------
  //
  //
  function selectmouse(e) {
    var nn6 = document.getElementById && !document.all;
    var fobj = nn6 ? e.target : event.srcElement;
    var topelement = nn6 ?  "HTML"  :  "BODY" ;
    
    if (!e) e = window.event;
    
    while (fobj.tagName != topelement && fobj.getAttribute("id") != "titleBar") {
      fobj = nn6 ? fobj.parentNode : fobj.parentElement;
    }

    if (fobj.getAttribute("id") == "titleBar") {
      isdrag = true;
      dobj = document.getElementById("styledPopup");
      tx = parseInt(dobj.style.left+0);
      ty = parseInt(dobj.style.top+0);
      x = e.clientX;
      y = e.clientY;
      document.onmousemove = movemouse;
      return false;
    }
  }
