/*
 * Initializes the section accordion.
 * 
 * Depends:
 *   jquery.js
 *   ui.core.js
 *   ui.accordion.js
 */

$(function() {
		initCategoriesAccordion(-1);
		displayAccordion();
});

function initCategoriesAccordion() {
	$('#accordion').accordion({
			header: 'h3',
			active: getAccordionIndex(false),
			alwaysOpen: false,
			autoHeight: false,
			collapsible: true,
			skip: ".validlink",
			change: function(event, ui) {
				var index = -1;
				$('#accordion .ui-accordion-header').each(function(i) {
					if ($(this).hasClass('ui-state-active')) {
						index = i;
						$(this).focus();
					}
				});
				setCookie('accordionIndexEAforums', index);
			}
	});
}

function displayAccordion() {
	$('#accordion .section').each(function(i) {
		$(this).removeClass('section');
	});
	$('#accordion .categories').each(function(i) {
			$(this).removeClass('categories');
	});
}

function getAccordionIndex (defaultIndex) {	
	if (this.getCookie('accordionIndexEAforums')) {
		return parseInt(this.getCookie('accordionIndexEAforums'));
	} else {	
		return defaultIndex;
	}
}

function getCookie (cookieName) {
	var allcookies = document.cookie;
	var pos = allcookies.indexOf(cookieName + '=');
	if (pos !== -1) {
		var start = pos + cookieName.length + 1; // add 1 to include the "=" sign
		var end	 = allcookies.indexOf(';', start);
		
		if (end === -1) {
			end = allcookies.length;
		}
		
		var value = allcookies.substring(start, end);
		value = decodeURIComponent(value);		
	}
	return value;
}

function setCookie (cookieName, cookieValue, expires) {
	var exp = expires || 360; // default to one year
	var expiresDate = new Date();	
	expiresDate.setTime(expiresDate.getTime() + (1000 * 60 * 60 * 24 * exp));
	document.cookie = cookieName + '=' + encodeURIComponent(cookieValue) + '; expires=' + expiresDate.toGMTString() + '; path=/';
}