var redirTo = '';
var hasPopped = false;
var isInternalClick = false;

var	QueryString = $.parseQuery(); //get our QueryString & pass in the imm_cid & imm_mid

function checkForReload() {
	if(redirTo == 'rates_feed') {
		//Allow it to fire once, block all subsequent
		hasPopped = true;
		redirTo = '';
		//pass with params
		window.location = '/mortgage-results.php?imm_cid='+QueryString.imm_cid+'&imm_mid='+QueryString.imm_mid+'&propertyStateCode='+QueryString.propertyStateCode+'&typeOfLoan='+QueryString.typeOfLoan;
	}
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function exitcheck(){
	if(!isInternalClick) {
		//'has_popped' is set inside here, but also fall back on 'Converted' cookie (set by 'anyotherpage.php')
		hasPopped = (readCookie('has_popped') || (readCookie('Converted') == 'YES'));
		if(!hasPopped) {
			if (quit()) {
				// user clicked OK -- send them to the results
				redirTo = 'rates_feed';
			}
		}
	} else {
		// reset 'internalClick'
		isInternalClick = false;
	}
}

function quit() {
	//write our cookie to ensure we only pop once.
	document.cookie = "has_popped=true; path=/;";
	if (confirm("Want a live rate quote without filling out our form?\n\n     Call 800-231-7988 to get a quote now.\n\n             (Powered by QuickenLoans)")) {
		return true;
	} else {
		return false;
	}
}

// scan for onBeforeUnload event, and redirect if the user would like to get rates
setInterval('checkForReload();',100);
window.onbeforeunload = exitcheck;