<!--
//WARNING - EVIL browser-sniffing ahead
//var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
var IE6 = /msie|MSIE 6/.test(navigator.userAgent);
var Safari = (document.childNodes) && (!document.all) && (!navigator.taintEnabled) && (!navigator.accentColorName);
var Opera = (self.opera != null); 

// -----------------------
// FUNCTION: fAllowTabbing
// DESCRIPTION: Prevents onkey evetns firing when the tab key is pressed, thus allowing users to tab past them
// ARGUMENTS: 1: the event - always described as: event, 2: a function name to call without parenthesis "()", 3 variable names to pass to a function. Multiple variable names must be seperated by a "~", i.e. 'variable one~variable two~variable three~etc...'
// RETURNS: n/a
// N.B: onKey.... events should be followed with "return:true;" NOT "return:false" as for onClick events.
// -----------------------
function fAllowTabbing(e, sFunctionName, sVariable) {
	var e = e || window.event;
	var sKeyPressed = e.keyCode || e.charCode;

	if (sKeyPressed != 9) {
		if (sVariable) {
			if (sVariable.match("~")) {
				var aVariables = sVariable.split('~');
				window[sFunctionName].apply(this, aVariables);
			} else {
				window[sFunctionName](sVariable);
			}
		} else {
		window[sFunctionName]();
		}
	}
}

// Switches a selected class on a specified element.
// Pass the element ID and class name that needs to be added or removed.
function fSwitchClass(sElementId, sClassToSwitch) {

	var eElement = document.getElementById(sElementId);
	var sClassName = eElement.className;
	if (sClassName.match(sClassToSwitch) || sClassName.match(' ' + sClassToSwitch)) {
		// Removes Class
		eElement.className = eElement.className.replace(sClassToSwitch, '');
	} else {
		// Adds Class
		eElement.className = sClassName + ' ' + sClassToSwitch;
	}
}
// -----------------------
// FUNCTION: addEvent
// DESCRIPTION: Attaches an event to the requested object
// ARGUMENTS: 1: The object type, 2: The event type 3: The function to be called
// -----------------------
function fAddEvent(sObject, sEventType, sFunction){ 
 if (sObject.addEventListener){ 
	 if (Safari && (sEventType == 'DOMContentLoaded'))	{	//safari
		sEventType = 'load';
	 } 
	 sObject.addEventListener(sEventType, sFunction, false); 
	 return true; 
 } else if (sObject.attachEvent){
	if (sEventType == 'DOMContentLoaded') {
		sEventType = 'load';
	}
	var sReturn = sObject.attachEvent("on" + sEventType, sFunction); 
	return sReturn; 
 } else { 
   return false; 
 } 
}
//-----------------
// Function: fRemoveEvent
// DESCRIPTION: Removes an event from the object
// ARGUMENTS: 1: The object 2: The event type 3: Associated function
// ----------------
function fRemoveEvent(sObject, sEventType, sFunction){
  if (sObject && sObject.removeEventListener){
    sObject.removeEventListener(sEventType, sFunction, false);
    return true;
  } else if (sObject.detachEvent){
    var oRemove = sObject.detachEvent("on" + sEventType, sFunction);
    return oRemove;
  } else {
    return false;
  }
}

// -----------------------
// FUNCTION: fGetTarget
// DESCRIPTION: Returns the object of an event
// ARGUMENTS: The Event
// RETURNS: The object
// -----------------------
function fGetTarget(e) {
	e = e || window.event;
	if (e.target) {
		var sTarget = e.target;
	}
	if (e.srcElement) {
		var sTarget = e.srcElement;
	}
	return sTarget;
}

// Removes the default value of an input
function fRemoveValue(e) {
	var oTarget = fGetTarget(e);
	var ignoreSite = ((isSiteInPath('pregnancycareplanner')) && (oTarget.defaultValue.indexOf('e.g.') != 0));  //fix for pregnancyplanner

	if ((oTarget.value == oTarget.defaultValue) && !ignoreSite) {
		oTarget.value = '';
	}
}

// Adds the default value to an input if no entry present
function fAddValue(e) {
	var oTarget = fGetTarget(e);
	if (oTarget.value == '') {
		oTarget.value = oTarget.defaultValue;
	}
}
// -----------------------
// FUNCTION: fInputClear
// DESCRIPTION: clears and repopulates inputs unless listed in aPresetFormElements array
// -----------------------
function fInputClear() {
	// Add clearing to Inputs
	aInputs = document.getElementsByTagName('input');
	nInputLength = aInputs.length;
	for (nInputCount = 0; nInputCount < nInputLength; nInputCount++) {		
		 if (aInputs[nInputCount].type == 'text') {
		    if (aInputs[nInputCount].readOnly) {
		        var sReadOnlyId = aInputs[nInputCount].id;
		        fAddEvent(aInputs[nInputCount], 'focus', function() {document.getElementById(sReadOnlyId).select();});   
		    } else {
			    fAddEvent(aInputs[nInputCount], 'focus', fRemoveValue);
			    fAddEvent(aInputs[nInputCount], 'blur', fAddValue);
			}
		 }
	}
	// Add clearing to Text areas
	aTextAreas = document.getElementsByTagName('textarea');
	nTextAreaLength = aTextAreas.length;
	for (nTextAreaCount = 0; nTextAreaCount < nTextAreaLength; nTextAreaCount++) {
		fAddEvent(aTextAreas[nTextAreaCount], 'focus', fRemoveValue);
		fAddEvent(aTextAreas[nTextAreaCount], 'blur', fAddValue);
	}
	// Check for excluded form elements.
	// NB: This will clear any elements with their ID listed in the array 'aPresetFormElements' - this array should be declared on the page from the back end.
	if (typeof aPresetFormElements != 'undefined') {
		var nPresetLength = aPresetFormElements.length;
		for (nPresetCount = 0; nPresetCount < nPresetLength; nPresetCount++) {
			fRemoveEvent(document.getElementById(aPresetFormElements[nPresetCount]), 'focus', fRemoveValue);
			fRemoveEvent(document.getElementById(aPresetFormElements[nPresetCount]), 'blur', fAddValue);
		}
	}
}

// Remove all nodes from within an element
function fRemoveNodes(sParentId) {
	var oChildNodes = document.getElementById(sParentId).childNodes;
	while (oChildNodes[0]) {
		document.getElementById(sParentId).removeChild(oChildNodes[0]);
	}
}

// Create and return a DOM element.
function fCreateElement(hElement) {
	if (hElement.type) {
		var oElement = document.createElement(hElement.type);
		if (hElement.className) {
			oElement.className = hElement.className;
		}		
		if (hElement.id) {
			oElement.id = hElement.id;
		}
		if (hElement.forTag) {
			oElement.htmlFor = hElement.forAttribute;
		}
		if (hElement.inputType) {
		    oElement.type = hElement.inputType;
		}
		if (hElement.inputValue) {
		    oElement.defaultValue = hElement.inputValue;
		    oElement.value = hElement.inputValue;
		}
		if (hElement.elementName) {
			oElement.name = hElement.elementName;
		}
		if (hElement.href) {
			oElement.href = hElement.href;
		}
		if (hElement.title) {
			oElement.title = hElement.title;
		}
		if (hElement.tabindex) {
			oElement.tabIndex = hElement.tabindex;
		}			
		return oElement;
	}	
}

