jQuery.noConflict();
// Put all your code in your document ready area
jQuery(document).ready(function($){


/*

Sitewide functions

Requires:

    JQuery 1.2.2 (jquery_1-2-2.js)

Changelog:

	2008-05-15 Thomas Hooper:
	- Added multi-element multi-width layout switcher

	2008-05-02 Thomas Hooper:
	- Allowed setCorners to be re-run to add corners to new elements

	2008-04-28 Thomas Hooper:
	- Added support for using a UL as the setScriptPrefrence container

	2008-04-22 Thomas Hooper:
	- Added options to change the link text on setScriptPrefrence, and added defaults to those and the containerId

	2008-01-27 Thomas Hooper:
	- Upgrade to jQuery 1.2.2

	2008-01-07 Thomas Hooper:
	- setLinks now applies .hover to the container, rather than the linked element.
	- DisableScripts link will only be added to the first UL

	2008-01-04 Thomas Hooper:
	- Moved initialisations back into one block (for easy editing upon minimization)
	- Modified from HOP, to make default template version of scripts
	- Seperated setLinks from setCorners script
	- Updated setLinks script (from Barcham)
	- Restricted setCorners class to just .corners
	- Added setLayoutSwitcher (from Barcham)
	- Paramaterised setScriptPreference

    2007-08-13 Thomas Hooper:
    - Removed pipe from disable-scripts link

    2007-08-03 Thomas Hooper:
    - All scripts self-initiate
    - Changed name from global.js to common.js

*/

/*  =======================
    Cookie control (from PPK http://www.quirksmode.org/js/cookies.html)
    ======================= */

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {
    createCookie(name,"",-1);
}



/*  =======================
    Add print link
    ======================= */

//function addPrintLink() {
//    $("#print-link").click(function(){
//        window.print();
//        return false;
//    });
//}

//$(document).ready(function(){
//    addPrintLink();
//});



/*  =======================
    Add rounded corners
    ======================= */

// Add the rounded corners to all classes specified
function setCorners() {

	var ne = "<span class='ne'>&nbsp;</span>";
	var nw = "<span class='nw'>&nbsp;</span>";
	var se = "<span class='se'>&nbsp;</span>";
	var sw = "<span class='sw'>&nbsp;</span>";

    // Gather elements
    var targetElems = $(".rounded, .block, .button");

    // Add extra divs loop
if (targetElems != null){
    $(targetElems).each(function(i){
        var targetElement = $(targetElems[i]);
        if (targetElement.children("span.ne, span.sw, span.se, span.sw").length == 0) {
        	targetElement.prepend(nw).prepend(ne).append(se).append(sw);
        }
    });
}
}



/*  =======================
    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
    if (targetContainers != null){
    $(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];
				});
				targetElement.keypress(function(){
					self.location.href = sourceLink[0];
				});
			}
		}


	}
}



/*  =======================
    Layout switcher, switches classes at different sizes
    ======================= */

/*
function setLayoutSwitcher(switchArray) {

	var switchers = new Array();

	var Switcher = function(switchParams) {
		var jqTarget = $(switchParams.selector);
		var ranges = switchParams.ranges;
		var lastClass = "";

		var checkThreshold = function(point) {
			var rangeToApply = null;

			for (var i = 0; i < ranges.length; i++) {
				var thBegin = 0;
				var thEnd = 9999999999;

				if (i == 0 && ranges[i].th != 0) {
					thBegin = ranges[i].th;
				} else if (i+1 < ranges.length) {
					thBegin = ranges[i].th;
					thEnd = ranges[i+1].th;
				} else {
					thBegin = ranges[i].th;
				}

				if (point >= thBegin && point < thEnd) {
					rangeToApply = i;
				}
			}


			if (rangeToApply == null) {
				applyClass("");
			} else {
				if (ranges[rangeToApply].className) {
					applyClass(ranges[rangeToApply].className)
				} else {
					applyClass("")
				}
			}
		}

		var applyClass = function(className) {
			if (lastClass != className) {
				if (lastClass != "") {
					jqTarget.removeClass(lastClass);
				}

				if (className != "") {
					jqTarget.addClass(className);
				}

				lastClass = className;
			}
		}

		return({
			checkThreshold:checkThreshold
		});
	}

	for (var i = 0; i < switchArray.length; i++) {
		switchers.push(new Switcher(switchArray[i]));
	}




	$(window).bind('resize', function() { checkWidth() } );

	checkWidth()

	function checkWidth(){

		var bodyWidth = $("body").width();

		for (var i = 0; i < switchers.length; i++) {
			//console.log(bodyWidth)
			switchers[i].checkThreshold(bodyWidth);
		}

	}
}

*/

/*  =======================
    Add Disable/Enable Scripts Prefrence
    ======================= */

function setScriptPrefrence() {

    var linkLocation;
	//this.containerId = "site-services";

	containerId = setScriptPrefrence.containerId ? setScriptPrefrence.containerId : "site-services";
	enableText = setScriptPrefrence.enableText ? setScriptPrefrence.enableText : "Enable Scripts";
	disableText = setScriptPrefrence.disableText ? setScriptPrefrence.disableText : "Enable Scripts";

    // Where the link gets inserted (tries different locations)
    if ($("#"+containerId).length != 0) {
        linkLocation = "#"+containerId

		// Check preferences, and set cookie if it's not there
		var allowScripts;
		if (readCookie('allowScripts') == 'false') {
			allowScripts = false;
		} else if (readCookie('allowScripts') == 'true') {
			allowScripts = true;
		} else {
			allowScripts = true;
			createCookie('allowScripts', 'true', 30);
		}

		// Check the link doesn't already exist
		if ($("#scripts-setting").length == 0) {;
			var location = window.location.href;
			// Strip hash
			var hash = location.indexOf("#");
			if (hash != -1) {
				location = location.substring(0, hash);
			}

			if (allowScripts == true) {
				link = "<a href='" + location + "' id='scripts-setting'>"+disableText+"</a>";
			} else {
				link = "<a href='" + location + "' id='scripts-setting'>"+enableText+"</a>";
			}

			if ($(linkLocation+" ul").length != 0) {
				// Add list item wrapper if theres a list in the container
				$(linkLocation+" ul").slice(0, 1).prepend("<li>"+link+"</li>");

			} else if($(linkLocation+":not(ul)").length == 0) {
				// Add list item wrapper if the container is a list
				$(linkLocation).prepend("<li>"+link+"</li>");

			} else {
				// Otherwise just prepend as it is
				$(linkLocation).prepend(link);
			}

			// Change setting and reload page
			$("#scripts-setting").click(function() {
				if (readCookie('allowScripts') == 'true') {
					createCookie('allowScripts', 'false', 30);
				} else if (readCookie('allowScripts') == 'false') {
					createCookie('allowScripts', 'true', 30);
				}
			});
		}

		return(allowScripts);
	}
}


/*  =======================
    INITIALISE Scripts
    ======================= */

$(function(){
	// Add corner spans to elements with class .rounded
    setCorners();

    // Linkify boxes with classes .linkified-box, .linkified-heading, .linkified-image"
    setLinks();
/*
    setLayoutSwitcher([{
		selector:"#footerWrapTwo", ranges:new Array(
			 // The default will be no class at 0-500
			{th:850, className:"switchFooter"}
    )},{
    	selector:"#mastHead", ranges:new Array(
    		{th:0}, // Default, although not required (0-300)
    		{th:975, className:"switchMastHead"}
    )},{
    	selector:"#contentBlock", ranges:new Array(
    		{th:900, className:"switchColumns"}

    )},{
    	selector:"#calendarHeader", ranges:new Array(
    		{th:900, className:"switchColumns"}

    )},{  
    	selector:"#topNavigationBlock", ranges:new Array(
    		{th:900, className:"switchColumnsOne"},
    		{th:1100, className:"switchColumnsTwo"}

    )},{     
       	selector:".featuredContentBlock", ranges:new Array(
    		{th:950, className:"switchOne"},
			{th:1150, className:"switchTwo"}
    )}]);
    
    */

	// Add "Disable Scripts" to this UL (or UL container)
    setScriptPrefrence.containerId = "topNavigationBlock";
	// Change script preference link text
	//setScriptPrefrence.enableText = "Turn on slide show animation";
	//setScriptPrefrence.disableText = "Turn off slide show animation";
});



function accessible_menus(listId) {

    function init() {
        /*
		based on http://www.htmldog.com/articles/suckerfish/dropdowns/
		see also http://www.htmldog.com/ptg/archives/000050.php#comment131
		lines added to workaround for IE not correctly interpreting multiple css classes.
		Conditional comments added to prevent IE<7 showing the select through the menu.
		*/

        /*@cc_on
		/*@if (@ie7 != true)
			var shim = document.createElement('iframe');
			shim.setAttribute('id', 'shim');
			shim.setAttribute('frameBorder','0');
			shim.setAttribute('scrolling','no');
			shim.setAttribute('src','javascript:;');
			//shim.style.display = 'none'; 
			//shim.style.border = '3px solid #f00';
			shim.style.width = '0';
			shim.style.height = '0';
			shim.style.left = '0';
			shim.style.top = '0'; 
			shim.style.zIndex = '90'; 
			shim.style.position = 'absolute'; 
			shim.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
			document.getElementById(listId).appendChild(shim);

			function positionShim(element) {
				var targetElement = null;

				if (element.tagName == "LI" && element.lastChild.tagName == "UL") {
					// LI with nested list, for hover condition
					targetElement = element.lastChild;
				} else if (element.tagName == "A") {
					if (element.parentNode.lastChild.tagName == "UL") {
						// A of a LI with nested list, i.e. keyboard to a top-level link.
						targetElement = element.parentNode.lastChild;
					} else {
						// Sub-nav A, keyboard to a sub-link
						if (element.parentNode.parentNode.getAttribute("id") != listId ) {
							targetElement = element.parentNode.parentNode.parentNode.lastChild;
						}

					}
				}

				if (targetElement) {
					shim.style.width	= targetElement.offsetWidth+"px";
					shim.style.height	= targetElement.offsetHeight+"px";
					shim.style.left		= targetElement.offsetLeft + "px";
					shim.style.top		= targetElement.offsetTop + "px";
					shim.style.display 	= 'block';
				}
			}

			function hideShim(element) {			
				var hideShim = false;

				if (element.tagName == "LI" && element.lastChild.tagName == "UL") {
					// LI with nested list
					hideShim = true;
				} else if (element.tagName == "A") {
					if (element.parentNode.lastChild.tagName == "UL") {
						// A of a LI with nested list
						hideShim = true;
					} else {
						// Sub-nav A
						hideShim = true;
					}
				}

				if (hideShim) {
					shim.style.display='none';
				}
			}
		
		/*@end			
		@*/

        var mcEls = document.getElementById(listId).getElementsByTagName("A");
        for (var i = 0; i < mcEls.length; i++) {
            mcEls[i].onfocus = focus;
            mcEls[i].onblur = blur;
        }
        var mcEls = document.getElementById(listId).getElementsByTagName("LI");
        for (var i = 0; i < mcEls.length; i++) {
            mcEls[i].onmouseover = function(e) {
                if (!e) {
                    if (window.event) {
                        e = window.event
                    }
                }
                this.getElementsByTagName("A")[0].onfocus(e);
            }
            mcEls[i].onblur = function(e) {
                if (!e) {
                    if (window.event) {
                        e = window.event
                    }
                }
                this.getElementsByTagName("A")[0].onfocus(e);
            }
            mcEls[i].onmouseout = function(e) {
                if (!e) {
                    if (window.event) {
                        e = window.event
                    }
                }
                this.getElementsByTagName("A")[0].onblur(e);
            }
            mcEls[i].onfocus = function(e) {
                if (!e) {
                    if (window.event) {
                        e = window.event
                    }
                }
                this.getElementsByTagName("A")[0].onblur(e);
            }
        }

        function focus(e) {
            if (!e) {
                if (window.event) {
                    e = window.event
                }
            }

            // Ensure menu displays
            if (e.type == "focus") {
                this.className += (this.className.length > 0 ? " ": "") + "sffocus";
            } //a:focus
            function showParents(target) {
                target.parentNode.className += (target.parentNode.className.length > 0 ? " ": "") + "sffocusparent"; //li < a:focus
                if (e.type == "focus") {
                    target.parentNode.parentNode.className += (target.parentNode.parentNode.className.length > 0 ? " ": "") + "sffocusparent";
                } //ul < li < a:focus
                if (target.parentNode.parentNode.parentNode.nodeName == "LI") { //li < ul < li < a:focus
                    showParents(target.parentNode.parentNode)
                }
            }
            showParents(this);

            fixOverhang(this);

            /*@cc_on
			/*@if (@ie7 != true)
				this.parentNode.className+=(this.parentNode.className.length>0? " ": "") + "sfhover";
				positionShim(this); // add iframe if needed.	
			/*@end			
			@*/
        }

        function blur(e) {
            if (!e) {
                if (window.event) {
                    e = window.event
                }
            }

            // Ensure menu hides		
            if (e.type == "blur") {
                this.className = this.className.replace(new RegExp("( ?|^)sffocus\\b"), "");
            }
            function hideParents(target) {
                target.parentNode.className = target.parentNode.className.replace(new RegExp("( ?|^)sffocusparent\\b"), "");
                if (e.type == "blur") {
                    target.parentNode.parentNode.className = target.parentNode.parentNode.className.replace(new RegExp("( ?|^)sffocusparent\\b"), "");
                }

                if (target.parentNode.parentNode.parentNode.nodeName == "LI") { //li < ul < li < a:focus
                    hideParents(target.parentNode.parentNode)
                }
            }
            hideParents(this);

            /*@cc_on
			/*@if (@ie7 != true)
				this.parentNode.className=this.parentNode.className.replace(new RegExp("( ?|^)sfhover\\b"), "");
				hideShim(this); // hide iframe if needed.
			/*@end			
			@*/
        }

        function fixOverhang(target) {
            var ulContainer = null;

            //Find container
            var mcEls = target.parentNode.childNodes;

            for (var i = 0; i < mcEls.length; i++) {
                if (mcEls[i].tagName == "UL") {
                    ulContainer = mcEls[i];
                }
            }
            if (!ulContainer && target.parentNode.parentNode.tagName == "UL") {
                ulContainer = target.parentNode.parentNode;
            }

            if (ulContainer) {
                // Incase of text size adjustment
                if (ulContainer.cachedPosition) {
                    if (ulContainer.cachedPosition != ulContainer.parentNode.offsetLeft) {
                        ulContainer.style.left = "";
                    }
                }
                ulContainer.cachedPosition = ulContainer.parentNode.offsetLeft;

                var ulContainerEdge = ulContainer.offsetLeft + ulContainer.offsetWidth;
                var navWidth = document.getElementById(listId).offsetWidth;

                if (ulContainerEdge >= navWidth) {
                    ulContainer.style.left = navWidth - ulContainer.offsetWidth + "px";
                } else {
                    ulContainer.style.left = "";
                }

            }
        }
    }

    // thanks http://www.brothercake.com/site/resources/scripts/onload/
    if (window.addEventListener) {
        // gecko, safari, konqueror and standard
        window.addEventListener('load', init, false);
    } else if (document.addEventListener) {
        // opera 7
        document.addEventListener('load', init, false);
    } else if (window.attachEvent) {
        // win/ie
        window.attachEvent('onload', init);
    } else {
        // mac/ie5
        if (typeof window.onload == 'function') {
            var existing = onload;
            window.onload = function() {
                existing();
                init();
            }
        } else {
            window.onload = init;
        }
    }

}

accessible_menus("top-nav");

});
