$(document).ready(function(){
	
	$(".myBox").filter(".myBoxToggle").each(function(i){
		$(this)
			.attr("count",i+1)
			.find("*")
			.attr("count",i+1);
	})
	.invokeBoxState()
	.find(".header a")
	.click(function(){
		var myCount = $(this).attr("count");
		var myBox = $(".myBox[count=" + myCount + "]");
		myBox.toggleMyBoxState();
	});
});

$.fn.invokeBoxState = function(){
	$(this)
	.each(function(i){
		var id = $(this).attr("id");
		var count = $(this).attr("count");
		var cookie = $.cookie('myBox_' + id);
		if (cookie == "open")
		{
			$(this)
				.removeClass("myClosedBox");
		}
		// so the first box always starts open if no cookie
		if (cookie != "open" && cookie != "closed" && count == 1)
		{
			$(this).removeClass("myClosedBox");
		}
	});
	return this;
}

$.fn.toggleMyBoxState = function(){
	var id = $(this).attr("id");
	$(this)
		.toggleClass("myClosedBox");
	if ( $(this).find(".content").css("display") == "none" ){
		$.cookie('myBox_' + id, "closed", {path: '/'} );
	} else {
		$.cookie('myBox_' + id, "open", {path: '/'} );
	}
	return this;
}
