// Copyright Instadia A/S 2003-2004
// $Source: /data/development/cvs/js/gather/version_c2/clientstep.js,v $ $Revision: 1.68 $
//
// Global variables.
// Instadia_Use_Onload = <0|1>
// If set to 1, then no events are sent to the server before the onload handler has been activated.
// Default: false - Send events to data gathering without delay.
// It is imperative that if Instadia_Use_OnLoad is set to true the then script must be included 
// after all onload handlers are defined.


var ICSgs = "www.instadia.net/cgi-bin/";
var ICSga = "gather";
var ICSTopR = 1;
var ICSretries = 5;
var ICSimgArr;
var ICSimgArrSize;
var ICSonlh = null;

function ICSIsDone(image)
{
  // Old versions of netscape seems not to have the name property on image. 
  if (image.name == "undefined")
  {
    return image.complete;
  }
  else
  {
    //if (image.complete && (image.name != "Done")) alert("Complete, but not done");
    //if (!image.complete && (image.name == "Done")) alert("Not Complete, but done");	
    return ((image.complete && (image.name == "Done")) || (image.name == "Abort"));
  }
}

// Removes retrieved images from the queue, and saves the queue in the navigator object.
function ICSSave()
{
  var arr = ICSimgArr;
  // Make sure that ICSimgArr is defined.
  if (typeof arr == 'undefined')
  {
    //alert("ICSSaved called out of context");
    return;
  }

  ICSimgArr = new Array();
  ICSimgArrSize = -1;
  var str = "";
  for (var i = 0; i < arr.length; i++)
  {
    var img = arr[i];
    if (!ICSIsDone(img))
    {
      str += img.src + "|";
      ICSimgArr[++ICSimgArrSize] = img;
    }
  }
  if ((typeof navigator != 'undefined') && (typeof str != 'undefined'))
  {
    navigator.ICSimgStr = str; 
  }
}

function ICSRetry(image, retries)
{
  retries--;
  if (retries >= 0)
  {
    var func = new Function("ICSRetry(this," + retries + ")");
    image.onerror = func;
    image.onabort = func;
    image.src     = image.src;
  }
  else
  {
    image.onerror = null;
    image.onabort = null;
    image.onload  = null;
    image.name    = "Abort";
    ICSSave();
  }
}

function ICSDone(image)
{	
  image.onerror = null;
  image.onabort = null;
  image.onload  = null;
  image.name    = "Done";
  ICSSave();
}

function ICSInvoke(url)
{
  var protocol = document.location.protocol;
  // Only allow http or https protocols.
  if (protocol != "https:")
  {
    protocol = "http:";
  }
  var source = protocol + url.substring(url.indexOf(":")+1, url.length);
  // Only begin creating images for tracking if ICSstartTracking is set to true.
  if (ICSstartTracking == 1)
  {
    //alert("Invoke - Real: " + source);
    var image = new Image(1,1);
    var func =  new Function("ICSRetry(this," + ICSretries + ");");
    image.onerror = func;
    image.onabort = func;
    image.onload  = new Function("if (typeof ICSDone == 'function') {ICSDone(this);}");
    image.name    = "Progress";
    // Change to protocol to match the document.location.protocol
    image.src = source;
    ICSimgArr[++ICSimgArrSize] = image;
    ICSSave();
  } 
  else
  {
    //alert("Invoke - Store: " + source);
    // Test that the navigator object exists.
    ICScache = ICScache + source + "|";
  }
}

function ICS_SE()
{
  return true;
}

//function ICS_SE(desc,page,line,chr)  {
// alert(
//  'JavaScript error occurred! \n'
// +'Caught by Instadia error handler.\n'
// +'\nError description: \t'+desc
// +'\nPage address:      \t'+page
// +'\nLine number:       \t'+line
// )
// return true
//}


