/*
Parameters used in the request for /cgi-bin/aws.cgi? :

 referrerURL = the referrer url (DOM: document.referrer)
 _t = title (DOM: document.title)
 _hn = host name (DOM: document.location.hostname)
 _p = path (DOM: document.location.pathname + document.location)

 _sr = screen resolution (DOM: self.screen.width + self.screen.height or self.java)
 _sc = screen color depth (DOM: self.screen.colorDepth)
 _ul = language (DOM: navigator.language)
 _je = java enabled (DOM: navigator.javaEnabled())
 javaScriptVersion = javascript version
 _ce = cookieEnabled (DOM: navigator.cookieEnabled)
 _fe = flash version (DOM: navigator.plugins[], window.ActiveXObject)
 _tzo = timezone offset (e.g. 2 for EET)

 Cookies:
 __awssi = permanent cookie storing session information            
      value: <domain hash>.<random no>.<first ever session start time in seconds>.<session counter>
 __awsst = expires when on session timeout
           value: <domain hash>  
 __awsse = expires when the browser is closed
           value: <domain hash>  
__awsci = cookie storing campaign information
          value: <domain hash>.<first ever session start time in seconds>.<session counter>.
*/

var currentDate, domainHashCode, awsSessionInfoUpdated=0, sessionCount=0, referrerURL="-", javaScriptVersion="-";
var CGIPath="/cgi-bin/aws.cgi?";
var Domain="";  
var sessionTimeout="1800";     // set the inactive session timeout in seconds
var timeout="15768000";    // set timeout in seconds (6 month default)
var campaignName="aws_campaign";  // name
var campaignMedium="aws_medium";    // medium (cpc|cpm|link|email|organic)
var campaignSource="aws_source";    // source
var campaignTerm="aws_term";    // term/keyword
var campaignContent="aws_content";  // content
var campaignID="aws_id";    // id number
var AWSscriptVersion = 1;  // aws.js version

//-- Auto/Organic Sources and Keywords
var searchEngines=new Array();
var searchScript=new Array();
searchEngines[0]="google";  searchScript[0]="q";
searchEngines[1]="yahoo";  searchScript[1]="p";
searchEngines[2]="msn";    searchScript[2]="q";
searchEngines[3]="aol";    searchScript[3]="query";
searchEngines[4]="lycos";  searchScript[4]="query";
searchEngines[5]="ask";    searchScript[5]="q";
searchEngines[6]="altavista";  searchScript[6]="q";
searchEngines[7]="search";  searchScript[7]="q";
searchEngines[8]="netscape";  searchScript[8]="query";
searchEngines[9]="earthlink";  searchScript[9]="q";
searchEngines[10]="cnn";  searchScript[10]="query";
searchEngines[11]="looksmart";  searchScript[11]="key";
searchEngines[12]="about";  searchScript[12]="terms";
searchEngines[13]="excite";  searchScript[13]="qkw";
searchEngines[14]="mamma";  searchScript[14]="query";
searchEngines[15]="alltheweb";  searchScript[15]="q";
searchEngines[16]="gigablast";  searchScript[16]="q";
searchEngines[17]="voila";  searchScript[17]="kw";
searchEngines[18]="virgilio";  searchScript[18]="qs";
searchEngines[19]="teoma";  searchScript[19]="q";

function tracker() {
  if (document.location.protocol=="file:") return;
  
  currentDate=new Date();
  domainHashCode=GetDomainHash();
  
  var refParam = GetReferrerInfo();
  var trackingParam = UpdateSessionTrackVars()+UpdateCampaignTrackVar();
  // launch cgi-bin from JS
  var holder = new Image();
  holder.src = CGIPath + GetClientInfo(refParam) + trackingParam + "&v="+AWSscriptVersion;
  
  // reset the awssi tracking paramater updated flag
  awsSessionInfoUpdated=0;
}

tracker();

function GetReferrerInfo() {
  referrerURL=document.referrer;
  if (!referrerURL || referrerURL=="") { referrerURL="-"; }
  else {
    p=referrerURL.indexOf(document.domain);
    if ((p>=0) && (p<=8)) { 
      referrerURL="0"; // onsite referrers
    } 
    if (referrerURL.indexOf("[")==0 && referrerURL.lastIndexOf("]")==(referrerURL.length-1)) { 
      referrerURL="-"; 
    }
  }

  // unescape to make sure we are correctly handling the referrers that are already encoded
  // use encodeURIComponent instead of escape/unescape to create URI parameter values as escape() 
  // will get the wrong results for strings containing a plus, or any non-ASCII characters.
  return "&_ref="+encodeURIComponent(referrerURL);
}

