function setCookie(c_name,value,expiredays){var exdate=new Date();exdate.setDate(exdate.getDate()+expiredays);document.cookie=c_name+"="+escape(value)+((expiredays==null)?"":";path=/;expires="+exdate.toUTCString());}
function getCookie(c_name){if(document.cookie.length>0){c_start=document.cookie.indexOf(c_name+"=");if(c_start!=-1){c_start=c_start+c_name.length+1;c_end=document.cookie.indexOf(";",c_start);if(c_end==-1)c_end=document.cookie.length;return unescape(document.cookie.substring(c_start,c_end));}}return "";}

var _no_exit  = false;
var _exit_msg = "15% Off your Entire Order if you Stay!";

// just hard code the offer dimensions
var _ow = 756;
var _oh = 505;

$(function () {
	var no_exit = function () {
		_no_exit = true;
		window.onbeforeunload = null;
	};

	if (getCookie('had_exit') != 1) {
		// stop this horrendous shit from firing as we're simply trying to fucking navigate on our own goddamned site
		$('a,div,span,p,img').mousedown(no_exit);

		window.onbeforeunload = function (e) {
			$.get(
				'/ajax/exit-coupon.php',
				function (ret) {
					var y = (document.body.scrollHeight - _oh) / 2;
					var x = (document.body.scrollWidth - _ow) / 2;
					$('body').append('<div id="exit-offer" style="top:0px; left:'+x+'px;"><div class="coupon">'+ret+'</div><a href="javascript:;" onclick="$(\'#exit-offer\').fadeOut();"></a></div>');
					setCookie('had_exit', 1, 7);
					setCookie('had_exit_coupon', ret, 2);
					no_exit();
					return false;
				}
			);

			var e = e || window.e;
			if (e) {
				e.returnValue = _exit_msg;
			}
			return _exit_msg;
		};
	}

	// put the discount code in the header!
	else if (getCookie('had_exit_coupon')) {
		$('.fj-header .slogan').html('15% OFF COUPON: <b>' + getCookie('had_exit_coupon') + '</b>').addClass('coupon');
	}
});