// *******************************************************************************
// *******************************************************************************
// BEGIN: Slider Functions
// *******************************************************************************
// *******************************************************************************
// Global variables for slider functions
var sElementId;
var nElementHeight;
var nHeight;
var nTargetHeight;
var sSetStyle;
var sSliderElementId;
var nSpeed;
var sClassName;
var nDivideBy;
var oDelay;
var sLinkElementId;
// -----------------------
// FUNCTION: fSliderSetUp
// DESCRIPTION: Searches for slider tags and attaches an onmousedown event to them
// -----------------------
function fSliderSetUp() {
	var aSliderLinks = document.getElementsByName('toggler-div');
	var nSliderCount = aSliderLinks.length;
	
	for (nCount = 0; nCount < nSliderCount ; nCount++ ) {
		fAddEvent(aSliderLinks[nCount], 'click', fHandleSliderEvents);
		fAddEvent(aSliderLinks[nCount], 'keypress', fHandleSliderEvents);
		var sIdentifier=aSliderLinks[nCount].id.replace(/toggler-link-/,"");
		if (aSliderLinks[nCount].innerHTML=="" && aSliderLinks[nCount].title!="")	{
			aSliderLinks[nCount].innerHTML=aSliderLinks[nCount].title;
			sLinkClass=aSliderLinks[nCount].className;
			if (sLinkClass.match('hidden') || sLinkClass.match(' hidden')) {
				fSwitchClass(aSliderLinks[nCount].id, 'hidden');
			}
		}
		if (sIdentifier == 'personalisation-footer') {
		    var sCookie = fReadCookie('Personalisation.FooterState');
		    if (sCookie) {
		        if (sCookie.match('show')) {
		            document.getElementById('toggler-div-personalisation-footer').className += ' hidden';
		            fSwitchClass('toggler-link-personalisation-footer', 'hide');
		            fSwitchClass('toggler-link-personalisation-footer', 'show');
		            document.getElementById('toggler-link-personalisation-footer').innerHTML = 'show';
		        }
		    } else {
		        var sInitialState = document.getElementById('toggler-link-' + sIdentifier).className;
		        if (sInitialState.match('show')) {
		            document.getElementById('toggler-div-' + sIdentifier).className += ' hidden';		
		            fCreateCookie('Personalisation.FooterState', 'show', 7);
		        }
		    }
	    } else {
				var sShowOrHide = document.getElementById('toggler-link-' + sIdentifier).className;
				if (sShowOrHide.match('show')) {
					fSwitchClass(('toggler-div-' + sIdentifier), 'hidden');
				}
			
		}
    }
}
// -----------------------
// FUNCTION: fHandleSliderEvents
// DESCRIPTION: Catches slider events
// ARGUMENTS: the event
// -----------------------
function fHandleSliderEvents(e) {
	if (oDelay)	{
		clearTimeout(oDelay);
	}
	var e = e || window.event;
	sKeyPressed = e.keyCode || e.charCode;
	if (sKeyPressed == 9) {
		return false;
	}
	var oTargetElement = e.target || e.srcElement;
	sElementId = oTargetElement.id;
	//var nTheNumber = sElementId.match(/\d+/);
	sIdentifier = sElementId.replace(/toggler-link-/,"");
	sElementId = 'toggler-div-' + sIdentifier;
	sLinkElementId = 'toggler-link-' + sIdentifier;
	fDetectState(sElementId);
}

// -----------------------
// FUNCTION: fDetectState
// DESCRIPTION: Detects the state of the slider div container and then calls either open or close as required
// ARGUMENTS: The id of the element to check
// -----------------------
function fDetectState(sElementId) {
	sSliderElementId = sElementId;
	var eElement = document.getElementById(sSliderElementId);
	sClassName = eElement.className;

	sSetStyle = document.getElementById(sSliderElementId).style;

	if (sClassName.match('divide-') || sClassName.match(' divide-')) {
			var nStringIndex = sClassName.indexOf('divide-');
			nDivideBy = sClassName.slice(nStringIndex + 7, nStringIndex + 11 );
			nDivideBy = parseInt(nDivideBy, 10);
		}
	if (sClassName.match('hidden') || sClassName.match(' hidden')) {
		fSlideOpen();
	} else {
		fSlideClosed();
	}
}
// -----------------------
// FUNCTION: fSlideOpen
// DESCRIPTION: Initial script to set up the div to slide open
// ARGUMENTS: none
// -----------------------
function fSlideOpen() {
	fSwitchClass(sSliderElementId, 'hidden');
	nElementHeight = fGetHeight(sSliderElementId);
	nTargetHeight = nElementHeight;
	nSpeed = (nTargetHeight/nDivideBy);
	sSetStyle.overflow = 'hidden';
	sSetStyle.height = '0px';
	nHeight = 0;
	fOpenControl();
	fCreateCookie('Personalisation.FooterState', 'hide', 7);
}
// -----------------------
// FUNCTION: fSlideClosed
// DESCRIPTION: Initial script to set up the div to slide closed
// ARGUMENTS: none
// -----------------------
function fSlideClosed() {
	nTargetHeight = 0;
	nElementHeight = fGetHeight(sSliderElementId);
	sSetStyle.height = nElementHeight;
	sSetStyle.overflow = 'hidden';
	nHeight = nElementHeight;
	nSpeed = (nElementHeight/nDivideBy);
	fCloseControl();
	fCreateCookie('Personalisation.FooterState', 'show', 7);
}
// -----------------------
// FUNCTION: fOpenControl
// DESCRIPTION: sets speed of slide and repeatedly calls the setHeight() function until fully open - then clears styling
// ARGUMENTS: none
// -----------------------
function fOpenControl() {
	nHeight += nSpeed;
	if (nHeight <= nTargetHeight) {
		oDelay = setTimeout('fSetHeight(\'fOpenControl\')', 1);
	} else {
		sSetStyle.overflow = '';
		sSetStyle.height = '';

		if (document.getElementById(sLinkElementId).className.match('show') || document.getElementById(sLinkElementId).className.match(' show')) {
			fSwitchClass(sLinkElementId, 'show');
			fSwitchClass(sLinkElementId, 'hide');
			if (document.getElementById(sLinkElementId).innerHTML.match('show')) {
			    document.getElementById(sLinkElementId).innerHTML = 'hide';
			}
		}
	}
}
// -----------------------
// FUNCTION: fCloseControl
// DESCRIPTION: sets speed of slide and repeatedly calls the setHeight() function until fully closed - then clears styling
// ARGUMENTS: none
// -----------------------
function fCloseControl() {
	nHeight -= nSpeed;

	if (nHeight >= nTargetHeight) {
		oDelay = setTimeout('fSetHeight(\'fCloseControl\')', 1);
	} else {
		fSwitchClass(sSliderElementId, 'hidden');
		sSetStyle.overflow = '';
		sSetStyle.height = '';
		if (document.getElementById(sLinkElementId).className.match('hide') || document.getElementById(sLinkElementId).className.match(' hide')) {
			fSwitchClass(sLinkElementId, 'hide');
			fSwitchClass(sLinkElementId, 'show');
			if (document.getElementById(sLinkElementId).innerHTML.match('hide')) {
			    document.getElementById(sLinkElementId).innerHTML = 'show';
			}
		}
	}
}
// -----------------------
// FUNCTION: fGetHeight
// DESCRIPTION: get the height of the div
// ARGUMENTS: none
// RETURNS: calculated height
// -----------------------
function fGetHeight() {
	return document.getElementById(sSliderElementId).offsetHeight;
}
// -----------------------
// FUNCTION: fSetHeight
// DESCRIPTION: sets a style height on a div and then calls the function passed to it
// ARGUMENTS: a function name
// -----------------------
function fSetHeight(sFunctionName) {
	document.getElementById(sSliderElementId).style.height = nHeight + 'px';
	window[sFunctionName]();
}

// *******************************************************************************
// *******************************************************************************
// END: Slider Functions
// *******************************************************************************
// *******************************************************************************