// The normal function that tries to get as much information as possible.
function Instadia_sendInfo(cId,ICSdesc,ICSsfname)
{
  var ICScId=(((cId?cId:"").length==5)?cId:"BADID");
  if (ICScId=="00000")
  {
    return
  }
  var ICSd=document;
  var ICSs=screen;
  var ICSn=navigator;
  var ICSN=(ICSn.appName=="Netscape"?1:0);
  var ICSt=new Date();
  var ICSbi="";
  var ICSm=((ICSd.lastModified)?Date.parse(ICSd.lastModified)/1000:0); ICSm=((ICSm>0)?ICSm:0);
  ICSbi+="4c"+ICScId+"&"+ICS_BID()+"&&";
  ICSbi+=ICSm+"&"+escape(ICSdesc?ICSdesc.slice(0,200):ICSd.title)+"&"+Math.round(ICSt.getTime()/1000)+"&";
  var ICSsw=ICSs.width; 
  var ICSsh=ICSs.height;
  var ICSsd=(ICSN?ICSs.pixelDepth:ICSs.colorDepth);
  var ICSdb=ICSd.body; 
  if(!ICSsd) 
  { 
    ICSsd=0;
  }
  ICSbi+=escape(ICS_REF())+"&"+ICSsw+"&"+ICSsh+"&"+ICSsd+"&";
  ICSbi+=(ICSs.availWidth?ICSs.availWidth:0)+"&"+(ICSs.availHeight?ICSs.availHeight:0)+"&";
  ICSbi+=(ICSN?ICSn.language:ICSn.userLanguage)+"&";
  ICSbi+=(ICSN?innerWidth:ICSdb?ICSdb.clientWidth:0)+"&"+(ICSN?innerHeight:ICSdb?ICSdb.clientHeight:0);
  ICSbi+="&"+(ICS_CT()+(ICSn.javaEnabled()?2:0)+1)+"&"+escape(ICS_PAGE(ICSsfname));
  ICSInvoke(document.location.protocol+"//"+ICSgs+ICSga+"?"+ICSbi);
}

// Use sessioncookies instead of persistence. Call once before the normal calls.
function Instadia_sessionCookies()
{
  ICSga="sgather";
}

function Instadia_sendInfoNoTop(cId,ICSdesc,ICSsfname)
{
  ICSTopR=0; 
  Instadia_sendInfo(cId,ICSdesc,ICSsfname);
}

function Instadia_sendInfoNoCache(cId,ICSdesc,ICSsfname)
{
  Instadia_sendInfo(cId,ICSdesc,ICSsfname);
}

function Instadia_sendInfoNoRefresh(cId,ICSdesc,ICSsfname)
{
  var ics_lp=ICS_RC("ICS_trackedPage");
  var ics_cp=document.location;
  if (ics_lp==ics_cp) return;
  document.cookie="ICS_trackedPage="+escape(ics_cp)+"; path=/";
  Instadia_sendInfo(cId,ICSdesc,ICSsfname);
}

// Simpler version of sendInfo, all params must be entered by hand. 
function Instadia_sendEvent(cId, ICSdesc,ICSsfname, useSecure)
{
  var ICScId=(((cId?cId:"").length==5)?cId:"BADID");
  if (ICScId=="00000")
  {
    return
  }
  var ICSt=new Date();var ICSbi="";
  ICSbi+="4c"+ICScId+"&"+ICS_BID()+"&&&";
  var ICSdsc=""+(ICSdesc?ICSdesc:"");
  ICSbi+=escape(ICSdsc.length?ICSdsc.slice(0,200):"")+"&"+Math.round(ICSt.getTime()/1000);
  ICSbi+="&&&&&&&&&&&";
  var ICSsfn=ICS_PAGE(ICSsfname);
  ICSbi+=escape(ICSsfn);
  ICSInvoke((useSecure?"https":"http")+"://"+ICSgs+ICSga+"?"+ICSbi);
}

// Set the Persistent ClientID cookie.
function setPCID(cid)
{
  if (cid.length>8)
    {
      var ICSe=new Date();
      ICSe.setTime(ICSe.getTime()+(3600*1000*24*365));
      var ICScdom=""+document.domain.replace(/^([^\.]*\.)?(.*\.)/,"$2");
      document.cookie="ICSPCID="+cid+";expires="+ICSe.toGMTString()+";path=/;domain="+ICScdom;
    }
  return;
}

// Set the Session ClientID cookie.
function setSCID(cid)
{
  if (cid.length>8)
    {
      var ICScdom=""+document.domain.replace(/^([^\.]*\.)?(.*\.)/,"$2");
      document.cookie="ICSSCID="+cid+";path=/;domain="+ICScdom;
    }
  return;
}

