// days after which the cookie will expire
var referrerCookieExpirationDays = 5000;

// referring and landing page URLs
var REF = document.referrer;
var LAND = location.href;

//CID
var l = "ABCDEFGHJKLMNPQRSTUVWXYZ";
var n = "23456789";
var CID = n.charAt(Math.floor(Math.random() * n.length));
CID += l.charAt(Math.floor(Math.random() * l.length));
CID += l.charAt(Math.floor(Math.random() * l.length));
CID += n.charAt(Math.floor(Math.random() * n.length));
CID += l.charAt(Math.floor(Math.random() * l.length));
CID += l.charAt(Math.floor(Math.random() * l.length));

// identify domain
var domain = location.hostname;
if(domain.indexOf(".") < domain.lastIndexOf(".")) {
	domain = domain.substr(domain.indexOf(".") + 1);
}

function setReferrerCookie () {
	var nowDate = new Date();

	var expiresDate = new Date();
	expiresDate.setTime(expiresDate.getTime() + (referrerCookieExpirationDays*24*60*60*1000));

	var cookieValue =
		"REF=" + escape(REF) +
		":REFD=" + escape(nowDate.toGMTString()) +
		":CID=" + escape(CID) +
		":SRC=" + escape(LAND) +
		"; expires=" + expiresDate.toGMTString() +
		"; path=/" + "; domain=" + domain; 

	document.cookie = cookieValue;
}

function isReferrerCookieSet () {
	return (document.cookie.indexOf("REF=") == -1);
}

function isValidReferrerDomain () {
	// invalid domains regular expression
	var invalidDomainsRE = new RegExp("^https?:\\/\\/(www\\.)?" + domain + "", "gi");
	return !invalidDomainsRE.test(REF);
}

function isValidPPCSrc (src) {
	// valid PPC source regular expression
	var validPPCRE = new RegExp("\\?(as|aw|as&.*|aw&.*|az|biz|be|ci|dt|ls|msn|my|nt|ov|pg|pr|ps|pt|pw|sd|sm|sp|y|source=CashbackShopping)(&zmam=2134960&zmas=1&zmac=[0-9]+&zmap=.*?)?$");
	return validPPCRE.test(src);
}

function isValidAffiliateSrc (src) {
	// valid affiliate source regular expression
	var validAffiliateRE = new RegExp("\\?aff-(isv)-(.+)$", "i");
	return validAffiliateRE.test(src);
}

if (isReferrerCookieSet()) {
	setReferrerCookie ();
} else {
	var cookieREF = unescape(document.cookie.replace(/.*REF=([^:]*).*/g, "$1"));
	var cookieLAND = unescape(document.cookie.replace(/.*SRC=([^;]*).*/g, "$1"));

	if (isValidReferrerDomain() && !isValidAffiliateSrc(cookieLAND) && (isValidPPCSrc(LAND) || isValidAffiliateSrc(LAND) || ((cookieREF == "") && !isValidAffiliateSrc(cookieLAND) && !isValidPPCSrc(cookieLAND)))) {
		setReferrerCookie ();
	}
}

if(document.cookie.indexOf("CID=") == -1) {
	var REF = unescape(document.cookie.replace(/.*REF=([^:]*).*/g, "$1"));
	var LAND = unescape(document.cookie.replace(/.*SRC=([^;]*).*/g, "$1"));
	setReferrerCookie ();
}

var CID = unescape(document.cookie.replace(/.*CID=([^:]*).*/g, "$1"));
var REMOTE_HOST = "(none)";
