// Change these to match your requirements
var siFireImmediately = true; // Set to false if you want to fire at the window.onload event
var siTrackerUrl      = "http://si.swinton.co.uk/images/track.gif";
var siCookieName      = "SIVISITOR";
var siCookieQPName    = "simigvis";
var siCookiePath      = "/";
var siCookieTimeout   = 315360000000;
var siDomainList      = new Array(".co.uk",".com");
var siAutoTracer      = true;
var siCentralCookie   = false;
var siCentralReqName  = "req";
var siCentralRefName  = "refer";
var siCentralURL      = "";
// These will be set by functions below - note image set is needed to stop variables going out of scope
var siIsCookieNew	    = "N"; // Default; set to true if a cookie is genned
var siCookieValue     = "";
var siPageID          = "";
var siTracerPath      = "";
var siTracerQuery     = "";
var siImageSet        = new Array(1);
var siReferrer        = document.referrer;
var siRequest         = document.URL;


function SiEncodeString(Input)
{
  var TransChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var Output     = "";
  for (var i = 0; i < Input.length; i += 3)
  {
    var NumBytesLeft = Input.length - i;
    var Value        = 0;
    Value  = (Input.charCodeAt(i) << 16) & 0x00ff0000;
    Value |= (NumBytesLeft > 1)? (Input.charCodeAt(i + 1) << 8) & 0x0000ff00 : 0;
    Value |= (NumBytesLeft > 2)? Input.charCodeAt(i + 2) & 0x000000ff : 0;
    Output += TransChars.charAt((Value & 0x00fC0000) >> 18);
    Output += TransChars.charAt((Value & 0x0003f000) >> 12);
    Output += (NumBytesLeft > 1)? TransChars.charAt((Value & 0x00000fc0) >> 6) : '_';
    Output += (NumBytesLeft > 2)? TransChars.charAt((Value & 0x0000003f)) : '_';
  }
  return Output;
}

//---------------------------------------------------------------------------------------------
// Encode all the relevent detals into a string
//---------------------------------------------------------------------------------------------
function SiEncodeDetails(Format)
{
   var Output = "";
   for (var i = 0; i < Format.length; i++)
   {
      var Data;
      switch (Format.charAt(i))
      {
      case 'r':
         Data = siReferrer;
         break;
      case 'p':
         Data = siRequest;      
         break;
      case 'd':
         Data = screen.availWidth+"x"+screen.availHeight+"x"+screen.colorDepth+"."+navigator.javaEnabled();
         if (navigator.plugins) Data += "."+navigator.plugins.length;
         break;
      case 'c':
         Data = siCookieValue;
         break;
      case 'u':
         Data = window.history.length+"."+(Math.random()*1000)+"."+(new Date()).getTime();
         break;
      case 't':
         Data = siPageID;
         break;
      case 'f':
         Data = siTracerPath;
         break;
      case 'q':
         Data = siTracerQuery;
         break;
      case 'g':
         Data = SiCollateTagData();
         break;
      case 'w':
         Data = siIsCookieNew;
         break;
      }
      //alert("Format="+Format.charAt(i)+", data: "+Data);
      Output += SiEncodeString(Data)+"*";
   }  
   return Output;
}

function SiCollateTagData()
{
	var TagData = "";
	
	TagData +=  "co=" + window.screen.colorDepth;
	TagData += "&sr=" + window.screen.width + 'x' + window.screen.height;
	today = new Date();
	if (null != today)
	{
		TagData += "&lt=" + today;
	}
	if (navigator.javaEnabled())
	{
		TagData += "&jv=1";
	}
	else
	{
		TagData += "&jv=0";
	}
	TagData += SiCollatePageRules();
	
	return TagData;
}	

function SiCollatePageRules()
{
	var PageData = "";

	if (window.siIsFrameset)
	{
		PageData += "&page:fset";
	}
	if (window.siIsMenu)
	{
		PageData += "&page:menu";
	}
	if (window.siIsExtraFrame)
	{
		PageData += "&page:x-frame";
	}
	if (window.siIsRedirection)
	{
		PageData += "&page:redir";
	}
	if (window.siIsPopup)
	{
		PageData += "&page:popup";
	}
	
	return PageData;
}

function SiIsMenu()
{
	window.siIsMenu = true;
}

function SiIsFrameset()
{
	window.siIsFrameset = true;
}

function SiIsExtraFrame()
{
	window.siIsExtraFrame = true;
}

function SiIsRedirection()
{
	window.siIsRedirection = true;
}

function SiIsPopup()
{
	window.siIsPopup = true;
}

function SiGetDomain()
{
  var DomainValue = null;
  var firstDot;
  var secondDot;
  var lastDot;
  var useHostname=document.location.hostname;
  if (useHostname != null)
  {
     var arIndex;
     for (arIndex = 0; (arIndex < siDomainList.length) && (DomainValue == null); arIndex++)
     {
        var tldIndex = useHostname.lastIndexOf(siDomainList[arIndex]);
        if (tldIndex > 0)
        {
           var nextDot = useHostname.lastIndexOf('.',tldIndex-1);
           if (nextDot >= 0)
           {
              DomainValue = useHostname.substring(nextDot);
           }
           else
           {
              DomainValue = "." + useHostname;
           }
        }
     }
  }
  return DomainValue;
}