// url info
// Params
// Computes values for the followign parameters in the aws.cgi request
// referrerURL = the referrer url (DOM: document.referrer)
// _t = title (DOM: document.title)
// _hn = host name (DOM: document.location.hostname)
// _p = path (DOM: document.location.pathname + document.location.search
// _tzo = timezone offset (e.g. 2 for EET) 
function GetClientInfo(refParam) {
 var p,s="",pg=document.location.pathname+document.location.search;
 
 // add host info
 if (document.location.hostname && document.location.hostname!="") s+="_hn="+escape(document.location.hostname);
 //add path info 
 s+="&_p="+pg;
 if (document.title && document.title!="") s+="&_t="+escape(document.title);
 
 // add referrer info
 s+=refParam;
 
 // add browser info
 s+=GetBrowserInfo();
 // add timezone offset info
 var tzo=(new Date().getTimezoneOffset()/60)*(-1); 
 s+="&_tzo="+tzo;
 return s;
}

// browser info
// Params
// _sr = screen resolution (DOM: self.screen.width, self.screen.height)
// _sc = screen color depth (DOM: self.screen.colorDepth)
// _ul = language (DOM: navigator.language)
// _je = java enabled (DOM: navigator.javaEnabled())
// javaScriptVersion = javascript version
// _ce = cookieEnabled (DOM: navigator.cookieEnabled)
// _fe = flash version (DOM: navigator.plugins[], window.ActiveXObject)
function GetBrowserInfo() {
 var sr="-",sc="-",ul="-",fl="-",je=1, ce="-",an="-",acn="-",av="-",fe="-";
 var n=navigator;
 
 if (self.screen) {
  sr=screen.width+"x"+screen.height;
  sc=screen.colorDepth+"-bit";
 } else if (self.java) {
  var j=java.awt.Toolkit.getDefaultToolkit();
  var s=j.getScreenSize();
  sr=s.width+"x"+s.height;
 }
 
 if (n.language) { ul=n.language.toLowerCase(); }
 else if (n.browserLanguage) { ul=n.browserLanguage.toLowerCase(); }

 je=n.javaEnabled()?1:0;
 ce = n.cookieEnabled; 
 fe = GetFlashVersion();
 GetJavaScriptVersion();
 return "&_sr="+sr+"&_sc="+sc+"&_ul="+ul+"&_je="+je+"&_ce="+ce+"&_fe="+fe+"&_jsv="+javaScriptVersion;
}

function GetJavaScriptVersion() {
  if (javaScriptVersion=="-") {
  for (var i=5;i>=0;i--) {
   var t="<script language='JavaScript1."+i+"'>javaScriptVersion='1."+i+"';</script>";
   document.write(t);
   if (javaScriptVersion!="-") break;
  }
 }
}

function GetFlashVersion() {
 var f="-",n=navigator;
 if (n.plugins && n.plugins.length) {
  for (var ii=0;ii<n.plugins.length;ii++) {
   if (n.plugins[ii].name.indexOf('Shockwave Flash')!=-1) {
    f=n.plugins[ii].description.split('Shockwave Flash ')[1];
    break;
   }
  }
 } else if (window.ActiveXObject) {
  for (var ii=10;ii>=2;ii--) {
   try {
    var fl=eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash."+ii+"');");
    if (fl) { f=ii + '.0'; break; }
   }
   catch(e) {}
  }
 }
 return f;
}

