/*  =======================
    Add links to certain elements
    ======================= */

// Add extra 'links' (mouse only) to certain elements
function setLinks() {

    // Gather elements
    var targetContainers = $(".linkified-box, .linkified-heading, .linkified-image");

    // Stores linked elements
    var linkedContainers = new Array();

    // Add links loop
    $(targetContainers).each(function(i){
		var targetContainer = $(targetContainers[i]);

		linkedContainers.push(new linkContainer(targetContainer))
	});

	function linkContainer(targetContainer) {
		
        // Get the first link (although there should only really be one)
		var sourceLink = $(targetContainer.find("a")[0]);

        if (targetContainer.is(".linkified-box")) {
       		// adding an onclick to the container element
			var targetElement = targetContainer;

			linkify(targetElement, sourceLink);
		}
		if (targetContainer.is(".linkified-heading")) {
			// adding a "linkified span" to the first and highest heading (prioritising highest over first)
			var heading = $(targetContainer.find("h1, h2, h3, h4, h5")[0]);
			// Add a span with the heading content
			var targetElement = $("<span></span>").html(heading.html());
			// Clear the heading content and replace it with the span
			heading.empty();
			heading.append(targetElement);

			linkify(targetElement, sourceLink);
		}
		if (targetContainer.is(".linkified-image")) {
			// adding an onclick to the first image
			var targetElement = $(targetContainer.find("img")[0]);
			linkify(targetElement, sourceLink);
		}


		// Linkify the element with the source link target
		function linkify(targetElement, sourceLink) {

			// Ensure there are no child links that would be rendered inaccessible (ignoring the source link)
			var noChildren = true;
			var allLinks = targetElement.find("a");
			if (allLinks.length > 0) {
				// There are child links

				if (allLinks.length > 1 || allLinks[0] != sourceLink[0]) {
					// There is more than one child link, or the one link doesn't equal the source link
					noChildren = false;
				}
			}

			// OK to proceed
			if (noChildren == true) {

				// Add class for styling
				targetElement.addClass("linkified");

				// Add and remove hover styles when hovering, also set window status to url
				targetElement.mouseover(function(){
					// Apply to all linked elements
					targetContainer.addClass("hover");
					window.status = sourceLink[0];
				});
				targetElement.mouseout(function(){
					// Apply to all linked elements
					targetContainer.removeClass("hover");
					window.status = window.defaultStatus;
				});

				// Map onClick Event to sourceLink Click handler
				targetElement.click(function(){
					self.location.href = sourceLink[0];
				});
			}
		}


	}
}

/*  =======================
    INITIALISE Scripts
    ======================= */

$(function(){
    // Linkify boxes with classes .linkified-box, .linkified-heading, .linkified-image"
    setLinks();
});