function SiSetCookie(Name,Value,Path) 
{
  var Expiry=new Date;
  Expiry.setTime(Expiry.getTime()+siCookieTimeout);
  var Domain=SiGetDomain();
  var CookieDetails=Name+"="+Value+"; expires=\""+Expiry.toGMTString()+"\" "+((siCookiePath) ? "; path=" + siCookiePath : "")+((Domain) ? "; domain="+Domain : "");
  document.cookie=CookieDetails;
}

function SiGetCookie(Name,DataSource,DataEndChar) 
{
  var Prefix = Name+"=";
  var Value  = null;
  var Begin  = DataSource.indexOf(Prefix);
  if ((Begin != -1) && (Name.length > 0))
  {
    var End = DataSource.indexOf(DataEndChar,Begin);
    if (End == -1) End = DataSource.length;
    Value = DataSource.substring(Begin+Prefix.length,End);
  } 
  return Value;
}

function SiBuildCookie()
{
   var CookieValue=SiGetCookie(siCookieQPName,document.URL,"&");
   if (CookieValue != null) 
   {
      SiSetCookie(siCookieName,CookieValue);

      if (siCentralCookie)
      {
         // Extract original referrer
         var extractedURL = SiGetCookie(siCentralRefName,document.URL,"&");
         if (extractedURL != null)
         {
            siReferrer = unescape(extractedURL);
         }

         // Extract original request
         extractedURL = SiGetCookie(siCentralReqName,document.URL,"&");
         if (extractedURL != null)
         {
            siRequest = unescape(extractedURL);
         }
      }
   }
   else
   {
      CookieValue=SiGetCookie(siCookieName,document.cookie,";");
      if (CookieValue == null)
      {
         CookieValue=SiEncodeDetails("u");
         siIsCookieNew = 'Y';
         SiSetCookie(siCookieName,CookieValue);

         if (siCentralCookie)
         {
            // Check cookies can be set
            CookieValue = SiGetCookie(siCookieName,document.cookie,";");
            if (CookieValue != null)
            {
               var centralURL = siCentralURL;
               if (siCentralURL.indexOf("?") == -1)
               {
                  centralURL += "?";
               }
               else
               {
                  centralURL += "&";
               }
               centralURL += siCentralReqName+"="+escape(document.URL)+"&"+siCentralRefName+"="+escape(document.referrer);

               // Stop any possibility of tag firing
               siAutoTracer = false;

               // Redirect to central cookie server
               document.location = centralURL;
            }
         }
      }
   }
   CookieValue = SiGetCookie(siCookieName,document.cookie,";");
   return CookieValue;
}

function SiMigrateCookie(link)
{
   var CookieValue=SiGetCookie(siCookieName,document.cookie,";");
   if (CookieValue != null) link.href=link.href+((link.href.indexOf('?') > 0) ? "&" : "?")+siCookieQPName+"="+CookieValue;
   return true;
}

function SiMigrateCookieForm(form)
{
   var CookieValue=SiGetCookie(siCookieName,document.cookie,";");
   if (CookieValue != null) form.action=form.action+((form.action.indexOf('?') > 0) ? "&" : "?")+siCookieQPName+"="+CookieValue;
   return true;
}

function SiSendTracer(cookieForm,noCookieForm)
{
   var Tracker = new Image();
   Tracker.src = (siCookieValue == null) ? siTrackerUrl+"?f="+noCookieForm+"&d="+SiEncodeDetails(noCookieForm) : siTrackerUrl+"?f="+cookieForm+"&d="+SiEncodeDetails(cookieForm);
   siImageSet[siImageSet.length] = Tracker;
}

function SiTrackForm(filePath,form,list)
{
   siTracerPath = filePath;
   siTracerQuery = "";
   if (form.elements && (form.elements.length > 0))
   {
      var doamp=false;
      for (var i=0; i<form.elements.length; i++)
      {
         var el=form.elements[i];
         if (el.name)
         {
            var capture=(list == null);
            if (list != null)
            {
               for (var j=0; !capture && (j<list.length); j++)
               {
                  if (el.name == list[j]) capture = true;      
               }
            }
            if (capture && (el.type == "radio")) capture = el.checked;
            if (capture) 
            {
               if (doamp) siTracerQuery += "&";
               siTracerQuery += escape(el.name)+"="+escape(el.value);
               doamp=true;
            }
         }
      }
   } 
   SiSendTracer("fqcrt","fqdrt");
   return true;
}

function SiTrackTracer(filePath,queryString)
{
   siTracerPath = filePath;
   siTracerQuery = queryString;
   SiSendTracer("fqcrtg","fqdrtg");
}

function SiTrackPage()
{
   siCookieValue = SiBuildCookie();
   siPageID = "t"+(new Date()).getTime()+"h"+window.history.length;
   if (siAutoTracer) SiSendTracer("pcrtg","pdrtg");
}

// This function stops us overwriting any other onload events
function SiWindowOnload(f)
{
   var prev=window.onload;
   window.onload=function(){ if(prev)prev(); f(); }
}
  
// We prefer to send the tracer once the page has loaded - this lets us process any page type tags
// present.  However, the onload event may be overwritten by client code - in which case we need
// to fire now
if (siFireImmediately)
{
	SiTrackPage();
}
else
{
	SiWindowOnload(SiTrackPage);
}