// Get the BrowserinstanceID
// The new BID uses 1 Party Persistant cookie and 1p session cookie as well as the nav.obj. 
function ICS_BID()
{
  var ICSpcid=ICS_RC("ICSPCID");
  var ICSscid=ICS_RC("ICSSCID");
  var ICScid=0;
  if (ICSpcid.length>8)
    {
      ICScid=ICSpcid;
    }
  else
    {
      if (ICSscid.length>8)
	{
	  ICScid=ICSscid;
	}
      else
	{
	  if (typeof navigator.ICSCID != "undefined")
	    { 
	      var ICSntid=(navigator.ICSCID).toString();
	      if (ICSntid.length>8)
		{
		  ICScid=navigator.ICSCID;
		}
	    }
	}
    }
  if (ICScid==0)
    {
      ICScid=(new Date()).getTime();
    }
  if (ICSpcid!=ICScid)
    {
      setPCID(""+ICScid);
    }
  if (ICSscid!=ICSpcid)
    {
      setSCID(""+ICScid);
    }
  if ((typeof navigator.ICSCID == "undefined") || (navigator.ICSCID!=ICScid))
    {
      navigator.ICSCID=ICScid;
    }
  return ICScid;
}

// Get the PageName. Maximum 250 chars. 
// Use the syntetic one if it exists but make sure there is also a servername.
function ICS_PAGE(synPage)
{
  var ICSpage="";
  if ( typeof document != 'undefined')
    {
      var ICSd=document;
      ICSpage=ICSd.location.toString();
      var server="";
      if ( typeof document.domain != 'undefined')
	{
	  server=ICSd.domain.toString();
	}
      if (ICSd.location.protocol=='file:') 
	{
	  server="local_file";
	  if ((typeof synPage == 'undefined') || (synPage.length==0))
	    {
	      synPage="/local_file";
	    }
	}
      server=ICSd.location.protocol.toString()+"//"+server;
      
      if ((typeof synPage != 'undefined') && (synPage.length>0))
	{
	  if ((synPage.indexOf("://")>1) && (synPage.indexOf("://")<10))
	    {
	      server="";
	    }
	  else if (synPage.indexOf('/')!=0)
	    {
	      synPage="/"+synPage;
	    }
	  ICSpage=server+synPage;
	}
    }
  return ICSpage.slice(0,250);
}

// Get the Referrer. Tries Cookie/Navigator/(top).document.referrer and trims it.
// RCT: '|' is used to indicate a used rct, '-' tells us that we didn't have one. 
function ICS_REF()
{
  var ICSr=ICS_RC("ICSref");
  var ICSrct=0;
  if (ICSr=="|")
    {
      ICSrct=1;
    }
  var ICScdom=""+document.domain.replace(/^([^\.]*\.)?(.*\.)/,"$2");
  if (ICSrct==0 && ICSr!="-")
    {
    
      ICSrct=1;
    }
  if ((ICSrct==0)&&(typeof(navigator) == 'object') && (typeof navigator.ICSREF != "undefined") &&
      (navigator.ICSREF!=null))
    {
      if (navigator.ICSREF!="|") 
	{
	  ICSr=navigator.ICSREF;
	} 
      ICSrct=1;
    }
  if ((ICSrct==1) )
    {
      if (ICSr=='|')
	{ 
	  ICSr=document.referrer;
	}
      document.cookie="ICSref=|;path=/;domain="+ICScdom;if (ICSr=="-")ICSr="";
      if (typeof navigator == 'object') 
	{ 
	  // If we have the cookie then reset navigator-referrer as well.
	  navigator.ICSREF="|";
	}
    }
  else
    { 
      var isOpera=false;
      var isOldNs=false;
      var ngualc=navigator.userAgent.toLowerCase();
      if (ngualc.indexOf("opera")!=-1) { isOpera=true; } 
      if ((ngualc.indexOf("netscape6")!=-1) || (ngualc.indexOf("mozilla/4.7")!=-1)) 
	{
	  isOldNs=true;
	}
      // Test if we are inside  a frameset. (doesnt works in some browsers)
      if (!isOpera && !isOldNs && (typeof parent != 'undefined') && (parent.frames.length>0))
	{ 
	  if (document.referrer!="" && (document.referrer.indexOf(document.domain)>=0))
	    {
	      document.cookie="ICSref=|;path=/;domain="+ICScdom;
	      navigator.ICSREF="|";
	      ICSr=(ICSTopR&&top.document.referrer)?top.document.referrer:document.referrer;
	    }
	  else
	    {
	      ICSr=document.referrer;
	      document.cookie="ICSref=|;path=/;domain="+ICScdom;
	      navigator.ICSREF="|";
	    }
	}
      else
	{
	  ICSr=document.referrer;
	}
    }
  
  var icsRre=/http[s]?[:]\/\/(.+)/;
  ICSr=ICSr.replace(icsRre, "http://$1");
  return ICSr?ICSr.slice(0,512):"";
}

