$(document).ready( function() {

	/* Bind click function to collapsible box click area */
	$("div.collapsible_boxes > div.box > a.box_spot").click( function() {
		boxId = $(this).parent().attr("id");
		if (boxId) {
			if ($("#" + boxId + " > a.box_spot > span").hasClass("open")) {
				closeBox(boxId, true);
			}
			else {
				openBox(boxId, true);
			}
		}
		return false;
	});
	
	/* Check for opened boxes stored in cookies */
	$("div.collapsible_boxes > div.box").each( function() {
		boxId = this.id;
		if (boxId) {
			var storedState = $.cookie(boxId);			if ((storedState) && (storedState == 'open')) {
				openBox(boxId, false);
			}
		}
	});
	
	/* Load box contents */
	$("div.box").each( function() {
		var boxId, boxContentPage;
	
		boxContentPage = $(this).attr("name");
		boxId = this.id;
		if (boxContentPage && boxId) {
			loadBoxContent(boxId, "/CollapsibleContent/"+boxContentPage);
			$("#" + boxId + " a.loading_trouble").click( function() {
				loadBoxContent(boxId, "/CollapsibleContent/"+boxContentPage);
				return false;
			});
		}
	});
			
});

loadBoxContent = function(boxId, url) {
	$("#" + boxId + " div.contents").load( url, {}, hideBoxLoading );
}

hideBoxLoading = function() {
	$(this).parent().children("div.loading").hide();
}
		
openBox = function(boxId, animate) {
	$("#" + boxId + " > a.box_spot > span.closed").removeClass("closed").addClass("open");
			
	if (animate) {
		$("#" + boxId + " > div.box_content").show("fast");
	}
	else {
		$("#" + boxId + " > div.box_content").show();
	}
	$.cookie(boxId, 'open', {expires: 365});
}
		
closeBox = function(boxId, animate) {
	$("#" + boxId + " > a.box_spot > span.open").removeClass("open").addClass("closed");
	if (animate) {
		$("#" + boxId + " > div.box_content").hide("fast");
	}
	else {
		$("#" + boxId + " > div.box_content").hide();
	}
	$.cookie(boxId, 'closed', {expires: 365});
}