﻿/*global document, YAHOO */



var COOKIE = {
	set: function (name, value) {
		var expires = new Date(),
		cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);

		expires.setFullYear(expires.getFullYear() + 1);
		expires = expires.toGMTString();
		cookie += '; expires=' + expires + '; path=/';

		document.cookie = cookie;
		return cookie;
	},
	get: function (name) {
		var cookies = document.cookie.split(/;\s*/),
		cookie, x = cookies.length;

		while (x--) {
			cookie = cookies[x];
			if (cookie.indexOf(name) === 0 &&
				cookie.charAt(name.length) === "=") {
				// +1 is for the equal sign
				return decodeURIComponent(cookie.substring(name.length + 1));
			}
		}
		return null;
	},
	del: function (name) {
		var expires = new Date(),
		cookie = encodeURIComponent(name) + '=';

		expires.setDate(expires.getDate() - 1);
		expires = expires.toGMTString();

		cookie += '; expires=' + expires + '; path=/';
		document.cookie = cookie;
		return cookie;
	}
};

var SINDEX = {

	/** When the Site Index page is loaded, init() check all the
	  * cookies. If there are cookies set, this loop through all the cookies
	  * and extract the id of the divs that were being viewed then displays
	  * them.
	  */
	init: function () {

		var cookie = COOKIE.get("SINDEX");

		if (cookie !== null) {
			cookie.split(",").forEach(function (id) {
				var el = document.getElementById(id);
				if (el) {
					el.style.display = '';
				}
			});
		}

	},

	/** This function displays/hides the clicked div and set/erase the cookie
	  * indicating its status
	  */
	swap: function (id) {

		var cookie = COOKIE.get("SINDEX"),
		x, el = document.getElementById(id);

		if (el) {
			cookie = (cookie) ? cookie.split(",") : [];

			if (el.style.display === 'none') {
				el.style.display = '';
				if (cookie.indexOf(id) === -1) {
					cookie.push(id);
					COOKIE.set("SINDEX", cookie.join(","));
				}
			} else {
				el.style.display = 'none';
				while ((x = cookie.indexOf(id)) !== -1) {
					cookie.splice(x, 1);
					COOKIE.set("SINDEX", cookie.join(","));
				}
			}
		}

	}

};

YAHOO.util.Event.onDOMReady(SINDEX.init, SINDEX, true);