//-----------------------
// FUNCTION: fCreateCookie
// DESCRIPTION: A function that creates a cookie
// ARGUMENTS: 1: Cookie Name, 2: Cookie Value 3: Expiry date
//-----------------------
function fCreateCookie(sName, sValue, sDays) {
	if (sDays) {
		var oDate = new Date();
		oDate.setTime(oDate.getTime() + (sDays * 24 * 60 * 60 * 1000));
		var sExpires = "; expires=" + oDate.toGMTString();
	}
	else var sExpires = "";
	document.cookie = sName + "=" + sValue + sExpires + "; path=/";
}
//-----------------------
// FUNCTION: fReadCookie
// DESCRIPTION: A function that reads a cookie
// ARGUMENTS: 1: Cookie Name
// RETURN: cookie string or null if no cookie present
//-----------------------
function fReadCookie(sName) {
	var sNameEQ = sName + "=";
	var aCookies = document.cookie.split(';');
	for(var nCount = 0; nCount < aCookies.length; nCount++) {
		var sCookie = aCookies[nCount];
		while (sCookie.charAt(0)==' ') sCookie = sCookie.substring(1, sCookie.length);
		if (sCookie.indexOf(sNameEQ) == 0) return sCookie.substring(sNameEQ.length, sCookie.length);
	}
	return null;
}
//-----------------------
// FUNCTION: fDeleteCookie
// DESCRIPTION: A function that deletes a cookie
// ARGUMENTS: 1: Cookie Name , path , domain
//-----------------------
function fDeleteCookie( name, path, domain ) 
{
    if ( GetCookie( name ) ) 
        document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// ----------------------
// FUNCTION: fGetHref
// DESCRIPTION: A function that returns the url of the "what's this' link in social bookmarks
// ARGUMENTS: None
// RETURN: sLinkRef (the url)
// ----------------------
function fGetHref() {
	var aLinks = document.getElementById('social-bookmarks').getElementsByTagName('a');
	var nLength = aLinks.length;

	for (nCount = 0; nCount < nLength ; nCount++) {
		if (aLinks[nCount].className.match('explanation')) {
			var sLinkRef = aLinks[nCount].href;
			return sLinkRef;
		}
	}
}

// ----------------------
// FUNCTION: fRenderBookmarkLinks
// DESCRIPTION: A function that renders bookmark links
// ARGUMENTS: None
// ----------------------
function fBookmarkingLinks() {
    fAddEvent(document.getElementById('delicious'), 'click', fDelicious);
    fAddEvent(document.getElementById('delicious'), 'keydown', function(){fDelicious});
    fAddEvent(document.getElementById('diggit'), 'click', fDigg);
    fAddEvent(document.getElementById('diggit'), 'keydown', function(){fDigg});
    fAddEvent(document.getElementById('facebook'), 'click', fFacebook);
    fAddEvent(document.getElementById('facebook'), 'keydown', function(){fFacebook});
    fAddEvent(document.getElementById('reddit'), 'click', fReddit);
    fAddEvent(document.getElementById('reddit'), 'keydown', function(){fReddit});
    fAddEvent(document.getElementById('stumbleupon'), 'click', fStumbleupon);
    fAddEvent(document.getElementById('stumbleupon'), 'keydown', function(){fStumbleupon});
	
}
function fDelicious(e) {
	window.open('http://del.icio.us/post?url=' + encodeURIComponent(location.href) + '%26title%3D' + encodeURIComponent(document.title));
	if (e.target) {
		e.preventDefault();
	}
	if (e.srcElement) {
		return false;
	}
}
function fDigg(e) {
	window.open('http://digg.com/submit?url=' + encodeURIComponent(location.href) + '%26title%3D' + encodeURIComponent(document.title));
	if (e.target) {
		e.preventDefault();
	}
	if (e.srcElement) {
		return false;
	}
}
function fFacebook(e) {
	window.open('http://www.facebook.com/sharer.php?u='  + encodeURIComponent(location.href) + '%26title%3D' + encodeURIComponent(document.title));
	if (e.target) {
		e.preventDefault();
	}
	if (e.srcElement) {
		return false;
	}
}
function fReddit(e) {
	window.open('http://reddit.com/submit?url=' + encodeURIComponent(location.href) + '%26title%3D' + encodeURIComponent(document.title));
	if (e.target) {
		e.preventDefault();
	}
	if (e.srcElement) {
		return false;
	}
}
function fStumbleupon(e) {
	window.open('http://www.stumbleupon.com/submit?url='  + encodeURIComponent(location.href) + '%26title%3D' + encodeURIComponent(document.title));
	if (e.target) {
		e.preventDefault();
	}
	if (e.srcElement) {
		return false;
	}
}

function fCheckPopUpStatus(oHttpRequest) {
	if (oHttpRequest.readyState == 4) {
		if (oHttpRequest.status == 200) {
			var sInnerHTML = oHttpRequest.responseText;
			fRenderPopUp(sInnerHTML)			
		} else {
			var sInnerHTML =  '<p class="error"><span>Sorry there was a problem with that request.</span> Please try again later</p>';
			fRenderPopUp(sInnerHTML)
		}
	}
}
/* NEW Bookmarking */
function fRenderPopUp(sInnerHTML) {
	var hDiv1 = {type:'div', className:'blur', id:'blur'};
	hDiv1 = fCreateElement(hDiv1);
	hDiv1.style.opacity = '.7';
	document.body.insertBefore(hDiv1, document.body.firstChild);
	
	/* Create the pop-up */
	hDiv1 = {type:'div', className:'info-box', id:'personalisation-popup'};
	hDiv1 = fCreateElement(hDiv1);
	if ((nPopupHeight) && (nPopupWidth)) {
	    nPopupWidth = (parseInt(nPopupWidth) + parseInt(20));
      nPopupHeight = (parseInt(nPopupHeight) + parseInt(44));
	    hDiv1.style.width = nPopupWidth + "px";    
	    hDiv1.style.height = nPopupHeight + "px";    
	    hDiv1.style.left =nPopupLeft + "px";    
	    hDiv1.style.top =nPopupTop + "px";
	    hDiv1.className = 'info-box tool-box ';   
	}	
	var hDiv2 = {type:'div', className:'top'};
	hDiv2 = fCreateElement(hDiv2);
	var hSpan1 = {type:'span', className:'crnr tl'};
	hSpan1 = fCreateElement(hSpan1);
	var hSpan2 = {type:'span', className:'crnr tr'};
	hSpan2 = fCreateElement(hSpan2);

	hDiv2.appendChild(hSpan1);
	hDiv2.appendChild(hSpan2);
	hDiv1.appendChild(hDiv2);

	hDiv2 = {type:'div', className:'info-mid-brdr'};
	hDiv2 = fCreateElement(hDiv2);
	var hDiv3 = {type:'div', className:'info-box-mid clear'};
	hDiv3 = fCreateElement(hDiv3);
	var hLink1 = {type:'a', id:'close', className:'close'};
	hLink1 = fCreateElement(hLink1);
	var sText1 = document.createTextNode('close');
	
	hLink1.appendChild(sText1);

	hDiv3.appendChild(hLink1);
	hDiv3.innerHTML += sInnerHTML;
	hDiv2.appendChild(hDiv3);
	hDiv1.appendChild(hDiv2);

	var hSpan1 = {type:'span', className:'crnr br'};
	hSpan1 = fCreateElement(hSpan1);
	var hSpan2 = {type:'span', className:'crnr bl'};
	hSpan2 = fCreateElement(hSpan2);

	hDiv1.appendChild(hSpan1);
	hDiv1.appendChild(hSpan2);

	var hDiv2 = {type:'div', className:'bottom'};
	hDiv2 = fCreateElement(hDiv2);	

	hDiv1.appendChild(hDiv2);

	document.body.insertBefore(hDiv1, document.body.firstChild);

	fAddEvent(document.getElementById('close'), 'click', fClosePopUp);
	
	if (IE6) {
		var nPageHeight = document.body.offsetHeight;
		document.getElementById('blur').style.height = nPageHeight;
		var nScrollPos = fGetScroll();
		var nDivHeight = document.getElementById('personalisation-popup').offsetHeight;
		document.getElementById('personalisation-popup').style.marginTop = nScrollPos;
		document.getElementById('personalisation-popup').style.marginBottom = ('-' + (nScrollPos + (nDivHeight - 7)));
	}
}

function fClosePopUp() {
	var oRemove = document.body.removeChild(document.getElementById('personalisation-popup'));
	oRemove = document.body.removeChild(document.getElementById('blur'));
}

// Creates a hidden input '___JSSniffer' and inserts into each <form> element on the page
// Used for JS detection on search result with maps. (i.e. if no JS - no map tab will be rendered).
function fCreateSniffer() {
	var aTheForm = document.body.getElementsByTagName('form');
	var nFormCount = (aTheForm.length);
	for (nCount = 0; nCount < nFormCount; nCount++) {
	    var oInput = document.createElement('input');
	    oInput.setAttribute('type', 'hidden');
	    oInput.setAttribute('name', '___JSSniffer');
	    oInput.id = '___JSSniffer';
	    oInput.value = 'true';  
	    aTheForm[nCount].insertBefore(oInput, aTheForm[nCount].firstChild);
	}
}

// Hides all elements of a given type within a container element using the CSS class 'hidden'
// recieves the container ID and element type
function fHideElements(sContainerId, sElementType) {
	var sElementId;
	var sContainer = document.getElementById(sContainerId);
	var aElements = sContainer.getElementsByTagName(sElementType);
	var nArrayLength = aElements.length;
	for (nCount = 0; nCount < nArrayLength ; nCount++) {
		sElementId = aElements[nCount].id;
		fSwitchClass(sElementId, 'hidden');
	}
}

var oMSGlobals; // Global variable for Main Search.

// Object instance to hold global variables for main search switching.
function fMainSearchGlobals() {
	this.sSearchContainer = 'search-options';
	this.sActiveId = 'search-1';
	this.sActiveClassName = 'active';
}

// ----------------------
// FUNCTION: fSearchOptionsSetUp
// DESCRIPTION: Re-styling and event allocation for main search.
// ARGUMENTS: none
// ----------------------
function fSearchOptionsSetUp() {
	fHideElements('search-options','input');
	oMSGlobals = new fMainSearchGlobals();
	var aLabels = document.getElementById(oMSGlobals.sSearchContainer).getElementsByTagName('label');
	var nLabelCount = aLabels.length;
	for (nCount = 0; nCount < nLabelCount; nCount++ ) {
		fAddEvent(document.getElementById(aLabels[nCount].id), 'click', fSearchOptionsSwitch);
		fAddEvent(document.getElementById(aLabels[nCount].id), 'keydown', fSearchOptionsSwitch);
	}
}

// ----------------------
// FUNCTION: fSearchOptionsSwitch
// DESCRIPTION: Switches active search tab
// ARGUMENTS: none
// ----------------------
function fSearchOptionsSwitch(e) {
	e = e || window.event;
	if (e.target) {
		var sTargetId = e.target.id;
	}
	if (e.srcElement) {
		var sTargetId = e.srcElement.id;
	}
	if (sTargetId) {
		if (sTargetId.match(/\d+/)) {
			if (sTargetId != oMSGlobals.sActiveId) {
				fSwitchClass(oMSGlobals.sActiveId, oMSGlobals.sActiveClassName);
				fSwitchClass(sTargetId, oMSGlobals.sActiveClassName);
				oMSGlobals.sActiveId = sTargetId;
			}
		}	
	}
}

// ----------------------
// FUNCTION: fSetIds
// DESCRIPTION: Searches for element types with a specific classname and adds an ID to them of that classname + a number. e.g. <ul class="list"> becomes <ul class="list" id="list-1">
// Arguments: sType is the element type e.g. "div" or "ul", sClassName is the class name to match
// ----------------------
function fSetIds(sType, sClassName) {
	var aElements = document.getElementsByTagName(sType);
	var nLength = aElements.length;
	var nIdCount = 0;
	this.aIds = new Array();

	for (nCount = 0; nCount < nLength ; nCount++) {
		if (aElements[nCount].className.match(sClassName)) {
			aElements[nCount].id = (sClassName + '-' + nIdCount);
			this.aIds[nIdCount] = (sClassName + '-' + nIdCount);
			nIdCount++
		}
	}
}

var oCLGlobals; // Global variable for carousel style lists.

function fCarouselListGlobals() {
	this.sClassIdentifier = 'carousel-list'; // classname attached to lists to search for
	this.sNewClass = 'carousel-list-js'; // New classname for the JS version list
	this.nListCount;
	this.nListPosition;
	this.nListItemCount;
	this.nSlideTime = '500'; // Time for sliding between list items (1000 = 1 second).
	this.nSlideInterval = '50'; // Time for each slide interval (100 = 0.1 second).
	this.nSectionWidth;
	this.sParentClass = 'list-box' // Classname for parent container that sets overall width for individual list item.
	this.nIntervalCounter = 0;
	this.nSwapCount = new Array();
	this.bIsActive = false;
}

function fAddListItemIds(sParentId, nListNumber) {
	var aListItems = document.getElementById(sParentId).getElementsByTagName('li');
	oCLGlobals.nListItemCount = aListItems.length;
	for (nSubCount = 0; nSubCount < oCLGlobals.nListItemCount ; nSubCount++) {
		aListItems[nSubCount].id = 'list-' + nListNumber + '-item-' + nSubCount;
	}
}

function fAddNav(sListId, sDirection) {
	var oDiv = document.createElement('span');
	oDiv.className = sDirection + '-arrow';
	var oImg = document.createElement('img');
	oImg.setAttribute('src', '/img/nhsdirect/' + sDirection + '-arrow.gif');
	oImg.setAttribute('alt', sDirection);
	oImg.setAttribute('height', '28');
	var oLink = document.createElement('a');
	oLink.setAttribute('title', sDirection);
	oLink.id = sListId + '-' + sDirection + '-arrow';
	var sLinkId = sListId + '-' + sDirection + '-arrow';
	oLink.appendChild(oImg);
	oDiv.appendChild(oLink);
	oParent = document.getElementById(sListId).parentNode;
	sListId = document.getElementById(sListId);
	oParent.insertBefore(oDiv, sListId);
	fAddEvent(document.getElementById(sLinkId), 'click', function() {fScroll(sLinkId, sDirection)});
}

function fScroll(sElementId, sDirection) {
	if (oCLGlobals.bIsActive == false) {
		var nListNumber = sElementId.match(/\d+/);
		var sListId = (oCLGlobals.sClassIdentifier + '-' + nListNumber);
		fSlideList(sListId, sDirection);	
	}	
} 

function fSlideList(sListId, sDirection) {
	var nIntervalCount = (oCLGlobals.nSlideTime / oCLGlobals.nSlideInterval);
	var nSlideDistance = (oCLGlobals.nSectionWidth / nIntervalCount);
	var sCurrentLeft = document.getElementById(sListId).style.left;
	if (oCLGlobals.nIntervalCounter < (nIntervalCount)) {
		var oSliderTimeout = setTimeout(function () {fSliderTimeout(sListId, sDirection, sCurrentLeft, nSlideDistance)}, oCLGlobals.nSlideInterval);
		oCLGlobals.bIsActive = true;
	} else {
		oCLGlobals.nIntervalCounter = 0;
		clearTimeout(oSliderTimeout);
		oCLGlobals.bIsActive = false;
		sListId = document.getElementById(sListId);
		fCenterList(sListId);
		fSwitchList(sListId, sDirection);
		}
}

function fSliderTimeout(sListId, sDirection, sCurrentLeft, nSlideDistance) {
	var nCurrentLeft = sCurrentLeft.match(/\d+(\.\d+)?/);
	if (sDirection == 'back') {
		var nNewLeft = (parseFloat(nCurrentLeft) - parseFloat(nSlideDistance));
	} else {
		var nNewLeft = (parseFloat(nCurrentLeft) + parseFloat(nSlideDistance));
	}
	document.getElementById(sListId).style.left = ('-' + nNewLeft + 'em');
	oCLGlobals.nIntervalCounter++;
	fSlideList(sListId, sDirection);
}

function fSwitchList(sListId, sDirection) {
	var aItems = sListId.getElementsByTagName('li');
	if (sDirection == 'back') {
		var oElementToSwitch = aItems[aItems.length-1].id;
		var oElementHolder = sListId.removeChild(document.getElementById(oElementToSwitch));
		sListId.insertBefore(oElementHolder, sListId.firstChild);
	} else {
		var oElementToSwitch = aItems[0].id;
		var oElementHolder = sListId.removeChild(document.getElementById(oElementToSwitch));
		sListId.appendChild(oElementHolder);
	}
	sListId.style.visability = '';
}

function fCreateCarouselLists() {
	oCLGlobals = new fCarouselListGlobals();
	var oSetIds = new fSetIds('ul', oCLGlobals.sClassIdentifier);
	oCLGlobals.nListCount = oSetIds.aIds.length;
	for (nCount = 0; nCount < oCLGlobals.nListCount; nCount++) {
		fSwitchClass(oSetIds.aIds[nCount], oCLGlobals.sClassIdentifier);
		fSwitchClass(oSetIds.aIds[nCount], oCLGlobals.sNewClass);
		fAddListItemIds(oSetIds.aIds[nCount], nCount);
		fAddNav(oSetIds.aIds[nCount], 'forward');
		fAddNav(oSetIds.aIds[nCount], 'back');
		var sListId = document.getElementById(oSetIds.aIds[nCount]);
		oCLGlobals.nSwapCount[nCount] = Math.floor(oCLGlobals.nListItemCount / 2);
		for (nSubCount = 0; nSubCount < oCLGlobals.nSwapCount[nCount] ; nSubCount++) {
			fSwitchList(sListId, 'back');
		}
	fCenterList(sListId);
	} 
}

function fCenterList(sListId) {
	var nListNumber = sListId.id;
	var nListNumber = nListNumber.match(/\d+/);
	// Loop up to parent that sets width.
	var sParentId = sListId;
	do {
		sParentId = sParentId.parentNode;
	} while (sParentId.className != oCLGlobals.sParentClass);
	
	// Get parent width
	if (window.getComputedStyle) {
		oCLGlobals.nListPosition = getComputedStyle(sParentId, null).getPropertyValue("width");
		var nDivideBy = fCalculateEMs(sListId ,oCLGlobals.nListPosition);	
		oCLGlobals.nListPosition = oCLGlobals.nListPosition.replace('px', '');
		oCLGlobals.nListPosition = Math.round(oCLGlobals.nListPosition / nDivideBy);
	} else if (sParentId.currentStyle) {
		oCLGlobals.nListPosition = sParentId.currentStyle.width + '';
		oCLGlobals.nListPosition = oCLGlobals.nListPosition.replace ('em', '');
	}
	// Add the negative margin to the list.
	sListId.style.visability = 'hidden';
	oCLGlobals.nSectionWidth = oCLGlobals.nListPosition;
	oCLGlobals.nListPosition = ('-' + (oCLGlobals.nListPosition * oCLGlobals.nSwapCount[nListNumber]) + 'em');
	sListId.style.left = oCLGlobals.nListPosition;
}

function fCalculateEMs(sListId, nPixelSize) {
	var oTempDiv = document.createElement('div');
	oTempDiv.id = 'em-test-div';  // N.B. Need id declaration to match in CSS with width of 1000em;
	sListId.appendChild(oTempDiv);
	var oTempId = document.getElementById('em-test-div');
	var nPixelWidth = window.getComputedStyle(oTempId, null).getPropertyValue("width");
	nPixelWidth = nPixelWidth.replace('px', '');
	var nEmWidth = (nPixelWidth / 1000);
	sListId.removeChild(oTempId);
	return nEmWidth;
}

var oCarouselGlobals;

function fCarouselGlobals() {
	this.oActiveTab = 0;
}

function fCarouselSwitch(e) {
	var oTarget = fGetTarget(e);
	var sTargetId = oTarget.id;
	var nTab = sTargetId.match(/\d+/);
	if (nTab != oCarouselGlobals.oActiveTab) {
		fSwitchClass(('carousel-image-' + oCarouselGlobals.oActiveTab), 'hidden');
		fSwitchClass(('carousel-image-' + nTab), 'hidden');
		if (document.getElementById('carousel-text-' + oCarouselGlobals.oActiveTab)) {
			fSwitchClass(('carousel-text-' + oCarouselGlobals.oActiveTab), 'hidden');	
		}
		if (document.getElementById('carousel-text-' + nTab)) {
			fSwitchClass(('carousel-text-' + nTab), 'hidden');
		}				
		fSwitchClass(('carousel-link-' + oCarouselGlobals.oActiveTab), 'active');
		fSwitchClass(('carousel-link-' + nTab), 'active');
		oCarouselGlobals.oActiveTab = nTab;
	}
}

function fGetPreviousSibling(oInsertBefore) {
	var oSibling = oInsertBefore.previousSibling;
	while (oSibling.nodeType !=1) {
			oSibling = oSibling.previousSibling;
		}
	return oSibling;
}

function fCarousel(sCarouselId) {
	oCarouselGlobals = new fCarouselGlobals();
	// Asign initial image ID
	var oOrignalImage = document.getElementById('carousel').getElementsByTagName('img');
	oOrignalImage[0].id = 'carousel-image-0';
	// Add Events
	var aStoredHrefs = new Array();
	var oLinks = document.getElementById(sCarouselId).getElementsByTagName('a');
	var nLinksLength = oLinks.length;
	var nLinkIdCount = 0;
	for (nLinksCount = 0; nLinksCount < nLinksLength; nLinksCount++) {
		if (oLinks[nLinksCount].className.match('tab-link')) {
			oLinks[nLinksCount].id = ('carousel-link-' + nLinkIdCount);
			aStoredHrefs[nLinkIdCount] = oLinks[nLinksCount].href;
			oLinks[nLinksCount].removeAttribute('href');
			fAddEvent(oLinks[nLinksCount], 'click', fCarouselSwitch)
			nLinkIdCount++;
		}
	}
	// Create Carousel text ids
	var oDivs = document.getElementById(sCarouselId).getElementsByTagName('div');
	var nDivLength = oDivs.length;
	var nTabIdIndex = 0;
	for (nDivCount = 0; nDivCount < nDivLength; nDivCount++) {
		if (oDivs[nDivCount].className.match('carousel-text')) {
			oDivs[nDivCount].id = ('carousel-text-' + nTabIdIndex);
		}
		if (oDivs[nDivCount].className.match('carousel-tab')) {
			oDivs[nDivCount].id = ('carousel-tab-' + nTabIdIndex);
			nTabIdIndex++
		}
	}		
	// Create Image objects
	var aImages = new Object();
	var nImageLength = aCarouselImages.length;
	for (nImageCount = 0; nImageCount < nImageLength; nImageCount++) {		
		// aStoredHrefs[nLinkIdCount]
		aImages[nImageCount] = document.createElement('img');
		aImages[nImageCount].setAttribute('src', aCarouselImages[nImageCount]);
		aImages[nImageCount].setAttribute('alt', aCarouselAltTexts[nImageCount]);
		aImages[nImageCount].className = 'hidden';
		aImages[nImageCount].id = ('carousel-image-' + (nImageCount + 1));
		if (!document.getElementById('carousel-text-' + (nImageCount + 1))) {
			var oLink = document.createElement('a');
			oLink.setAttribute('href', aStoredHrefs[nImageCount +1])
			oLink.setAttribute('title', '');
			oLink.appendChild(aImages[nImageCount]);
			aImages[nImageCount] = oLink;
		}
	}
	// Insert images
	for (nInsertCount = 0; nInsertCount < nImageCount; nInsertCount++) {
		if (document.getElementById('carousel-text-' + (nInsertCount + 1))) {
			var oInsertPoint = document.getElementById('carousel-text-' + (nInsertCount + 1));
		} else {
			var oInsertPoint = document.getElementById('carousel-tab-' + (nInsertCount + 1));
		}
		var oSibling = fGetPreviousSibling(oInsertPoint);
		document.getElementById('carousel').insertBefore(aImages[nInsertCount], oInsertPoint);
	}
}

// Checks for requirement of and adds common site wide events.
function fAddChoicesEvents() {
	fSliderSetUp();
	if (document.getElementById('social-bookmarking')) {
		fBookmarkingLinks();
	}
	if (document.getElementById('questions')) {
		fCreateCarouselLists();
	}
	if (document.getElementById('search-options')) {
		fSearchOptionsSetUp();
	}
	if (document.getElementById('carousel')) {
		fCarousel('carousel');
	}
	fInputClear();
	fCreateSniffer();
   
}
fAddEvent(window, 'load', fAddChoicesEvents);

/* BEGIN: Personalisation Functionality */

/* Global Variables */
var nWinWidth = '';
var nWinHeight = '';
var nPopupHeight = '';
var nPopupWidth = '';
var nPopupLeft = '';
var nPopupTop = '';
// ----------------------
// FUNCTION: fShowLayer
// DESCRIPTION: A function that positions, reveals and gives focus to the layer
// ARGUMENTS: n/a
// ----------------------
function fShowLayer(sLayerID) {
	fSwitchClass(sLayerID, 'display-none');

		var oSelects = document.getElementsByTagName('select');
		var nSelectCount = oSelects.length;
		if (IE6) {
			var sTempId = '';
			for (nCount = 0; nCount < nSelectCount ; nCount++) {
				sTempId = oSelects[nCount].id;
				fSwitchClass(sTempId, 'hidden');
			}
			var nScreenHeight = document.body.offsetHeight;
			document.getElementById('blur').style.height = nScreenHeight;
		}
		var nScrollPos = fGetScroll();
		fGetPageSize();
		var nMessageHeight = document.getElementById('message-box').offsetHeight;
		var nTop = Math.floor((nScrollPos + (nWinHeight/2)) - (nMessageHeight/2)) ;
		var nMessageWidth = document.getElementById('message-box').offsetWidth;
		var nLeft = Math.floor((nWinWidth/2) - (nMessageWidth/2));
		document.getElementById('message-box').style.top = nTop + 'px';
		document.getElementById('message-box').style.left = nLeft + 'px';
		document.getElementById('top-to-bottom').style.height = nMessageHeight + 'px';
		document.getElementById('left-to-right').style.height = (nMessageHeight - 18) + 'px';
		document.getElementById('message-box-close').focus();
}

// ----------------------
// FUNCTION: fGetScroll
// DESCRIPTION: A function that returns how far the user has scrolled down the page.
// ARGUMENTS: n/a
// RETURN: nScrollHeight - the number of pixels scrolled down.
// ----------------------
function fGetScroll() {
	var nScrollHeight = 0;
    if ( typeof(window.pageYOffset) == 'number' ) {
		nScrollHeight = window.pageYOffset;
    } else if (document.body && document.body.scrollTop) {
		nScrollHeight = document.body.scrollTop;
    } else if (document.documentElement && document.documentElement.scrollTop) {
		nScrollHeight = document.documentElement.scrollTop;
	}
	return nScrollHeight;
}

// ----------------------
// FUNCTION: fGetPageSize
// DESCRIPTION: A function that calculates the width and height of the available view port.
// ARGUMENTS: n/a
// ----------------------
function fGetPageSize(){
	if (typeof window.innerWidth!='undefined') {
		nWinWidth = window.innerWidth;
		nWinHeight = window.innerHeight;
	} else if (document.documentElement && typeof document.documentElement.clientWidth!='undefined' && document.documentElement.clientWidth!=0 ) {
		nWinWidth = document.documentElement.clientWidth;
		nWinHeight = document.documentElement.clientHeight;
	} else if (document.body && typeof document.body.clientWidth!='undefined') {
		nWinWidth = document.body.clientWidth;
		nWinHeight = document.body.clientHeight;
	}
}

// ----------------------
// FUNCTION: fRemoveElement
// DESCRIPTION: A function that removes an element from the DOM
// ARGUMENTS: 1: The parent ID, 2: The actual element ID
// ----------------------
function fRemoveElement(sParent, sElementToRemove) {
	sParent = document.getElementById(sParent);
	sElementToRemove = document.getElementById(sElementToRemove);
	sParent.removeChild(sElementToRemove);
}

// ----------------------
// FUNCTION: fMakeRequest
// DESCRIPTION: A function that makes a httpRequest and then passes that to a function
// ARGUMENTS: sUrl: the url of the file to be called, sFunction: the function to pass it to
// RETURN: False or Function Call
// ----------------------
function fMakeRequest(sUrl, sFunction) {
	var oHttpRequest;

	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		oHttpRequest = new XMLHttpRequest();
			if (oHttpRequest.overrideMimeType) {
				oHttpRequest.overrideMimeType('text/xml');
			}
		}	else if (window.ActiveXObject) { // IE
				try {
					oHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
				}	catch (e) {
						try {
							oHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
						}	catch (e) {
							}
					}
			}
			if (!oHttpRequest) {
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
			fPopupHeightWidth(sUrl);
        oHttpRequest.onreadystatechange = function() { eval(sFunction + '(oHttpRequest)'); };        
		oHttpRequest.open('GET', sUrl+'?bustcache='+new Date().getTime(), true);
        oHttpRequest.send('');
    }
    
// ----------------------
// FUNCTION: fPopupHeightWidth
// DESCRIPTION: A function that returns top and left positions for a popup box for it to be in the center of the screen
// ARGUMENTS: sUrl: the url of the popup content containing it's height and width
// RETURN: 1: Left position, 2: Top position
// ----------------------
function fPopupHeightWidth(sUrl) {
    if(sUrl.length > 1) {
        keyValuePairs = new Array();
        keyValue = new Array();
   
        for (var i=0; i < sUrl.split('&').length; i++) {
            keyValuePairs[i] = sUrl.split('&')[i];             
            keyValue = keyValuePairs[i].split('=');
            if (keyValue[0]== 'height') {
                nPopupHeight = (parseInt(keyValue[1]) + parseInt(10)); // give it extra height
            } 
            else if (keyValue[0]== 'width') {
                nPopupWidth = (parseInt(keyValue[1]) + parseInt(10)); //give it extra width
            }
        }
        
        fGetPageSize();
        nPopupLeft = (parseInt((nWinWidth) - parseInt(nPopupWidth))/parseInt(2));
        nPopupTop = (parseInt((nWinHeight) - parseInt(nPopupHeight))/parseInt(2)); 
    
        if (nPopupLeft < 0) {
            nPopupLeft = 10; // give it a little positioning
        }
        
        if (nPopupTop < 0) {
            nPopupTop = 10; // give it a little positioning
        }
    }
}

/* Height & Weight */
var aHeightInputs = new Array();
var aWeightInputs = new Array();

// -----------------------
// FUNCTION: fAddBMIListeners
// DESCRIPTION: A function that adds event listeners to the height and weight form.
// ARGUMENTS: 1: fieldset ID.
// -----------------------
function fAddBMIListeners(sFieldsetID) {
	if (document.getElementById(sFieldsetID)) {
		var oContainerID = document.getElementById(sFieldsetID);

		switch (sFieldsetID)
		{
		case 'height' :
			aHeightInputs = oContainerID.getElementsByTagName('input');
			var nLength = aHeightInputs.length;
			for (nCount = 0; nCount < nLength; nCount++ ) {
				fAddEvent(aHeightInputs[nCount], 'keyup', fBMIControl)
			}
			break;
		case 'weight' :
			aWeightInputs = oContainerID.getElementsByTagName('input');
			var nLength = aWeightInputs.length;
			for (nCount = 0; nCount < nLength; nCount++ ) {
				fAddEvent(aWeightInputs[nCount], 'keyup', fBMIControl)
			}
			break;
		}
	}
}
/* Conversion Globals */
var bHeightError = false;
var bWeightError = false;
// -----------------------
// FUNCTION: fBMIControl
// DESCRIPTION: A function that handles the weight and height events.
// ARGUMENTS: 1: the event itseld.
// -----------------------
function fBMIControl(e) {
	fPopulateInputArray();
	e = e || window.event;
	if (e.target) {
		var sTargetId = e.target.id;
		var sValue =  e.target.value;
	}
	if (e.srcElement) {
		var sTargetId = e.srcElement.id;
		var sValue = e.srcElement.value;
	}
	var nAtLeastZero = document.getElementById(sTargetId).value;
					if (nAtLeastZero == '') {
						nAtLeastZero = 0;
						document.getElementById(sTargetId).value = 0;
					}
	var sLastDigit = sValue.charAt(sValue.length-1);
	var bIsNotANumber = isNaN(sLastDigit);
	if (bIsNotANumber) {
		var nCutStringAt = sValue.length-1;
		sValue = sValue.substr(0, nCutStringAt);
		document.getElementById(sTargetId).value = sValue;
		fAtLeastZero(sTargetId);
	} else {
		
		var aTargetId = sTargetId.split('_');
		var nArrayLength = (aTargetId.length -1);

		switch (aTargetId[nArrayLength]) {
			case 'feet':
				fAtLeastZero(sTargetId);
				fHeightImperialToMetric();
				break;
			case 'inches':
				var nInchesValue = document.getElementById(sTargetId).value;
				
				if (nInchesValue > 11 && bHeightError == false) {
					var oDiv = document.createElement('div');
					var oLabel = document.createElement('label');
					oDiv.setAttribute('id', 'height-error');
					oLabel.setAttribute('id', 'height-error-label');
					oDiv.setAttribute('tabindex', '0');
					oLabel.setAttribute('for', sTargetId);
					oLabel.setAttribute('tabindex', '0');
					var oText = document.createTextNode('Please enter an inches value of less than 12');
					oLabel.className = 'error';
					oLabel.appendChild(oText);
					oDiv.appendChild(oLabel);
					var oHeight = document.getElementById('height');
					oHeight.insertBefore(oDiv, oHeight.firstChild);
					document.getElementById('height-error').focus();
					bHeightError = true;
				}
				if (nInchesValue < 12 && bHeightError == true) {
					fRemoveElement('height', 'height-error');
					bHeightError = false;
				}
				fAtLeastZero(sTargetId);
				fHeightImperialToMetric();
				break;
			case 'metres':
				fAtLeastZero(sTargetId);
				fHeightMetricToImperial();
				break;
			case 'centimetres':
				fAtLeastZero(sTargetId);
				fHeightMetricToImperial();
				break;
			case 'stone':
				fAtLeastZero(sTargetId);
				fWeightImperialToMetric(0);
				break;
			case 'pounds':
				var nPoundsValue = document.getElementById(sTargetId).value;
				
				if (nPoundsValue > 13 && bWeightError == false) {
					var oDiv = document.createElement('div')
					var oLabel = document.createElement('label');
					oDiv.setAttribute('id', 'weight-error');
					oDiv.setAttribute('tabindex', '0');
					oLabel.setAttribute('for', sTargetId);
					oLabel.setAttribute('tabindex', '0');
					oLabel.setAttribute('id', 'weight-error-label');
					var oText = document.createTextNode('Please enter an pounds value of less than 14');
					oLabel.className = 'error';
					oLabel.appendChild(oText);
					oDiv.appendChild(oLabel);
					var oWeight = document.getElementById('weight');
					oWeight.insertBefore(oDiv, oWeight.firstChild);
					document.getElementById('weight-error').focus();
					bWeightError = true;
				}
				if (nPoundsValue < 14 && bWeightError == true) {
					fRemoveElement('weight', 'weight-error');
					bWeightError = false;
				}
				fAtLeastZero(sTargetId);
				fWeightImperialToMetric(0);
				break;
			case 'kilos':
				fAtLeastZero(sTargetId);
				fWeightMetricToImperial();
				break;
			}
		}
}

var aInputIds = new Array();
/* N.B. 0 = feet, 1 = inches, 2 = metres, 3 = centimetres, 4 = stone, 5 = pounds, 6 = kilos */

// -----------------------
// FUNCTION: fPopulateInputArray
// DESCRIPTION: A function that gathers the IDs of the height & weight inputs into the array aInputIds.
// ARGUMENTS: None
// -----------------------
function fPopulateInputArray() {
	var aHeightInputIds = new Array();
	var aWeightInputIds = new Array();
	var sFieldset = document.getElementById('height');
	var aHeightInputs = new Array();
	aHeightInputs = sFieldset.getElementsByTagName('input');
	for (nCount = 0; nCount < aHeightInputs.length; nCount++ ) {
		aHeightInputIds[nCount] = aHeightInputs[nCount].id;
	}
	sFieldset = document.getElementById('weight');
	var aWeightInputs = new Array();
	aWeightInputs = sFieldset.getElementsByTagName('input');
	for (nCount = 0; nCount < aWeightInputs.length; nCount++ ) {
		aWeightInputIds[nCount] = aWeightInputs[nCount].id;
	}
	
	aInputIds = aHeightInputIds.concat(aWeightInputIds);
}
// -----------------------
// FUNCTION: fAtLeastZero
// DESCRIPTION: A function that ensures the minimum value in any field is at least 0.
// ARGUMENTS: 1: Target element id
// -----------------------
function fAtLeastZero(sTargetId) {
	var nAtLeastZero = document.getElementById(sTargetId).value;
	if (nAtLeastZero == '') {
		document.getElementById(sTargetId).value = 0;
	}
	var sStartingZero = nAtLeastZero;
	if (sStartingZero.length > 1) {
		sStartingZero = nAtLeastZero.charAt(0);
		if (sStartingZero == "0") {
			nAtLeastZero = nAtLeastZero.substr(1, nAtLeastZero.length);
			document.getElementById(sTargetId).value = nAtLeastZero;
		}
	}
}
// -----------------------
// FUNCTION: fHeightImperialToMetric
// DESCRIPTION: A function that converts Imperial Heights to Metric.
// ARGUMENTS: None
// -----------------------
function fHeightImperialToMetric() {
	nFeetValue = document.getElementById(aInputIds[0]).value;
	nInchesValue = document.getElementById(aInputIds[1]).value;
	nInchesValue = parseInt(nInchesValue) + parseInt(nFeetValue * 12);
	var nCentimetreValue = Math.round(nInchesValue * 2.54);
	var nMetricValue = nCentimetreValue / 100;
	nMetricValue = fRoundToTwo(nMetricValue);
	aMetricValue = nMetricValue.split(".");
	document.getElementById(aInputIds[2]).value = aMetricValue[0];
	document.getElementById(aInputIds[3]).value = aMetricValue[1];
}

// -----------------------
// FUNCTION: fHeightMetricToImperial
// DESCRIPTION: A function that converts Metric Heights to Imperial.
// ARGUMENTS: None
// -----------------------
function fHeightMetricToImperial() {
	nMetresValue = document.getElementById(aInputIds[2]).value;
	nCentimetresValue = document.getElementById(aInputIds[3]).value; 
	nCentimetresValue = parseInt(nMetresValue * 100) + parseInt(nCentimetresValue);
	var nImperialValue = Math.round(nCentimetresValue / 2.54);
	nFeetValue = Math.floor(nImperialValue / 12);
	nInchesValue = (nImperialValue - (nFeetValue * 12));
	document.getElementById(aInputIds[0]).value = nFeetValue;
	document.getElementById(aInputIds[1]).value = nInchesValue;
}

// -----------------------
// FUNCTION: fWeightMetricToImperial
// DESCRIPTION: A function that converts Metric Weights to Imperial.
// ARGUMENTS: None
// -----------------------
function fWeightMetricToImperial() {
	var nKilosValue = document.getElementById(aInputIds[6]).value;
	var nMetricValue = Math.round(nKilosValue / 0.45359);
	var nStoneValue = Math.floor(nMetricValue / 14);
	var nPoundsValue = (nMetricValue - (nStoneValue * 14));
	document.getElementById(aInputIds[4]).value = nStoneValue;
	document.getElementById(aInputIds[5]).value = nPoundsValue;	
}

// -----------------------
// FUNCTION: fWeightImperialToMetric
// DESCRIPTION: A function that converts Imperial Weights to Metric.
// ARGUMENTS: None
// -----------------------
function fWeightImperialToMetric() {
	var nStoneValue = document.getElementById(aInputIds[4]).value;
	var nPoundsValue = document.getElementById(aInputIds[5]).value;
	var nImperialValue = (parseInt(nStoneValue * 14) + parseInt(nPoundsValue));
	var nKiloValue = Math.round(nImperialValue * 0.45359);
	document.getElementById(aInputIds[6]).value = nKiloValue;
}

// -----------------------
// FUNCTION: fRoundToTwo
// DESCRIPTION: A function that converts any number to decimal places.
// ARGUMENTS: None
// -----------------------
function fRoundToTwo(nNumber) {
  var nRounded = nNumber * 1000;
  nRounded = Math.round(nRounded /10) + "";
  while (nRounded.length < 3) {nRounded = "0" + nRounded};
  var nLength = nRounded.length;
  nRounded = nRounded.substring(0,nLength-2) + "." + nRounded.substring(nLength-2,nLength);
  return nRounded; 
} 

// ----------------------
// FUNCTION: fSelectText
// DESCRIPTION: A function that selects the contents of a text area
// ARGUMENTS: None
// ----------------------
function fSelectText() {
	if (window.event) {
		window.event.srcElement.select();
	} else {
		this.select();
		}
}

var nStrength = 0;
var aMessages = new Array("WEAK", "POOR", "FAIR", "GOOD", "STRONG");
var bHasNumber = false;
var bHasMixedCase = false;
var bHasSymbol = false;
var bHasEight = false;

// ----------------------
// FUNCTION: fCheckStrength
// DESCRIPTION: A function that checks the strenght of the entered password and updates the indicator
// ARGUMENTS: None
// ----------------------
function fCheckStrength() {
    if (document.getElementById('ctl00_PlaceHolderMain_MyChoices_YourAccount1_ChangePassword1_txtPassword')) {
        var sPasswordValue = document.getElementById('ctl00_PlaceHolderMain_MyChoices_YourAccount1_ChangePassword1_txtPassword').value;
    }
    if (document.getElementById('ctl00_PlaceHolderMain_Registration1_cuwChoices_CreateUserStepContainer_Password')) {
	    var sPasswordValue = document.getElementById('ctl00_PlaceHolderMain_Registration1_cuwChoices_CreateUserStepContainer_Password').value;
    }
    if (document.getElementById('ctl00_PlaceHolderMain_ResetPassword1_ResetPasswordWizard_Password')) {
        var sPasswordValue = document.getElementById('ctl00_PlaceHolderMain_ResetPassword1_ResetPasswordWizard_Password').value;
    }
	if (sPasswordValue.length > 7) {
		bHasEight = true;
	} else {
		bHasEight = false;
	}

	if (sPasswordValue.match(/\d+/)) {
		bHasNumber = true;
	} else {
		bHasNumber = false;
	}
	
	if (sPasswordValue.match(/[A-Z]/) && sPasswordValue.match(/[a-z]/)) {
		bHasMixedCase = true;
	} else {
		bHasMixedCase = false;
	}

	if (sPasswordValue.match(/[\W]/)) {
		bHasSymbol = true;
	} else {
		bHasSymbol = false;
	}

	nStrength = 0;
	if (bHasEight) {
		nStrength++;
		if (bHasNumber) {
		nStrength++;
		}
		if (bHasMixedCase) {
			nStrength++;
		}
		if (bHasSymbol) {
			nStrength++;
		}
	}
	var sListId = document.getElementById('password-strength-indicator');
	var aListElements = sListId.getElementsByTagName('li');
	for (nCount = 0; nCount < aListElements.length; nCount++ ) {	
		var sTheId = aListElements[nCount].id;
		if (nCount < nStrength) {
			document.getElementById(sTheId).className = 'good';
		} else {
			document.getElementById(sTheId).className = '';
		}
	}
	var oText = document.getElementById('password-strength-phrase').childNodes[0];
	document.getElementById('password-strength-phrase').removeChild(oText);
	oText = document.createTextNode(aMessages[nStrength]);
	document.getElementById('password-strength-phrase').appendChild(oText);
}

// ----------------------
// FUNCTION: fRenderPasswordStrength
// DESCRIPTION: A function that renders the passwrod strength indicator
// ARGUMENTS: None
// ----------------------
function fRenderPasswordStrength() {
	var oDiv;
	var oText;
	oDiv = document.createElement('div');
	oDiv.setAttribute('id', 'password-strength');
	document.getElementById('update-password').appendChild(oDiv);
	oDiv = document.createElement('p');
	oText = document.createTextNode('Strength');
	oDiv.appendChild(oText);
	document.getElementById('password-strength').appendChild(oDiv);
	oDiv = document.createElement('ul');
	oDiv.setAttribute('id', 'password-strength-indicator');
	document.getElementById('password-strength').appendChild(oDiv);
	for (nCount = 1; nCount <=4 ; nCount++ ) {
		oDiv = document.createElement('li');
		oDiv.setAttribute('id', 'strength-' + nCount);
		document.getElementById('password-strength-indicator').appendChild(oDiv);
	}
	oDiv = document.createElement('p');
	oDiv.setAttribute('id', 'password-strength-phrase');
	oText = document.createTextNode('WEAK');
	oDiv.appendChild(oText);
	document.getElementById('password-strength').appendChild(oDiv);
	
	if (document.getElementById('ctl00_PlaceHolderMain_Registration1_cuwChoices_CreateUserStepContainer_Password')) {
	    fAddEvent(document.getElementById('ctl00_PlaceHolderMain_Registration1_cuwChoices_CreateUserStepContainer_Password'), 'keyup', fCheckStrength);
	}
	if (document.getElementById('ctl00_PlaceHolderMain_MyChoices_YourAccount1_ChangePassword1_txtPassword')) {
	    fAddEvent(document.getElementById('ctl00_PlaceHolderMain_MyChoices_YourAccount1_ChangePassword1_txtPassword'), 'keyup', fCheckStrength);
	} 
	if (document.getElementById('ctl00_PlaceHolderMain_ResetPassword1_ResetPasswordWizard_Password')) {
	    fAddEvent(document.getElementById('ctl00_PlaceHolderMain_ResetPassword1_ResetPasswordWizard_Password'), 'keyup', fCheckStrength);
	}   
}

// ----------------------
// FUNCTION: fAddPersonalisationEvents
// DESCRIPTION: A function that adds personalisation events where appropriate
// ARGUMENTS: None
// ----------------------
function fAddPersonalisationEvents() {
	if (document.getElementById('height') && document.getElementById('weight')) {
		fAddBMIListeners('height');
		fAddBMIListeners('weight');
	}
	if (document.getElementById('rss-feed-link')) {
		fAddEvent(document.getElementById('rss-feed-link'), 'click', fSelectText);
		fAddEvent(document.getElementById('rss-feed-link'), 'keypress', fSelectText);
	}
	if (document.getElementById('update-password')) {
		fRenderPasswordStrength();
	}
}
function fInsertAfter(newElement,targetElement) 
{
	var parent = targetElement.parentNode;
	if(parent.lastchild == targetElement) 
	{
		parent.appendChild(newElement);
	} else 
	{
		parent.insertBefore(newElement, targetElement.nextSibling);
	}
}
// ----------------------
// FUNCTION: fRemoveElementIfExists
// DESCRIPTION: A function that removes provided element
// ARGUMENTS: element id
// ----------------------
function fRemoveElementIfExists(sElementId) {
	if (document.getElementById(sElementId)) {
		var oElement = document.getElementById(sElementId);
		oElement.parentNode.removeChild(oElement);
	}
}
// ----------------------
// FUNCTION: fHideElementsServices
// DESCRIPTION: A function that hides elements in a provided container
// ARGUMENTS: sContainerId,sElementType
// ----------------------
function fHideElementsServices(sContainerId, sElementType) {
	var sElementId;
	var sContainer = document.getElementById(sContainerId);
	var aElements = sContainer.getElementsByTagName(sElementType);
	var nArrayLength = aElements.length;
	for (nCount = 0; nCount < nArrayLength ; nCount++) {
		sElementId = aElements[nCount].id;
		fSwitchClass(sElementId, 'hidden');
	}
}
// ----------------------
// FUNCTION: fShowLabels
// DESCRIPTION: A function that shows elements in a provided container
// ARGUMENTS: sContainerId,sElementType
// ----------------------
function fShowLabels(sContainerId, sElementType){
	var sElementId;
	var sContainer = document.getElementById(sContainerId);
	var aElements = sContainer.getElementsByTagName(sElementType);
	var nArrayLength = aElements.length;
	for (nCount = 0; nCount < nArrayLength ; nCount++) {
		sElementId = aElements[nCount].id;
		var eElement = document.getElementById(sElementId);
		eElement.className = sElementId;
	}
}

function fRemoveAttributes(sContainerId, sElementType,sAttribute){
	var sElementId;
	var sContainer = document.getElementById(sContainerId);
	var aElements = sContainer.getElementsByTagName(sElementType);
	var nArrayLength = aElements.length;
	for (nCount = 0; nCount < nArrayLength ; nCount++) {
		sElementId = aElements[nCount].id;
		var eElement = document.getElementById(sElementId);
		eElement.removeAttribute(sAttribute);
	}
}
fAddEvent(window, 'load', fAddPersonalisationEvents);

function fHappyBobby() {
}
//-->

// ----------------------
// FUNCTION: toggle-content
// DESCRIPTION: JQuery function for opening times toggler in Rating and Comments
// ----------------------

;(function($) {

$(document).ready(function(){
	$(".toggle-times-first").addClass("first");
	$(".toggle-times").addClass("closed");
	
	$(".toggle-content").hide();

	$("h3.toggle-times").toggle(function(){
		$(this).addClass("active"); 
		}, function () {
		$(this).removeClass("active");
	});
	
	$(".toggle-content-first").show();

	$("h3.toggle-times-first").toggle(function(){
		$(this).addClass("active"); 
		}, function () {
		$(this).removeClass("active");
	});
	
	$("h3.toggle-times").click(function(){
		$(this).next(".toggle-content").slideToggle("slow,");
	});
	
	$("h3.toggle-times-first").click(function(){
		$(this).next(".toggle-content-first").slideToggle("slow,");
	});
	
});
})(jQuery);
//-->


// ---------------------------
// Check if string exists in url - for checking whether you're in a particular subsite
// ---------------------------
function isSiteInPath(sSubsite)
{
    try
    {
        var path = document.location.pathname.toLowerCase();
        if(path == null) {return false;}
        
        
        var idx = path.indexOf(sSubsite.toLowerCase());
        if (idx > 0)
            return true;
        return false;
        
    }
    catch(err)
    {
        return false;
    }

}