// ------------------------------------------------------------
// Functions for client-side management of cookie-based popups.
// ------------------------------------------------------------
//
// Usage: 
// 1. Include this script between the <HEAD> tags of the desired HTML page, like:
//        <script src="PATH TO SCRIPT/hicookiepopup.js" type="text/javascript" language="javascript"></script>
// 2. In the BODY begin tag add an "onload" event handler containing a call to "initializePopup".
// 3. At the end of the page, before the ending </BODY> tag, include:
//    - the DIV representing the pseudo-popup (its ID will be used wherever the "popupID" is required);
//      - inside the DIV: the actual IMG representing the popup, and referencing the MAP with clickable areas;
//    - the MAP element that describes the clickable areas of the popup;
//      - inside the MAP: AREA elements representing active parts of the popup;
//      - the AREA elements that are to hide and disable (temporarily or permanently) the popup need to have 
//        the "onclick" attribute set with a call to the "disablePopup" function.
//    Note: If desired, the "onunload" event handler of the BODY tag can also be hooked in order to call 
//          "disablePopup". This will then disable (for the specified duration) the popup as soon as the 
//          user leaves the page or closes the window.
// Details regarding the usage of the mentioned functions are available below with the function definitions.
//
// -----------------------------------------------------------
// -----------------------------------------------------------
// A. Functions for management of cookie-based pseudo-popups.
// In order to conditionally display a cookie-based popup, call initializePopup.
// In order to hide and disable (potentially just temporarily) the popup, call disablePopup.
// -----------------------------------------------------------
// -----------------------------------------------------------
// Function for initializing a cookie-based popup: 
// - displays the popup if no cookie was set
// - hides the popup if an associated cookie exists.
// This function should be called upon completing the load of the popup's host page.
// Supply the ID of the popup object of interest.
// The second argument is optional, and represents the number of milliseconds to delay 
// the display of the popup. If not supplied, the default value is 1000 (i.e. 1 second).
function initializePopup(popupId,delay) {
	var d=parseInt(delay);
	if (isNaN(d)||d<0) d=1000;
	window.setTimeout("showPopup(findPopup('"+popupId+"'),isPopupEnabled('"+popupId+"')?'show':'hide')",d);
}
// Set a cookie to signal that this popup object should no longer be displayed.
// Supply the ID of the popup object of interest.
// Optionally an integer can be supplied, representing the interval, in minutes,
// during which the popup must remain disabled.
function disablePopup(popupId, minutesDisabled) {
	// expiration time for the cookie - by default, Jan-01-2015
	// if set too far in the future, some older browsers will not set it correctly,
	// i.e. will set instead a cookie that expires at the end of the browser's session
	var dExpiration=new Date(2015, 0, 1);
	// check if an interval has been specified
	var iMinutes=parseInt(minutesDisabled);
	if (!isNaN(iMinutes)) {
		// add the specified number of minutes to the current time - this will be the expiration time
		var d=new Date();
		dExpiration=new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes()+iMinutes, d.getSeconds());
	}
	// set a cookie with a name based on the supplied ID, and marked to
	// expire after the supplied number of minutes (or else in year 2015)
	setCookie(buildPopupCookieName(popupId), 'disabled', dExpiration);
	// hide the popup anyway
	showPopup(findPopup(popupId),'hide');
}
// Find out (by querying a cookie) whether or not to display the popup.
// Supply the ID of the popup object of interest.
function isPopupEnabled(popupId) {
	// if the cookie exists, the popup must not be displayed
	return (getCookie(buildPopupCookieName(popupId)) ? false : true);
}
// Build a cookie name based on the ID of a HTML element.
// Supply the ID of the popup object of interest.
function buildPopupCookieName(popupId) {
	return 'popup_cookie_' + popupId;
}
// Helper function for locating the popup object inside the hosting page.
// Attempts various standard & browser-specific ways to reach the popup object.
// Supply the ID of the popup object of interest, and optionally the document object.
function findPopup(popupId, doc) {
	var i,obj;
	if (!doc) doc=document;
	if (doc.getElementById) obj=doc.getElementById(popupId);
	if (!obj&&!(obj=doc[popupId])&&doc.all) obj=doc.all[popupId];
	for (i=0;!obj&&i<doc.forms.length;i++) obj=doc.forms[i][popupId];
	for (i=0;!obj&&doc.layers&&i<doc.layers.length;i++) obj=findPopup(popupId,doc.layers[i].document);
	return obj;
}
// Helper function that sets the visibility of a pseudo-popup (DIV).
// Supply the popup object of interest in the first argument, and "show" or "hide", 
// as desired, in the second argument.
function showPopup(popupObj, action) {
	if (popupObj) {
		var show,hide,obj=popupObj.style;
		if (obj){show='visible';hide='hidden';} else {obj=popupObj;show='show';hide='hide';}
		obj.visibility=(action=='show')?show:hide;
	}
}
// -----------------------------------------------------------
// -----------------------------------------------------------
// B. Cookie management.
// -----------------------------------------------------------
// To set a cookie, use:
//        var isCookieAccepted = setCookie(name, value, [expires, [domain, [path, [isSecure]]]]);
//    The variable isCookieAccepted will be false if the browser did not set the cookie (e.g. cookies are 
//    not enabled, or the cookie is deleted). Versions of Opera appear to return false even after 
//    successfully setting the cookie.
//
// To retrieve a cookie, use:
//        var myCookie = getCookie(name);
//
// To modify a cookie, simply set it again with the new settings.
//
// To delete a cookie, set its expires attribute to a past date. A cookie deleted in this manner might not 
// be removed immediately by the browser. E.g. use:
//        var cookieDeleteAllowed = setCookie(name, '', new Date(0));
// (The call "new Date(0)" produces a Date object corresponding to Jan 1, 1970, which causes the cookie to 
//  be marked as expired).
// -----------------------------------------------------------
// -----------------------------------------------------------
// Sets the specified value to the cookie with the specified name.
// Name and value may contain any characters. The rest of arguments are optional.
// - name:    The name of the cookie to set, modify or delete.
// - value:   The string to be set as the value of the cookie.
// - expires: Setting no expiration date on a cookie causes it to expire when the browser closes.
//            If you set an expiration date in the future, the cookie is saved across browser 
//            sessions. If you set an expiration date in the past, the cookie is deleted.
//            A date can be specified like: new Date(year, month, day, hour, minute, second), where
//            year = e.g. 2005, month=0..11, day=1..31, hour=0..23, minute=0..59, second=0..59.
// - domain:  Setting the domain of the cookie allows pages on a domain made up of more than one 
//            server to share cookie information.
// - path:    Setting a path for the cookie allows the current document to share cookie information 
//            with other pages within the same domain - that is, if the path is set to /thispathname, 
//            all pages in /thispathname and all pages in subfolders of /thispathname can access 
//            the same cookie information.
// - secure:  Setting this flag means the stored cookie information can be accessed only 
//            from a secure environment (HTTPS).
// Returns true if the cookie exists by the time when the function finishes (this can be used
// to test if cookies are enabled in the host browser).
function setCookie(name, value, expires, domain, path, secure) {
	// try to set the cookie
	path = '/'
	document.cookie = escape(name) + "=" + escape(value) +
					((expires && expires.toGMTString) ? ("; expires=" + expires.toGMTString()) : "") +
					((domain) ? ("; domain=" + domain) : "") +
					((path) ? ("; path=" + path) : "") +
					((secure) ? "; secure" : "");
	// check if the cookie is defined
	return (getCookie(name) ? true : false);
}

// Retrieves the value of the cookie with the specified name.
// Returns null if the cookie was not found.
function getCookie(name) {
	// name can contain any characters
	var escName = escape(name);
	// cookie parts and cookies are separated by semicolons
	var aCookie = document.cookie.split("; ");
	for (var i=0; i < aCookie.length; i++) {
		// a name/value pair is separated by an equal sign
		var aNameValue = aCookie[i].split("=");
		if (escName == aNameValue[0]) 
			return unescape(aNameValue[1]);
	}
	// a cookie with the requested name does not exist
	return null;
}
