// Referrer cookies
// cookie expiration
var exp = new Date(); 
exp.setTime(exp.getTime() + (30*365*24*60*60*1000));
// last visit date
var date=new Date();
var d  = date.getDate();
var day = (d < 10) ? '0' + d : d;
var m = date.getMonth() + 1;
var month = (m < 10) ? '0' + m : m;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;

var referrer;

// define list of valid referrer urls
var validreferrers=Array(3);
validreferrers[0]="www.google.com";
validreferrers[1]="www.bing.com";
validreferrers[2]="search.yahoo.com";

// define list of keyword vars, used by referrer search engines
var keyword_varnames = Array(3);
keyword_varnames[0]="q";
keyword_varnames[1]="q";
keyword_varnames[2]="p";

// Paid Ad parameter in link url
var loc = new URL(document.location.href);
var paid="NOTPAID";
if(loc.getArgumentValue("source")){
	paid=loc.getArgumentValue("source");
}
// ref data seperator
var sep="~";

// four cookies  are used 
// hits = visit date and total entrance hit count(hits|date)
// lastvisit = last visit date
// refFirst = first visit referrer data (date,domain,paid,keywords)
// refSubsequent = subsequent visit referrers(date,domain,paid,keywords;...)

// search referrer array for referrer domain match
var ref_match=-1;
if(document.referrer){
	referrer=new URL(document.referrer);
	for(var i=0;i<validreferrers.length;i++){
		if(validreferrers[i]==referrer.getHost()){
			ref_match=i;
			break;
		}
	}
}else{
	referrer=null;
}

// if domain matched search engine or not current domain, set hit count and referrer cookies
if(ref_match>=0||!document.referrer||referrer.getHost()!=loc.getHost()){
	// entrance hit counter
	var hits = GetCookie("hits");
	if(!hits){
		hits=0;
	}
	hits++;
	SetCookie("hits",hits,exp,"/");
	SetCookie("lastvisit",month+"/"+day+"/"+year,exp,"/");
	// grab keywords from referrer
	var keywords="none";
	if(ref_match>=0){
		keywords = referrer.getArgumentValue(keyword_varnames[i]);
	}
	if(document.referrer){
		refdomain=referrer.getHost();
	}else{
		// direct link cookies
		refdomain="DIRECT_LINK";
	}
	if(GetCookie("refFirst")==null){
		// first referrer
		SetCookie("refFirst",month+"/"+day+"/"+year+sep+refdomain+sep+paid+sep+keywords,exp,"/");
	}else{
		// subsequent referrers
		var refSubsequent = GetCookie("refSubs");
		if(!refSubsequent) {
			SetCookie("refSubs",month+"/"+day+"/"+year+sep+refdomain+sep+paid+sep+keywords,exp,"/");
		}else{
			SetCookie("refSubs",month+"/"+day+"/"+year+sep+refdomain+sep+paid+sep+keywords+sep+sep+refSubsequent,exp,"/");
		}
	}
}


