jQuery.fn.collapsibleNav = function(options) {

	var defaults = {
		hideByDefault: '', //ids of elements you want hidden by default
		clickController: 'a.arrow', //your heading elements
		slideSpeed: 300 //speed of animation
	};

	//initial variables
	var opts = jQuery.extend(defaults, options),
		$list = jQuery(this), //reference list passed to plugin
		$heading = $list.find(opts.clickController), //cache heading element
		$listItems = $list.children(), //get each top level list item
		closedItems; //define var for items to be stored in cookie
	
	//function that is called when slidable is clicked
	function updateArray(e) {

		//get id of element clicked for adding to closed items array
		var eId = jQuery(e).attr('id');

		//look for element in cookie array
		var arrPos = jQuery.inArray(eId, closedItems);

		if (arrPos == -1) {

			//element is not in array, so add it
			closedItems.push(eId);

		} else {

			//element is in array, so remove it
			closedItems.splice(arrPos, 1);

		}

		//update cookie
		jQuery.cookie('closedItems', closedItems, { path: '/', expires: 365 });
	}
	
	
	//remember closed/open state of nav items

	//check that the cookie plugin is available
	if (jQuery.cookie) {

		/*
		  if no cookie called "closedItems" exists, then create one with
		  elements you want hidden by default.
		  '1' is given as first value to prevent cookie from being
		  deleted if it contains no ids
		*/
		if (!jQuery.cookie('closedItems')) {
			jQuery.cookie('closedItems', '1,'+opts.hideByDefault, { path: '/', expires: 365 });
		}

		//if cookie called "closedItems" exists
		if (jQuery.cookie('closedItems')) {

			//split cookie into array
			closedItems = jQuery.cookie('closedItems').split(',');

			//iterate through array and apply "closed" class to each element within it
			for (var i = 0; i < closedItems.length; ++i) {
				jQuery('#' + closedItems[i]).addClass('closed');
			}

			//hide child ul for list items that have a class of closed
			jQuery('.closed').children('div.section').hide();
		}
	}
	
	$heading.click(function(){

		var $target = jQuery(this),
			$parent = $target.parent();

		//toggle closed class
		$parent.toggleClass('closed');

		//show/hide content
		$target.next().slideToggle(opts.slideSpeed);

		//update cookie with current list-item
		updateArray($parent);

		return false;

	});

	return this;
};

$(function() {
	if(!$.cookie('closedItems')){
		$(".section").hide();
		
		
		$(function() {
			var closedItems = new Array; 
			$('div[id^="level_"]').each(function(i) {
				closedItems[i] = this.id ;
				//element is not in array, so add it
			});
			// list = "'+list+'";
			$.cookie('closedItems', closedItems, { path: '/', expires: 365 });
		});
		
	}
	$('#menu').collapsibleNav();
});