function detectReferrerGeneral(){ 
  var theref;
  theref = document.referrer;
  if (document.referrer.length == 0)
  { theref = 'none';
  }
  return theref;
}

function detectParameter(param1){ 
  var urlParamStr=location.href.split("?");
  var urlParamItems, urlParamID;
  var i;

  if (urlParamStr[1]){
    urlParamItems=urlParamStr[1].split("&");
    i=0;
    while (urlParamItems[i]) {
      urlParamID=urlParamItems[i].split("=");
      if((urlParamID[0]==param1) && (urlParamID[1])) {
        return urlParamID[1];
      }
      i++;
    }
  }
  return 'none';
}

function WriteCookie(name,value,domain,path,expires,secure){ 
	var CookieVal, CookError;
	CookieVal=CookError="";
      //Set cookie to expire in 31 days
      expires = new Date();
	  expires.setTime(expires.getTime() + (1000*60*60*24*31));
	if (name){
		CookieVal=CookieVal+escape(name)+"=";
	}
	if (value){
		CookieVal=CookieVal+escape(value);
	}
	if (domain){
		CookieVal=CookieVal+"; domain="+domain;
	}
	if (path){
		CookieVal=CookieVal+"; path="+path;
	}
	if (expires){
		CookieVal=CookieVal+"; expires="+expires.toGMTString();
	}
	if (secure){
		CookieVal=CookieVal+"; secure="+secure;
	}
	else{
		CookError=CookError+"Write failure";
	}
	document.cookie=CookieVal;  // sets the cookie
}

function captureReferrer(){
	if (ReadCookie('referrer_general').length == 0)
	{ 
		WriteCookie('referrer_general',detectReferrerGeneral(),window.location.host,'/', null ,0);
	    WriteCookie('referrer_planned',detectParameter('referrer'),window.location.host,'/', null ,0);
	    WriteCookie('referrer_keyword',detectParameter('keyword'),window.location.host,'/', null ,0);
	}
}

function ReadCookie(aName){
  var allCookie, cookieVal, length, start, end;
  cookieVal="";
  name=aName+"=";
  allCookie=document.cookie;
  length=allCookie.length;
  if (length>0){
    start=allCookie.indexOf(name, 0);
    if (start!=-1){
      start+=name.length;
      end=allCookie.indexOf(";",start);
      if (end==-1) {
        end=length;
      }
      cookieVal=unescape(allCookie.substring(start,end));
    }
  }
  len=cookieVal.length;
  return(cookieVal);
}

function ClearCookie(cookie_name){
  var the_date = new Date("December 31, 2000"); 
  var the_cookie_date = the_date.toGMTString(); 
  var the_cookie = cookie_name + "='';path=/;domain=" + window.location.host + ";expires=" + the_cookie_date; 
  document.cookie = the_cookie; 
}

function ClearCookies(){
  ClearCookie('referrer_general');
  ClearCookie('referrer_planned');
  ClearCookie('referrer_keyword');
}

captureReferrer();