// URL parser
function URL(url){
	if(url.length==0) eval('throw "Invalid URL ['+url+'];');
	this.url=url;
	this.port=-1;
	this.query=(this.url.indexOf('?')>=0)?this.url.substring(this.url.indexOf('?')+1):'';
	if(this.query.indexOf('#')>=0) this.query=this.query.substring(0,this.query.indexOf('#'));
	this.protocol='';
	this.host='';
	var protocolSepIndex=this.url.indexOf('://');
	if(protocolSepIndex>=0){
		this.protocol=this.url.substring(0,protocolSepIndex).toLowerCase();
		this.host=this.url.substring(protocolSepIndex+3);
		if(this.host.indexOf('/')>=0) this.host=this.host.substring(0,this.host.indexOf('/'));
		var atIndex=this.host.indexOf('@');
		if(atIndex>=0){
			var credentials=this.host.substring(0,atIndex);
			var colonIndex=credentials.indexOf(':');
			if(colonIndex>=0){
				this.username=credentials.substring(0,colonIndex);
				this.password=credentials.substring(colonIndex);
			}else{
				this.username=credentials;
			}
			this.host=this.host.substring(atIndex+1);
		}
		var portColonIndex=this.host.indexOf(':');
		if(portColonIndex>=0){
			this.port=this.host.substring(portColonIndex);
			this.host=this.host.substring(0,portColonIndex);
		}
		this.file=this.url.substring(protocolSepIndex+3);
		this.file=this.file.substring(this.file.indexOf('/'));
	}else{
		this.file=this.url;
	}
	if(this.file.indexOf('?')>=0) this.file=this.file.substring(0, this.file.indexOf('?'));
	var refSepIndex=url.indexOf('#');
	if(refSepIndex>=0){
		this.file=this.file.substring(0,refSepIndex);
		this.reference=this.url.substring(this.url.indexOf('#'));
	}else{
		this.reference='';
	}
	this.path=this.file;
	if(this.query.length>0) this.file+='?'+this.query;
	if(this.reference.length>0) this.file+='#'+this.reference;

	this.getPort=getPort;
	this.getQuery=getQuery;
	this.getProtocol=getProtocol;
	this.getHost=getHost;
	this.getUserName=getUserName;
	this.getPassword=getPassword;
	this.getFile=getFile;
	this.getReference=getReference;
	this.getPath=getPath;
	this.getArgumentValue=getArgumentValue;
	this.getArgumentValues=getArgumentValues;
	this.toString=toString;

	/* Returns the port part of this URL, i.e. '8080' in the url 'http://server:8080/' */
	function getPort(){
		return this.port;
	}

	/* Returns the query part of this URL, i.e. 'Open' in the url 'http://server/?Open' */
	function getQuery(){
		return this.query;
	}

	/* Returns the protocol of this URL, i.e. 'http' in the url 'http://server/' */
	function getProtocol(){
		return this.protocol;
	}

	/* Returns the host name of this URL, i.e. 'server.com' in the url 'http://server.com/' */
	function getHost(){
		return this.host;
	}

	/* Returns the user name part of this URL, i.e. 'joe' in the url 'http://joe@server.com/' */
	function getUserName(){
		return this.username;
	}

	/* Returns the password part of this url, i.e. 'secret' in the url 'http://joe:secret@server.com/' */
	function getPassword(){
		return this.password;
	}

	/* Returns the file part of this url, i.e. everything after the host name. */
	function getFile(){
		return this.file;
	}

	/* Returns the reference of this url, i.e. 'bookmark' in the url 'http://server/file.html#bookmark' */
	function getReference(){
		return this.reference;
	}

	/* Returns the file path of this url, i.e. '/dir/file.html' in the url 'http://server/dir/file.html' */
	function getPath(){
		return this.path;
	}

	/* Returns the FIRST matching value to the specified key in the query.
	   If the url has a non-value argument, like 'Open' in '?Open&bla=12', this method
	   returns the same as the key: 'Open'...
	   The url must be correctly encoded, ampersands must encoded as &amp;
	   I.e. returns 'value' if the key is 'key' in the url 'http://server/?Open&amp;key=value' */
	function getArgumentValue(key){
		var a=this.getArgumentValues();
		if(a.length<1) return '';
		for(i=0;i<a.length;i++){
			if(a[i][0]==key) return a[i][1];
		}
		return '';
	}

	/* Returns all key / value pairs in the query as a two dimensional array */
	function getArgumentValues(){
		var a=new Array();
		var b=this.query.split('&');
		var c='';
		if(b.length<1) return a;
		for(i=0;i<b.length;i++){
			c=b[i].split('=');
			a[i]=new Array(c[0],((c.length==1)?c[0]:c[1]));
		}
		return a;
	}

	/* Returns a String representation of this url */
	function toString(){
		return this.url;
	}
}
// cookie handlers
function GetCookie (name) {  
var arg = name + "=";  
var alen = arg.length;  
var clen = document.cookie.length;  
var i = 0;  
while (i < clen) {
	var j = i + alen;    
	if (document.cookie.substring(i, j) == arg)      
		return getCookieVal (j);    
	i = document.cookie.indexOf(" ", i) + 1;    
	if (i == 0) break;   
}  
return null;
} 

function getCookieVal(offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

function SetCookie (name, value) {  
var argv = SetCookie.arguments;  
var argc = SetCookie.arguments.length;  
var expires = (argc > 2) ? argv[2] : null;  
var path = (argc > 3) ? argv[3] : null;  
var domain = (argc > 4) ? argv[4] : null;  
var secure = (argc > 5) ? argv[5] : false;  
document.cookie = name + "=" + escape (value) + 
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + 
((path == null) ? "" : ("; path=" + path)) +  
((domain == null) ? "" : ("; domain=" + domain)) +    
((secure == true) ? "; secure" : "");
}

function DeleteCookie (name) {  
var exp = new Date();  
exp.setTime (exp.getTime() - 1);   
var cval = GetCookie (name);  
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}


