﻿/*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 cookie,
			cookies = document.cookie.split(/;\s*/),
			x       = cookies.length;

		while (x--) {
			cookie = cookies[x];
			if (cookie.indexOf(name) === 0) {
				// +1 is for the equal sign
				return 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 SITEINDEX = {

	/** 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 display them.
	  */
	init: function () {

		document.cookie.split('; ').forEach(function (cookie) {
			cookie = cookie.split('=');
			var el = document.getElementById(cookie[0]);
			if (el) {
				el.style.display = '';
			}
		});
	},

	/** This function displays/hides the clicked div and set/erase the cookie
	  * indicating its status.
	  */
	swap: function (id) {
		var element = document.getElementById(id);
		if (element.style.display === 'none') {
			element.style.display = '';
			COOKIE.set(id, 'on');
		} else {
			element.style.display = 'none';
			COOKIE.del(id);
		}
	}

};

YAHOO.util.Event.onDOMReady(SITEINDEX.init, SITEINDEX, true);