// update tracking valiables (i.e. cookies/URL paramaters)
function UpdateSessionTrackVars() {
  var awssi,awsst,awsse,v,expires="",s="";
  var urlAWSSISet=0;
  var nx=" expires=Sun, 18 Jan 2038 00:00:00 GMT;";
  var _random=Math.round(Math.random()*2147483647);
 
  _ust=Math.round(currentDate.getTime()/1000);// the current time in seconds
 
  if (sessionTimeout && sessionTimeout!="") {
    expires=new Date(currentDate.getTime()+(sessionTimeout*1000));
  }
  s=document.location.search;
  // if the URL contains the __awssi parameter then lookup the parameter values (i.e. __awssi, __awsst, __awsse) in the url
  if(s && s!="" && s.indexOf("__awssi=")>=0) {
    // get value for the __awssi, __awsst, __awsse params 
    awssi=GetParamValue(s,"__awssi=","&");
    awsst=GetParamValue(s,"__awsst=","&");
    awsse=GetParamValue(s,"__awsse=","&");
    
    if (awssi && awssi!="" && awssi!="-") {
      urlAWSSISet=1;
      
      if (!awsst || awsst=="" || awsst=="-" || 
          !awsse || awsse=="" || awsse=="-") { // either __awsst or __awsse are missing from the URL query
        awssi=UpdateSessionInfo(s,"&",_ust); // adjust the __awssi param value (i.e. replace 4th with 5th part, increment last part and set the before-last part to the current time in seconds)
        awsst=domainHashCode;
        awsse=domainHashCode;
        awsSessionInfoUpdated=1;        
      }
    
      // set expiration time to __awssi, __awsst, __awsse cookies
      SaveCookie('__awssi', awssi, -1, '/', '', '' );// set permanent cookie (i.e. expires=Sun, 18 Jan 2038 00:00:00 GMT) 
      SaveCookie('__awsst', awsst,  expires, '/', '', '' );// set session cokie (i.e. expires in on session timeout from current date/time) 
      SaveCookie('__awsse', awsse,  0, '/', '', '' ); // set cookie expiring when the browser is closed
    }    
  }
  
  if (urlAWSSISet==0) { // cookie lookup (all the __awssi, __awsst, __awsse paramaters are missing from the URL query string)
    awssi=GetParamValue(document.cookie,"__awssi="+domainHashCode,";");
    awsst=GetParamValue(document.cookie,"__awsst="+domainHashCode,";");
    awsse=GetParamValue(document.cookie,"__awsse="+domainHashCode,";");
  
    if (awssi && awssi!="" && awssi!="-") { // if the __awssi cookie is set
      if (!awsst || awsst=="" || awsst=="-" ||
          !awsse || awsse=="" || awsse=="-") { // either __awsst or __awsse cookies are missing
         awssi=UpdateSessionInfo(document.cookie,";",_ust); // adjust the __awssi cookie value (i.e. replace 4th with 5th part, increment last part and set the before-last part to the current time in seconds)                  
        awsst=domainHashCode;
        awsse=domainHashCode; 
        awsSessionInfoUpdated=1;
      }            
    } else { // otherwise the __awssi cookie is set  
      awssi=domainHashCode+"."+_random+"."+_ust+".1"; // initialze it
      awsst=domainHashCode;
      awsse=domainHashCode;
      awsSessionInfoUpdated=1;
    }   
    
    SaveCookie('__awssi',    awssi, -1, '/', Domain, '' ); 
    SaveCookie('__awsst', awsst,  expires, '/', Domain, '' ); 
    SaveCookie('__awsse', awsse,  0, '/', Domain, '' );     
  }
  
  // get cokies values
  return "&__awssi="+awssi+"&__awsst="+awsst+"&__awsse="+awsse;
}

function SaveCookie( name, value, expires, path, domain, secure ) 
{  
  var expires_date = ( (expires==-1) ? "Sun, 18 Jan 2038 00:00:00 GMT" : ( (expires>0) ? expires.toGMTString() : '' ) );

  document.cookie = name + "=" + value +
                   ( ( expires!=0 ) ? ";expires=" + expires_date : "" ) + 
                   ( ( path ) ? ";path=" + path : "" ) + 
                   ( ( domain && domain.indexOf('.') == 0 ) ? ";domain=" + domain : "" ) +
                   ( ( secure ) ? ";secure" : "" );
}


// Parses the value of the given key in the given string
// str = string
// key = key
// separator
function GetParamValue(str,key,separator) {
 if (!str || str=="" || !key || key=="" || !separator || separator=="") return "-";
 var i,i2,i3,c="-";
 i=str.indexOf(key);
 i3=key.indexOf("=")+1;
 if (i > -1) {
  i2=str.indexOf(separator,i); if (i2 < 0) { i2=str.length; }
  c=str.substring((i+i3),i2);
 }
 return c;
}

