function UserReferrerGetter(cookieValue, queryString, cookiesToSet, httpReferrer, documentLocation, aliases, isLoggedIn, dbReferrer) {
    this.cookieValue = cookieValue;
    this.queryString = queryString;
    this.cookiesToSet = cookiesToSet;
    this.httpReferrer = httpReferrer;
    this.documentLocation = documentLocation;
    this.aliases = aliases;
    this.isLoggedIn = isLoggedIn;
    this.dbReferrer = dbReferrer;
    this.domainToReferrerMapping = {
	"coaches": "coachesnew",
	"marieclaire": "marieclaire"};
}

UserReferrerGetter.prototype.execute = function() {
    if (isEmpty(this.isLoggedIn)) {
	if (isEmpty(this.queryString)) {
	    if (isEmpty(this.cookieValue)) {
		if (!this.referrerMatchesSiteAliases(this.httpReferrer)) {
		    if (this.getReferrerFromUrl() != null) {
			return this.setAndReturnReferrer(this.getReferrerFromUrl());
		    } else if( this.getReferrerForDomain() != null ) {
			return this.setAndReturnReferrer(this.getReferrerForDomain());
		    }
		}
	    } 
	    else {
		return this.cookieValue;
	    }
	}
	else {
	    this.cookiesToSet.push(this.queryString);
	    return this.queryString;
	} 
	return null;
	
    }
    else {
	return this.dbReferrer;
    }
}    

UserReferrerGetter.prototype.getReferrerForDomain = function() {
    return this.domainToReferrerMapping[this.getDomainsListFromUrl(this.documentLocation)[0]];
}

UserReferrerGetter.prototype.setAndReturnReferrer = function(referrer) {
    this.cookiesToSet.push(referrer);
    return referrer;
}

UserReferrerGetter.prototype.getReferrerFromUrl = function() {
    var list = this.getDomainsListFromUrl(this.httpReferrer);
    return list[list.length - 2];
}

UserReferrerGetter.prototype.getDomainsListFromUrl = function(url) {
    var matches = url.match(/http:\/\/(.*?)\//);
    
    if (matches != null) {
	return matches[1].split(".");
    } else {
	return [];
    }
}

UserReferrerGetter.prototype.referrerMatchesSiteAliases = function(referrer) {
    if (referrer == null) return false;
    for(var i=0;i<this.aliases.length;i++)
        if (referrer.toLowerCase().indexOf(this.aliases[i].toLowerCase())!=-1) return true;

    return false;
}


