function PropReports() {
	this.affiliatedKey = "prAffiliate";
}

PropReports.prototype.getRequestParameter = function(name) {
	var result = decodeURIComponent(window.location.search).match('[\\?&]' + name + '=([^&#]*)');
	return result ? result[1] : null;
};

PropReports.prototype.getCookie = function(name) {
	var result = document.cookie.match (name + '=(.*?)(;|$)');
	return result ? decodeURIComponent(result[1]) : null;
};

PropReports.prototype.setCookie = function(name, value, expireDays) {
	var today = new Date();
	var expiration = new Date(today.getTime() + (expireDays * 1000 * 60 * 60 * 24));
	document.cookie = name + "=" + encodeURIComponent(value) + "; expires=" + expiration.toGMTString();
};

PropReports.prototype.addLoadEvent = function (func) {
	var oldonload = window.onload;

	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

PropReports.prototype.getAffiliateCookie = function() {
	return this.getCookie(this.affiliatedKey);
};

PropReports.prototype.setAffiliateCookie = function() {
	var affiliateValue = this.getRequestParameter(this.affiliatedKey);
	if (affiliateValue) {
		this.setCookie(this.affiliatedKey, affiliateValue, 30);
	}
};

PropReports.prototype.__sendAffiliate = function(propReportsUrl) {
	var affiliate = this.getAffiliateCookie();
	if (!affiliate) {
		return;
	}
	var remoteScript = document.createElement('script');
	remoteScript.setAttribute('type', 'text/javascript');
	remoteScript.setAttribute('src', propReportsUrl + 'affiliate.php?' +
		this.affiliatedKey + "=" + encodeURIComponent(affiliate));

	var documentHead = document.getElementsByTagName('head')[0];
	// Gotcha: set attribute and src BEFORE appending, or Safari won't work
	documentHead.appendChild(remoteScript);
};

PropReports.prototype.sendAffiliate = function(propReportsUrl) {
	// Gotcha: send the affiliate after the page loads or the session might not be shared
	// with the application form
	this.addLoadEvent(function() {
		propReports.__sendAffiliate(propReportsUrl);
	});
};

var propReports = new PropReports();
propReports.setAffiliateCookie();
propReports.sendAffiliate('keystone.propreports.com');