(function () {
	var SHORT_EXPIRY_MINUTES = 2;
	var LONG_EXPIRY_MINUTES = 24 * 60;
	var LOGIN_COOKIE_ID = 'sid';
	
	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 getCurrentDomain () {
		return window.location.hostname;
	}
	
	function createCookie (name, value, expiryDate) {
		var expires = "";
		var domain = getCurrentDomain();
		if (expiryDate) {
			expires = "; expires=" + expiryDate.toGMTString();
		}
		document.cookie = name + "=" + value + expires + "; path=/help/; domain=" + domain + "; secure";
	}
	
	function getFutureDate (timeInMinutes) {
		var futureDate = new Date();
		futureDate.setTime(futureDate.getTime() + (timeInMinutes * 60 * 1000));
		return futureDate;
	}
	
	function deleteCookie (name) {
		var expiryDate = getFutureDate(-1000*60*60);
		var domain = getCurrentDomain();
		document.cookie = name + "=; max-age=0; expires=" + expiryDate.toGMTString(); + "; path=/help/; domain=" + domain + "; secure";
	}

	function updateLoginCookieExpiryDate (newExpiryDate) {
		var loginCookieValue = readCookie(LOGIN_COOKIE_ID);
		if (loginCookieValue) {
			deleteCookie(LOGIN_COOKIE_ID);
			createCookie(LOGIN_COOKIE_ID, loginCookieValue, newExpiryDate);
		}
	}
	
	jQuery(window).unload( function () {
		var shortExpiryDate = getFutureDate(SHORT_EXPIRY_MINUTES);
		updateLoginCookieExpiryDate(shortExpiryDate);
	});

	var longExpiryDate = getFutureDate(LONG_EXPIRY_MINUTES);
	updateLoginCookieExpiryDate(longExpiryDate);
}())