// Returns the new value for the __awssi parameter
// c = the string to search in (e.g. url query string, cookie string)  
// s = parameter key value pairs separator (e.g. '&' for the URL search string, ';' for the cookie string)
// t = time value in seconds
function UpdateSessionInfo(c,s,t) {
 if (!c || c=="" || !s || s=="" || !t || t=="") return "-";

 var a=GetParamValue(c,"__awssi="+domainHashCode,s); // looks up the string following the __awssi=<domain hash> until the separator is encountered
 var lt=0,i=0;

 // if the last occurence of the '.' is >6 (i.e. there is at least 1 char in each of the 4 '.' groups)
 if ((i=a.lastIndexOf("."))>5) {
  sessionCount=a.substring(i+1,a.length); // get the numeric substring after the last '.' char occurence
  sessionCount=(sessionCount*1)+1; // increment 1 to that number
  a=a.substring(0,i); // get the substring from the beginning up to the char preceeding the last '.' char occurence
  
  a+="."+sessionCount;
 }
 return a;
}

function GetDomainHash() {
 // assign domain 
 var d=document.domain;
 if (d.substring(0,4)=="www.") {
  d=d.substring(4,d.length);
 }
 Domain=d;
 return HashCode(Domain);
}

function HashCode(d) {
 if (!d || d=="") return 1;
 var h=0,g=0;
 for (var i=d.length-1;i>=0;i--) {
  var c=parseInt(d.charCodeAt(i));
  h=((h << 6) & 0xfffffff) + c + (c << 14);
  if ((g=h & 0xfe00000)!=0) h=(h ^ (g >> 21));
 }
 return h;
}

