/*********************************************************
 * 
 * onexit.js - Javascript exit logger
 * 
 * Copyright 2006 KeyRelevance
 *
 * KeyRelevance.com
 *
 * Permission to use granted as long as this copyright notice 
 * is left intact.
 *
 * Comments?  Improvements?  onexit (at) keyrelevance (dot) com
 *
 * To use:
 * 1) copy this file to the web server
 * 
 * 2) Copy the exiturl.htm file to the server as well.  If placed on the 
 *     server somewhere other than the domain root, you will need to
 *     change the uLog variable, below, as well.  If you are using BASE tags, 
 *     make sure you use an absolute URL, or that the relative URL works in 
 *     conjunction with the BASE.
 * 
 * 3) include this javascript reference before the BODY tag 
 *     on each landing page (or every page on the site) by adding
 *     <script src="(thisurllocation]"></script>
 *     to the web page (using the correct location for the JS file).
 * 
 * 4) Add an onunload="logunload()" attribute to
 *     each page's BODY tag as well
 *
 * 5) somewhere in the body, (perhaps just before the closing </body> tag)
 *    add an image tag like the following:
 *    <img id='onexit' width=0 height=0 border=0>
 *
 * When the site is exited, either by clicking an external 
 * link or by hitting the "Back" button, an entry in the 
 * access_log for uLog will be recorded.
 *
 ************************************************************/

var uLog = 'http://www.keyrelevance.com/exiturl.htm?url=';
//
// NO CHANGES NEEDED AFTER THIS POINT
//

document.onclick = logexitclick; // route all click events
var leftbyclick=false;
function whenerror() {
 document.location.href = url; 
}

function logunload() {
   if (!document.getElementById) return true; // DOM only

   if(leftbyclick) {
      return false;
   }
   var eTag = document.getElementById('onexit');

   eTag.onerror = whenerror ;
   eTag.src = uLog+'backbutton';
   var now = new Date();
   // this is a hack, but it allows the server time to log the exit 
   // before the visitor actually leaves
   var exitTime = now.getTime() + 1000;
   while (true) {
       now = new Date();
       if (now.getTime() > exitTime)
           return false;
   }
}
function logexitclick(e) {
   leftbyclick=true;  // keeps logunload from logging exit
   if (!document.getElementById) return true; // DOM only
   var eTag = document.getElementById('onexit');

   if (!e) { 
      var e = window.event; // IE
      var eClicked = e.srcElement;
   } else { 
      var eClicked = e.target; // FF
   }
   // walk the DOM til we find the anchor
   while (String(eClicked.nodeName) != "A") {
      eClicked=eClicked.parentNode; 
      if (String(eClicked.nodeName) == "HTML") return true;
   }
   url = String(eClicked);
   if (url.indexOf("http") != -1 && url.indexOf(location.hostname) == -1) {
      eTag.onerror = whenerror ;
      eTag.src = uLog + url;
      return false; 
   }
   return true; 
}
