/* 
Creates a cookie holding the value of the document's url and query 
string if a tracking code is found.
Example of link with tracking code attached: 
http://www.artschools.com/?WT.mc_n=edu_nblue_art_250x250&subaffid=45454&orderid=12451&adid=81
*/
var raw_domain = document.domain;
var domain_pattern = /^(\w*\-*\w*\.)*(\w+\.\w{3,4})$/g;
var domain_array = domain_pattern.exec(raw_domain);
var domain = domain_array[2];
var track_code = /patid/g;
var url = location.href;

if (url.match(track_code)){
	if (document.cookie.indexOf('track_cookie') == -1) { // no track_cookie found so need to make one
		cookie_bake();
	} else {
		var ca = document.cookie.split(';');
		var nameEQ = "track_cookie=";
		var cookie_value;

		for(var i=0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
			if (c.indexOf(nameEQ) == 0) cookie_value = c.substring(nameEQ.length, c.length);
		}
		if ((cookie_value != "") || (cookie_value != null)) {
			if ( escape(cookie_value) != escape(url) ) {
				cookie_bake();				
			}
		}
	}
} else {
	var d = new Date();
	document.cookie = "track_cookie=1; expires=" + d.toGMTString() + "; domain=" + domain + ";";	
}

function cookie_bake() {
	//creating expiration date for 30 days from today
	var exp = new Date();
	exp.setTime(exp.getTime() + 1000 * 60 * 60 * 24 * 30);

	document.cookie = "track_cookie=" + escape(url) + "; domain=" + domain + "; expires=" + exp + "; path=/;";
	if (document.referrer) {
		var referral = document.referrer;
		document.cookie = "referral_site=" + referral + ";";
	}	
}
