/*cookieUtil.js*/

//create a cookie
function createCookie(name,value,days) {
	if(name && value) {
	
		var expires = "";
	
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			expires = "; expires="+date.toGMTString();
		}

		document.cookie = name + "=" + value + expires + "; path=/";
	}
}

//read a cookie
function readCookie(name) {
	var nameEQ = name + "=";
	var allCookies = document.cookie.split(';');
	for(i=0; i < allCookies.length; i++) {
		var currentCookie = allCookies[i];

		while (currentCookie.charAt(0) == ' ') {
			currentCookie = currentCookie.substring(1);
		}

		if (currentCookie.indexOf(nameEQ) == 0) {
			return currentCookie.substring(nameEQ.length,currentCookie.length);
		}
	}

	return null;
}

//erase a cookie
function eraseCookie(name) {
	createCookie(name,"",-1);
}


//check for cookie onload and create 1/3 of the time
function checkAndDrop() {
	//if there's not a cookie
	if(!readCookie("exitSurvey")) {
		//drop one 1/3 of the time that allows an exit survey
		if(Math.random()*100 <= 33.3333) {
			createCookie("exitSurvey","allow");
		} else {
			//and shut it off for everyone else
			createCookie("exitSurvey","deny");
		}
	} else {
		//cookie exists. Do nothing.
	}
}

var selfUnload = new Boolean(true);

function launchUnload() {
	if(selfUnload == true) {
		if(readCookie("exitSurvey") == "allow") {
			window.open("unloadCatcher.html","unloadCatcher","width=1,height=1");
		}
	}
}

function stopUnload() {
	selfUnload = false;
}