// update the campaign tracking valiable (i.e. cookies/URL paramaters)
function UpdateCampaignTrackVar() {
 if (!timeout || timeout=="") { timeout="15768000"; }
 
 var c="",t="-",t2="-",o=0,cs=0,cn=0;i=0;
 var s=document.location.search;
 var ci=GetParamValue(s,"__awsci=","&"), ciParamVal="";
 var x=new Date(currentDate.getTime()+(timeout*1000)); 
 // if the __awsci parameter is present in the URL then set the corresponding cookie
 if (ci!="-") { 
   SaveCookie( '__awsci', unescape(ci), x, '/', Domain, '' ) 
   return "&__awsci="+ci; 
 }
 // Try to read the __awsci cookie (if set for this domain)
 ci=document.cookie.indexOf("__awsci="+domainHashCode);

 if (ci>-1) { 
   ci=GetParamValue(document.cookie,"__awsci="+domainHashCode,";"); 
 }
 else { 
   ci="-"; 
 }
 t=GetParamValue(s,campaignID+"=","&");
 t2=GetParamValue(s,campaignSource+"=","&");
 // try to get campaign info from the URL
 if ((t!="-" && t!="") || (t2!="-" && t2!="")) {
  if (t!="-" && t!="") { 
    c+="awscid="+encodeSpaces(t); 
    if (t2!="-" && t2!="") 
      c+="|awscsr="+encodeSpaces(t2);
  } else { 
    if (t2!="-" && t2!="") 
      c+="awscsr="+encodeSpaces(t2); 
  }
  t=GetParamValue(s,campaignName+"=","&");
  if (t!="-" && t!="") 
    c+="|awsccn="+encodeSpaces(t);
  else 
    c+="|awsccn=(not+set)";
  t=GetParamValue(s,campaignMedium+"=","&");
  if (t!="-" && t!="") 
    c+="|awscmd="+encodeSpaces(t);
  else  
    c+="|awscmd=(not+set)";
  t=GetParamValue(s,campaignTerm+"=","&");
  if (t!="-" && t!="") 
    c+="|awsctr="+encodeSpaces(t);
  else {
    t=GetOrganicSEInfo(1); 
    if (t!="-" && t!="") 
      c+="|awsctr="+encodeSpaces(t); 
  }
  t=GetParamValue(s,campaignContent+"=","&");
  if (t!="-" && t!="") 
    c+="|awscct="+encodeSpaces(t);  
 }
 // try to get the organic SE referral info
 if (c=="-" || c=="") { 
   c=GetOrganicSEInfo();   
 }
 // try to get the referrer info
 if (c=="-" || c=="") { 
   if (awsSessionInfoUpdated==1) { 
     c=GetReferrerURL(); 
   }
 }
 // direct access
 if (c=="-" || c=="") {
  if (awsSessionInfoUpdated==1) { 
    c="awsccn=(direct)|awscsr=(direct)|awscmd=(none)"; 
  }
  if (c=="-" || c=="")  {
    return "";
  }
 }
 if (ci!="-") {
  i=ci.indexOf(".");
  if (i>-1) 
    i=ci.indexOf(".",i+1);
  if (i>-1) 
    i=ci.indexOf(".",i+1);
  if (i>-1) 
    i=ci.indexOf(".",i+1);
  t=ci.substring(i+1,ci.length);
  if (t.toLowerCase()==c.toLowerCase()) 
    cs=1;
  t=ci.substring(0,i);
  if ((i=t.lastIndexOf(".")) > -1) {
   t=t.substring(i+1,t.length);
   cn=(t*1);
  }
 }
 if (cs==0 || awsSessionInfoUpdated==1) {
  t=GetParamValue(document.cookie,"__awssi="+domainHashCode,";");
  if ((i=t.lastIndexOf("."))>9) {
   sessionCount=t.substring(i+1,t.length);
   sessionCount=(sessionCount*1);
  }
  cn++;
  if (sessionCount==0) 
    sessionCount=1;
  // set the value for the __awsci cookie storing campaing information
  ciParamVal=domainHashCode+"."+_ust+"."+sessionCount+"."+cn+"."+c;

  SaveCookie( '__awsci', ciParamVal, x, '/', Domain, '' )   
  return "&__awsci=" + ciParamVal;
 }
 
 return "";
}
function GetReferrerURL() {
 if (referrerURL=="0" || referrerURL=="" || referrerURL=="-") {
   return "";
 }
 var i=0,h,k,n;
 if ((i=referrerURL.indexOf("://"))<0) {
   return "";
 }
 h=referrerURL.substring(i+3, referrerURL.length);
 if (h.indexOf("/") > -1) {
  k=h.substring(h.indexOf("/"),h.length);
  if (k.indexOf("?") > -1)
    k=k.substring(0,k.indexOf("?"));
  else if (k.indexOf("&") > -1)
    k=k.substring(0,k.indexOf("&"));
  h=h.substring(0,h.indexOf("/"));
 }
 h=h.toLowerCase();
 n=h;
 if ((i=n.indexOf(":")) > -1) 
   n=n.substring(0,i);
 if (h.indexOf("www.")==0) 
   h=h.substring(4,h.length);
  return "awsccn=(referral)|awscsr="+encodeSpaces(h)+"|"+"awscct="+encodeSpaces(k)+"|awscmd=referral";
}
function GetOrganicSEInfo(t) {
 if (referrerURL=="0" || referrerURL=="" || referrerURL=="-") return "";
 var i=0,h,k;
 if ((i=referrerURL.indexOf("://")) < 0) return "";
 h=referrerURL.substring(i+3, referrerURL.length);
 if (h.indexOf("/") > -1) {
  h=h.substring(0,h.indexOf("/"));
 }
 for (var ii=0;ii<searchEngines.length;ii++) {
  if (h.indexOf(searchEngines[ii]) > -1) {
   if ((i=referrerURL.indexOf("?"+searchScript[ii]+"=")) > -1 || (i=referrerURL.indexOf("&"+searchScript[ii]+"=")) > -1) {
    k=referrerURL.substring(i+searchScript[ii].length+2, referrerURL.length);
    if ((i=k.indexOf("&")) > -1) k=k.substring(0,i);
    if (t) 
      return encodeSpaces(k);
    else 
      return "awsccn=(organic)|awscsr="+encodeSpaces(searchEngines[ii])+"|"+"awsctr="+encodeSpaces(k)+"|awscmd=organic";
   }
  }
 }
 return "";
}

function encodeSpaces(s) {
  var n="";
  if (!s || s=="") return "";
  for (var i=0;i<s.length;i++) {if (s.charAt(i)==" ") n+="+"; else n+=s.charAt(i);}
  return n;
}