// CookieTest Create a local (first party) cookie with short expire-time.
// Then try to read it to determine if cookies are supported.
function ICS_CT()
{
  var ICSe=new Date();
  ICSe.setTime(ICSe.getTime()+20000);
  document.cookie="Cookie=CookieTest"+((ICSe)?"; expires="+ICSe.toGMTString():"")+"; path=/";
  if(ICS_RC("Cookie")!="-")
    return 4;
  return 0;
}

// OLD, for compatibility only.
function Instadia_sendBigInfo(cId,ICSdesc,ICSsfname)
{
  Instadia_sendInfo(cId,ICSdesc,ICSsfname);
}

// OLD,  for compatibility only.
function Instadia_sendSmallInfo(cId,ICSdesc,ICSsfname)
{
  Instadia_sendInfo(cId,ICSdesc,ICSsfname);
}

// ReadCookie (cookieName)
// Returns '-' if cookie doesn't exist.
function ICS_RC (ICScn)
{
  var ICScs=document.cookie.split(';');var ICScp;var ICSrv="-"; var ICSi=0;
  for (ICSi=0;((ICSi<ICScs.length)&&(ICSrv=="-"));ICSi++)
  {
    ICScp=ICScs[ICSi].split('=');
    if(ICScp[0].substring(0,1)==' ')
    {
      ICScp[0]=ICScp[0].substring(1,ICScp[0].length);
    }
    if(ICScp[0]==ICScn)
    {
      ICSrv=unescape(ICScp[1]);
    }
  }
  if (ICSrv=="undefined")
    {
      ICSrv="";
    }
  return ICSrv;
}

var ICSfls="";
// FormEvent, Used to tracking FORM-interaction.
function Instadia_formEvent(cId,formf,ICSdesc,ICSfname,useSecure)
{
  var ff=formf; var f=ff.form?ff.form:ff;
  if (ICSfls!=ff.name)
  {
    Instadia_sendEvent(cId,(ICSdesc?ICSdesc:"Form Interaction"),
		       "form interaction/"+
		       ((typeof(f.ICSfident)!='undefined')?f.ICSfident.value:
			(f.name?f.name:(f.id==''?'noname':f.id)))+"/# " + 
		       (ICSfname?ICSfname:ff.name),useSecure);
  }
  ICSfls=formf.name;
}

// Start sending any pending events. 
// This may include pending events that originates from this page.
function ICSStart()
{
  ICSimgArr = new Array();
  ICSimgArrSize = -1;
  ICSstartTracking = 1;

  var cache = "";
  if ((typeof navigator.ICSimgStr != "undefined") && navigator.ICSimgStr && navigator.ICSimgStr != "")
  {
    cache = navigator.ICSimgStr;
    navigator.ICSimgStr = "";	
  }
  cache = cache + ICScache;
  ICScache = "";
  var urlArr = cache.split('|');
  for (var i = 0; i < urlArr.length; i++)
  {
    var url = urlArr[i];
    if (url && url != "")
    { 
      ICSInvoke(url);
    }
  }
}

function ICSOnLoad()
{
  var res = ICSonlh();
  ICSStart();
  return res;
}

// Main script starts.

// Initialize default values.
if (typeof ICSLoaded == "undefined" || ICSLoaded != 1) 
{
  var ICSLoaded = 0;
}

if (typeof ICSstartTracking == "undefined" || ICSstartTracking != 1)
{
  var ICSstartTracking = 0;
}

if (typeof Instadia_Use_Onload == "undefined" || Instadia_Use_Onload != 1)
{
  var Instadia_Use_Onload = 0;
}

if (typeof ICScache == "undefined")
{
  var ICScache = "";
}

// Insert eventhandlers, and load cache if nessessary.
if (ICSLoaded == 0) 
{
  if((typeof window.onerror == 'undefined') || (!window.onerror)) 
    { 
      window.onerror=ICS_SE;
    }
  
  if (Instadia_Use_Onload == 1)
  {
    // Enter a onload handler.
    if (typeof window.onload == "function")
    {
      ICSonlh = window.onload;
      window.onload = ICSOnLoad;
    } 
    else
    {
      window.onload = ICSStart;
    }
  }
  else
  {
    ICSStart();
  }
  // Mark the script active.  
  ICSLoaded = 1;
}
