// First, Get the domain name of where the page is.
var cDomain = self.location.hostname;
if(cDomain.indexOf(".") < cDomain.lastIndexOf(".")){
  var domainOffset = cDomain.indexOf(".")+1
  cDomain = cDomain.substr(domainOffset);
}

// Next check for the need to write the cookie
// Check that the referrer page is NOT part of the same domain
// and that there IS a referrer to write to cookie
// and that the cookie has NOT already been written before
if(document.referrer.indexOf(cDomain)==-1 && document.referrer!="" && document.cookie.indexOf("referrer=")==-1){
  var expDays = 180; // set the number of days to expiry of the cookie
  var exp = new Date(); 
  exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
  var refdate = new Date();
  document.cookie = "referrer=" + escape(document.referrer + "&&&" + refdate.toGMTString().replace(/ /g,"_")) + "&&&" + "NA" + "&&&" + "NA" + "; expires=" + exp.toGMTString() + "; path=/" + "; domain=" + cDomain;
// the cookie has now been written.
}

// The next part allows the cookie to be read back after writing
// first, we find  if there is the referer cookie
var allCookies = document.cookie;
var cPos = allCookies.indexOf("referrer=");
// if the cookie exists, we read back its values
// and break the useful data from the rest
if(cPos != -1){
var cdstart = cPos + 9;
var cdend = allCookies.indexOf(";", cdstart);
if(cdend == -1) cdend = allCookies.length;
var cookieContent = allCookies.substring(cdstart,cdend);
cookieContent = unescape(cookieContent);
var cData = cookieContent.split("&&&");
var cRefer = cData[0];
var cDateRef = cData[1];
var cSourceRef = cData[2];
var cKeywordRef = cData[3];
}
else{
var cRefer = "No cookie";
var cDateRef = "No cookie";
var cSourceRef = "No cookie";
var cKeywordRef = "No cookie";
}
// The variable cRefer is the referring URL
// The variable cDateRef is the date of that referral
// The variable cSourceRef is the source of that referral
// The variable cKeywordRef is the keyword of that referral
