// Box Toggle
function boxToggle(targetSelector) {

	var boxes = $(targetSelector);
	var boxArray = [];
	
	var ToggleBox = function (targetNode) {
		// *** SETUP VARIABLES ***
		
		var box = $(targetNode);
		// Get the first and highest heading (prioritising highest over first)
		var firstHeading = box.find("h1, h2, h3, h4, h5")[0];
		// Select the heading's ancestors
		var headingAncestors = $(firstHeading).parents();
		// Add in the heading
		var headingAncestors  = headingAncestors.add(firstHeading);
		// Restrict the ancestors to the box
		headingAncestors = headingAncestors.not(box.parents());
		headingAncestors = headingAncestors.not(box);
		// Get the siblings of ancestors (uncle, great uncle, ...)
		var boxContents = headingAncestors.siblings();


		// *** HIDE/SHOW LINK ***

		var toggleLink = $("<a href='#'></a>");
		toggleLink.insertAfter(firstHeading);


		// *** TOGGLE FUNCTIONS ***

		var hideBox = function() {
			toggleLink.one("click", function(){
				showBox();
				return false;
			})
			toggleLink.text("Read More")
			toggleLink.attr("class", "box-toggle-show");

			boxContents.addClass("hide")
			//boxContents.attr("style", "display:none");
		}

		var showBox = function() {
			toggleLink.one("click", function(){
				hideBox();
				return false;
			})
			toggleLink.text("Close");
			toggleLink.attr("class", "box-toggle-hide");

			boxContents.removeClass("hide")
			//boxContents.removeAttr("style");
		}

		// Initiate
		hideBox();
	}	
	
	boxes.each(function () {
		boxArray.push(new ToggleBox(this));
	});
}

$(document).ready(function(){
	boxToggle("#comments");
});