// Sitewide functions

// Dictionary Links
function popupLinks(targetSelector, iconUrl, width, height) {
	
	var links = $(targetSelector);
	var linkArray = [];
	var icon = $('<img src="'+iconUrl+'" alt="(opens in a new window)" />')
	var popupFeatures = "menubar=0,width="+width+",height="+height;
	
	var PopupLink = function (targetNode) {
		var link = $(targetNode);

		link.attr('title', 'Opens in a new window');
		link.text(link.text() + '\u00a0');
		link.append(icon.clone());
		
		link.click(function () {
			var linkHref = $(this).attr('href');
			window.open(linkHref, 'dictionary', popupFeatures);
			return false;
		});
	}	
	
	links.each(function () {
		if ($(this).is("a")) {
			linkArray.push(new PopupLink(this));
		}
	});
}


// 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("Show")
			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("Hide");
			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");
	popupLinks("a.dictionary-link", "images/popup.gif", 300, 500);
});