/* Copyright Art McBain */

$(document).ready(function() {

	// From http://forum.jquery.com/topic/feature-req-any-selector-filter
	jQuery.expr[':'].any = function(el, i, match) {
		return jQuery.find.matches(match[3], [el]).length > 0;
	};

	function boundHeight(item) {
		return Math.round(item.getBoundingClientRect().height);
	}

	var items = $("#content > .item");
	var maxHeight = 315;
	var margin = 8;

	for(var i = 0; i < items.length; i++) {

		if(boundHeight(items[i]) >= maxHeight) {

			var divs = $("#content > #" + items[i].id + " > :any(header, footer)");
			var paragraphs = $("#content > #" + items[i].id + " > p");

			var total = boundHeight(divs[0]) + Math.floor(margin * .5) + boundHeight(divs[1]);
			var first = null;

			for(var j = 0; j < paragraphs.length; j++) {
				total += margin + boundHeight(paragraphs[j]);

				if(total >= maxHeight) {
					first = j;
					break;
				}
			}

			if (first) {
				var toggle = document.createElement("a");
				toggle.href = location;
				toggle.className = "softlink";
				toggle.style.display = "block";
				toggle.style.cursor = "pointer";
				toggle.style.textAlign = "center";
				toggle.style.outline = "none";
				toggle.onclick = (function(toggle, first, paragraphs) {
					return function() {
						toggle.innerHTML = (toggle.innerHTML === "Show More")? "Show Less" : "Show More";

						for(var i = first; i < paragraphs.length; i++) {
							paragraphs[i].style.display = (paragraphs[i].style.display === "none")? "block" : "none";
						}

						return false;
					};
				}(toggle, first, paragraphs));
				toggle.onclick();

				items[i].appendChild(toggle);
			}
		}
	}
});

