function load24bitPNGs () // If 8 bit PNGs loaded in a rush first, then load 24 bit PNGs now at leisure.
	{
	// ---- config -----
	oldext = /url\(["']?(([^)]+)\-nq8\.png)["']?\)/;		// regarded as fixed and used as globals within this function's scope
	newext = '.png';
	css_base_href = 'http://www.mountain.rescue.org.uk/assets/templates/mrew/css/'; // Used if stylesheet objects contain relative URLs
	// -----------------

	var cssSheet, cssRules, r, s, images, i, thisRule, matches;

	i = 0;
	images = new Array();

	for (s=0; s < document.styleSheets.length; ++s) // Search all stylesheets
		{
		// Get stylesheet (cross browser)
		cssSheet = document.styleSheets[s];
		cssRules = cssSheet.cssRules ? cssSheet.cssRules : cssSheet.rules;

		for (r=0; r < cssRules.length; ++r) // Search all rules witin each stylesheet
			{
			thisRule = cssRules[r];

			if (thisRule.selectorText && (matches = thisRule.style.cssText.match(oldext)))
				{
				// matches[1] is now the old filename + extension, matches [2] is the new filename

				// Make new image object and store indices so we know where to alter the CSS when the image has loaded
				images[++i] = new Image();
				images[i].stylesheetIndex = s;
				images[i].ruleIndex = r;
				images[i].oldsrc = matches[1];

				images[i].onload = function ()
					{
					var cssSheet, cssRules, selectorTxt, styleTxt;
					
					// Get stylesheet (cross browser)
                			cssSheet = document.styleSheets[this.stylesheetIndex];
                			cssRules = cssSheet.cssRules ? cssSheet.cssRules : cssSheet.rules;
			
					selectorTxt = cssRules[this.ruleIndex].selectorText;
					styleTxt = cssRules[this.ruleIndex].style.cssText.replace(this.oldsrc, this.src);
					
					if (cssSheet.deleteRule)
						{
						// W3C compliant
						cssSheet.deleteRule(this.ruleIndex);
						cssSheet.insertRule(selectorTxt+'{'+styleTxt+'}', this.ruleIndex);
						}
					else
						{
						// IE
						cssSheet.removeRule(this.ruleIndex);
						cssSheet.addRule(selectorTxt, styleTxt, this.ruleIndex);
						}
					}
				
				// Cater for both absolute and relative URLs in the stylesheet object. 
				// Note that Opera 10 translates relative URLs into absolute URLs.
				if (matches[2].substr(0,4) == 'http') images[i].Xsrc = matches[2]+newext; // Disabled pending fix for Opera 10 (TS)
				else images[i].src = css_base_href+matches[2]+newext;
				}
			}
		}
	}

function richtextImagePositioning()
	{
	// Richtext content images - wrap text around narrower images (no changes made if images already floated)
	// Last modified: 26 August 2009 (TS)
	// ----------------------------------
	var divs, imgs, i, j, widthThreshold, contentDiv, imageMargins;

	/*
	 * 	GET THE ELEMENT THAT CONTAINS THE CONTENT
	 */
	contentDiv = document.getElementById('content');
	if (!contentDiv) return; // !! Early Return !!
	/*
	 * 	THIS LINE SETS THE THRESHOLD BELOW WHICH WORDS ARE WRAPPED AROUND A LEFT FLOATED IMAGE
	 */
	widthThreshold = contentDiv.offsetWidth * 0.7;
	/* 
	 *	THIS LINE SETS IMAGE MARGINS
	 */
	imageMargins = '15px';

	divs = contentDiv.getElementsByTagName('div');
	for (i=0; i< divs.length; ++i)
		{
		if(divs[i].className == 'richtext-container')
			{
			// Remove empty text nodes between images (IE workaround)
			if (ieversion) divs[i].innerHTML = divs[i].innerHTML.replace(/(<(img|IMG)[^>]+>)(\&nbsp;|\s)+\<(IMG|img)/, '$1<img');

			imgs = divs[i].getElementsByTagName('img');
			for (j=0; j<imgs.length; ++j)
				{
				if (!imgs[j].style.cssFloat && !imgs[j].style.styleFloat) // If not already floated
					{
					if (imgs[j].offsetWidth + imgs[j].offsetLeft < widthThreshold)
						{
						imgs[j].style.cssFloat = 'left';
						imgs[j].style.styleFloat = 'left';
						imgs[j].style.marginRight = imageMargins;
						}
					else
						{
						if (imgs[j].getAttribute('style')) imgs[j].removeAttribute('style');
						}

					// Remove empty text nodes after images (non-IE)
					if (!ieversion)
						{
						if (imgs[j].nextSibling && imgs[j].nextSibling.nodeType == 3 && imgs[j].nextSibling.nodeValue.match(/^(\&nbsp;|\s)+$/)) imgs[j].parentNode.removeChild(imgs[j].nextSibling);
						}

					// Add margin-right if image comes next 
					if (imgs[j].nextSibling && imgs[j].nextSibling.tagName && imgs[j].nextSibling.tagName.toLowerCase() == 'img') imgs[j].style.marginRight = imageMargins;
					}
				}
			}
		}
	}

// Cross browser style and dimension retrieval
//
// NB:
//	.currentStyle gives the cascaded styles (e.g. '1em') for IE (and Opera, but that isn't used here).
// 	.computedStyle in standards compliant browsers gives computed (pixel) styles.
//
function computedDimension(element, property) {
	/* 
	 * Return computed dimension as a number (in pixels)
	 */
	if (window.getComputedStyle)
		{
		// W3C compliant
		return parseInt(document.defaultView.getComputedStyle(element, null).getPropertyValue(property));
		}
	else if (element.currentStyle)
		{
		/* 
		 * Following is needed for IE up to 7 (IE8 to be tested)
		 */
		var IE_cascadedStyle, hyphen, tempDiv, dimension;
		while ((hyphen = property.indexOf('-')) != -1)
			{ // Convert to camelcase e.g. 'margin-top' becomes 'marginTop'
			// Need to repeat as some properties have >1 hyphen. 
			property = property.substr(0, hyphen).concat(property.charAt(hyphen+1).toUpperCase()).concat(property.substr(hyphen+2));
			}
		IE_cascadedStyle = element.currentStyle[property];
		if (IE_cascadedStyle.match(/^\d+px$/))
			{
			// If cascaded style in pixels, bale out here.
			return parseInt(IE_cascadedStyle);
			}
		else if (IE_cascadedStyle.match(/\d+(%|em|ex|pt|pc|in|mm|cm)$/))
			{
			/* If cascaded style is a length (other than specified
			 * in pixels, then create a dummy block element with this width,
			 * and measure .offsetWidth 
			 */
			tempDiv = document.createElement("div");
        		tempDiv.style.width = IE_cascadedStyle;
		        document.body.appendChild(tempDiv);
		        dimension = tempDiv.offsetWidth;
		        document.body.removeChild(tempDiv);
		        return dimension;
			}
		else
			// Not a dimension - just return value
			return IE_cascadedStyle;
		}
	}

var ieversion; // !! GLOBAL !!

function layout()
	{
	var searchSection_el, searchTab_el, listSection_el, listTab_el, sponsors_el, latest_news_el, scrollFlag, maxHeight, navCol, mainCol, summaryCol;


	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) //test for MSIE x.x;
		ieversion=new Number(RegExp.$1);
	else
		ieversion = null;


	// Wrap text around images in content (see function comments)
	// ----------------------------------
	richtextImagePositioning();

	// Various divs
	// ------------
	searchSection_el = document.getElementById('search-section');
	listSection_el = document.getElementById('list-section');
	sponsors_el = document.getElementById('sponsors-logos');
	latest_news_el = document.getElementById('latest-news-list');
	navCol = document.getElementById('nav');
	mainCol = document.getElementById('main-content');
	summaryCol = document.getElementById('summary-content');
	searchTab_el = document.getElementById('search-tab');
	listTab_el = document.getElementById('list-tab');

	// Equalise columns
	// ----------------

	function equaliseCol(col, maxHeight)
		{
		var newHeight;
		newHeight = (maxHeight - parseInt(computedDimension(col, 'padding-top')) - parseInt(computedDimension(col, 'padding-bottom'))).toString().concat('px');
		if (ieversion == null || ieversion > 6) col.style.minHeight = newHeight;
		else col.style.height = newHeight;
		}

	// Ensure longest section is measured on download list page
	if (searchSection_el && listSection_el)
		{
		if (searchSection_el.offsetHeight > listSection_el.offsetHeight)
			listSection_el.style.display = 'none';
		else
			searchSection_el.style.display = 'none';
		}

	if (mainCol)
		{
		// Equalise columns #nav, #main-content, #summary-content
		// ------------------------------------------------------
		maxHeight = Math.max(mainCol.offsetHeight, navCol.offsetHeight);

		// Equalise nav and main column...
		equaliseCol(navCol, maxHeight);
		equaliseCol(mainCol, maxHeight);
		// ..and fix this one to match the others regardless of its own content length (as it scrolls)
		latest_news_el.style.height = (maxHeight - document.getElementById('emergency-info').offsetHeight).toString().concat('px');
		}
	else
		{

		// Equalise forum columns
		// ----------------------
		mainCol = document.getElementById('content'); // Forums have #content not #main-content
		maxHeight = Math.max(mainCol.offsetHeight, navCol.offsetHeight);
		// Equalise nav and main column...
                equaliseCol(navCol, maxHeight);
                equaliseCol(mainCol, maxHeight);
		}

	// Sponsor logos bottom positioning
	// --------------------------------
	if (sponsors_el) sponsors_el.className = (sponsors_el.className ? sponsors_el.className + ' ' : '') + 'position-bottom' ;

	// Download list sections and 'tabs'
	// ---------------------------------
	if (searchSection_el && listSection_el)
		{
		if (window.location.href.match(/(\?|\&)searchTerms\=/))
			{
			searchSection_el.style.display = 'block';
			searchTab_el.style.display = 'none';
			listSection_el.style.display = 'none';
			}
		else
			{
			listSection_el.style.display = 'block';
			listTab_el.style.display = 'none';
			searchSection_el.style.display = 'none';
			}

		searchTab_el.onclick = function ()
			{
			searchSection_el.style.display = 'block';
			searchTab_el.style.display = 'none';
			listSection_el.style.display = 'none';
			listTab_el.style.display = 'block';
			return false;
			};

		listTab_el.onclick = function ()
			{
			listSection_el.style.display = 'block';
			listTab_el.style.display = 'none';
			searchSection_el.style.display = 'none';
			searchTab_el.style.display = 'block';
			return false;
			};
		}

	// Latest news scrolling
	// ---------------------
	scrollFlag = 1;
	if (latest_news_el)
		{
		function scrollNews()
			{
			if (scrollFlag) latest_news_el.scrollTop = latest_news_el.scrollTop+1;
			scrollTimeout = setTimeout(scrollNews,100);
			}
		scrollNews();
		latest_news_el.onmouseover = function () { scrollFlag = 0; };
		latest_news_el.onmouseout = function () { scrollFlag = 1; };
		}

	// Team lists
	// ----------
	if (document.getElementById('region-filter'))
		{
		document.getElementById('show-by-region-submit').style.visibility = 'hidden';
		document.getElementById('region').onchange= function () { this.parentNode.parentNode.submit(); };
		}

	// 24 bit PNGs
	// -----------
	if (!ieversion || ieversion > 6) load24bitPNGs();
	}

if (window.addEventListener) // DOM Level 2 API
	{
	window.addEventListener("load", layout, 0);
	window.addEventListener("resize", richtextImagePositioning, 0);
	}
else if (window.attachEvent) // IE workaround
	{
	window.attachEvent("onload", layout);
	window.attachEvent("onresize", richtextImagePositioning);
	}

// External links
//
function externalLinks()
	{
	var as, i;
	as = document.getElementsByTagName('a');
	for (i=0; i<as.length; ++i)
		{
		if (as[i].hostname != window.location.hostname && as[i].protocol.toLowerCase().substr(0,4) == "http")
			{
			as[i].onclick = function ()
				{
				window.open(this.href);
				return false;
				}
			}
		}
	}

if (window.addEventListener) // DOM Level 2 API
	window.addEventListener("load", externalLinks, 0);
else if (window.attachEvent) // IE workaround
	window.attachEvent("onload", externalLinks);

