
// Some browsers/versions don't have this function, and we need it
if(!document.getElementsByClassName) {
	document.getElementsByClassName = function(className, tag, elm){
		var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
		var tag = tag || "*";
		var elm = elm || document;
		var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
		var returnElements = [];
		var current;
		var length = elements.length;
		for(var i=0; i<length; i++){
			current = elements[i];
			if(testClass.test(current.className)){
				returnElements.push(current);
			}
		}
		return returnElements;
	}
}

// date stuff used in cached pages
dayofweek= new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
dayofmonth= new Array("","1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th","13th","14th","15th","16th","17th","18th","19th","20th","21st","22nd","23rd","24th","25th","26th","27th","28th","29th","30th","31st");
months= new Array("January","February","March","April","May","June","July","August","September","October","November","December");

// Change image source function
function swapImg(img, src) {
	document.images[img].src = src;
	return true;
}

// returns todays date as a formated string
function theDate(){
	var mydate=new Date();
	var year=mydate.getYear();
	if (year < 1000) year+=1900;
	var day=mydate.getDay();
	var month=mydate.getMonth();
	var daym=mydate.getDate();
	todaysDate="  "+dayofweek[day]+" "+dayofmonth[daym]+" "+months[month]+" "+year;
	return todaysDate;
}

// Add current page to favourites (IE only)
function addToFavourites() {
	window.external.AddFavorite(window.location.href, document.title);
}

// Make current page your home page (IE only)
function makeHomePage() {
	document.body.style.behavior='url(#default#homepage)';
	document.body.setHomePage(window.location.href);
}

// Open popup window
function openWindow(strName, prefix, nArticleID, strURLParams, width, height, resize) {
  w=open(prefix + 'index.cfm?articleid=' + nArticleID + strURLParams, strName, 'width='+width+',height='+height+',alwaysLowered=no,alwaysRaised=yes,channelmode=no,dependent=no,directories=no,fullscreen=no,hotkeys=yes,location=no,menubar=no,resizable='+(resize ? 'yes' : 'no')+',scrollbars=yes,status=yes,titlebar=yes,toolbar=no,z-lock=no');
}

// Search box validation used for the main search page
function searchpagevalidate(ref) {
	if(ref.startArticleID.options[ref.startArticleID.selectedIndex].value!='') {
		if (ref.keyword.value != '')
			return true;
		else {
			alert('Need a keyword to search on!');
			return false;
		}
	}
	else {
		alert('Please select an area of the site to search');
		return false;
	}
}

// Expand vertical line for non-home template articles
// NOTE: I've had to use javascript to calculate the position of the selected nav link and resize
//       the line accordingly.  It's not ideal, but the clock was ticking and this worked.
function expandDottedLine() {
	ah=document.getElementById('penDummy').offsetTop; // get the position of the dummy DIV (aka, the header height)
	e=document.getElementById('penLev2Sel');
	if(e==null) { // Level 1
		e=document.getElementById('penLev1Sel'); 
		if(e!=null) {
			eh=(e.offsetTop-3);
			eh=(msie)?(eh+ah-2):(eh); // Adjust for IE
		}
		else eh=(ah-8);
	}
	else { // Level 2
		eh=(e.offsetTop-6);
		eh=(msie)?(eh+ah+e.offsetParent.offsetTop-3):(eh); // Adjust for IE
	}
	if((eh%2)) eh--; // If odd height, make even (so dots line up right)
	document.getElementById('penVLine').style.height=(eh+'px');
}

// Publications search box validation used for the search box in the Document Archive template
function pubsearchboxvalidate(ref) {
	if (ref.pubkeyword.value != '')
		return true;
	else {
		alert('Need a keyword to search on!');
		return false;
	}
}

// Search box validation used for both the search box and the main search page
function searchboxvalidate(ref) {
	if (ref.keyword.value != '')
		return true;
	else {
		alert('Need a keyword to search on!');
		return false;
	}
}

// Contact us form validation
function contactusvalidate(ref) {
	if(ref.utitle.options[ref.utitle.selectedIndex].value!='') {
		if (ref.ufirstname.value != '' && ref.usurname.value != '')
			if (ref.uemail.value != '' || ref.utelephone.value != '') {
				if (ref.utelephone.value == '' || (ref.utelephone.value != '' && ref.utelephone.value.search('^[0-9() +]+$') != -1)) {
					if (ref.uemail.value == '' || (ref.uemail.value != '' && ref.uemail.value.search('^[A-Za-z0-9_\\.-]+@([A-Za-z0-9]+([\\.\\-][A-Za-z0-9]+)*\\.)+[A-Za-z]{2,7}$') != -1)) {
						if(!ref.uhousenameno || (ref.uhousenameno && (ref.uhousenameno.value != '' && ref.uaddress1.value != '' && ref.utown.value != '' && ref.ucounty.value != '' && ref.upostcode.value != ''))) {
							if (ref.ucomments.value != '') {
								return true;
							}
							else {
								alert('Please provide some comments or information on your reason for contacting us');
								return false;
							}
						}
						else {
							alert('Please provide your address details');
							return false;
						}
					}
					else {
						alert('Your email address appears to be invalid');
						return false;
					}
				}
				else {
					alert('Telephone number must be numeric');
					return false;
				}
			}
			else {
				alert('Please specify your email address and/or telephone number');
				return false;
			}
		else {
			alert('Please fill in your name');
			return false;
		}
	}
	else {
		alert('Please specify your title');
		return false;
	}
}

// NEW Contact us form validation
function newcontactusvalidate(ref) {
	if(ref.salutation.options[ref.salutation.selectedIndex].value!='') {
		if (ref.firstname.value != '' || ref.surname.value != '') {
			if (ref.telno.value != '' || ref.email.value != '') {
				if (ref.telno.value == '' || (ref.telno.value != '' && ref.telno.value.search('^[0-9() +]+$') != -1)) {
					if (ref.email.value == '' || (ref.email.value != '' && ref.email.value.search('^[A-Za-z0-9_\\.-]+@([A-Za-z0-9]+([\\.\\-][A-Za-z0-9]+)*\\.)+[A-Za-z]{2,7}$') != -1)) {
						if(ref.businessarea.options[ref.businessarea.selectedIndex].value!='') {
							if(document.getElementById("subject" + ref.businessarea.options[ref.businessarea.selectedIndex].value).value!='') {
								if(ref.businessarea.options[ref.businessarea.selectedIndex].value=='0' || ref.businessarea.options[ref.businessarea.selectedIndex].value=='1') {
									if (ref.custref.value != '' || (ref.hname.value != '' && ref.postcode.value != '')) {
										if (ref.custref.value != '') {
											if (!isNaN(ref.custref.value)) {
												if (ref.comments.value != '') {
													return true;
												}
												else {
													alert('Please provide some comments or information on your reason for contacting us');
													return false;
												}
											} else {
												alert('Customer reference needs to be a 10 digit number');
												return false;
											}
										}
										else {
											if (ref.postcode.value == '' || (ref.postcode.value != '' && ref.postcode.value.search("(^([A-Za-z]{1,2}[0-9]{1,2}|[A-Za-z]{1,2}[0-9][A-Za-z]|[A-Za-z]{3,3}) ?[0-9][A-Za-z]{2,2}$)|(^BFPO ?[0-9]{3,3}$)") != -1)) {
												if (ref.comments.value != '') {
													return true;
												}
												else {
													alert('Please provide some comments or information on your reason for contacting us');
													return false;
												}
											}
											else {
												alert('Please provide a valid postcode');
												return false;
											}
										}
									}
									else {
										alert('Please provide either a customer reference or a house name/no and a postcode');
										return false;
									}
									
								}
								else {
									if (ref.comments.value != '') {
										return true;
									}
									else {
										alert('Please provide some comments or information on your reason for contacting us');
										return false;
									}
								}
							}
							else {
								alert('Please select a subject');
								return false;
							}
						}
						else {
							alert('Please select a business area');
							return false;
						}
					}
					else {
						alert('Your email address appears to be invalid');
						return false;
					}
				}
				else {
					alert('Telephone number must be numeric');
					return false;
				}
			}
			else {
				alert('Please specify your email address and/or telephone number');
				return false;
			}
		} 
		else {
			alert('Please fill in your name');
			return false;
		}
	}
	else {
		alert('Please specify your title');
		return false;
	}
}

// WCVALIDATE()
// Water Conservation form validation
function wcValidate(ref,pre) {
	// Arrays of required fields (and error messages if not completed), along with regular expression testing for fields
	rqFields = new Array('salutation','initials','surname','company','type','hrsday','daysyr','occday','toilets','address1','town','postcode','telno');
	rqTexts = new Array('Please enter your title','Please enter your initials','Please state your surname','Please state your company name','Please select a business type','Please enter your business hours per day','Please enter your business days per year','Please enter your average occupancy per day','Please specify the total number of toilets','Please enter your address','Please enter your town','Please specify your postcode','Please specify your telephone number');
	rqRegExp = new Array('(^([A-Za-z\.]{1,4})$)','(^([A-Za-z\.]{1,4})$)','','','','(^([1-9]|1[0-9]?|2[0-4])$)','(^([1-9][0-9]?|[1-2][0-9][0-9]|3[0-5][0-9]|36[0-6])$)','(^([1-9][0-9]?[0-9]?[0-9]?)$)','(^([1-9][0-9]?)$)','','','(^([A-Za-z]{1,2}[0-9]{1,2}|[A-Za-z]{1,2}[0-9][A-Za-z]|[A-Za-z]{3,3}) ?[0-9][A-Za-z]{2,2}$)|(^BFPO ?[0-9]{3,3}$)','(^[0-9A-Za-z() +:]+$)');
	rqRegExpErr = new Array('Title should only contain letters or a full stop','Initials should only contain letters or a full stop','','','','Business hours per day must be between 1 and 24','Business days per year must be between 1 and 366','Average occupancy/day should be numeric and non-zero','Number of toilets should be numeric and non-zero','','','Please provide a valid UK postcode','Please enter a valid telephone number');
	// Form field prefix
	if(typeof pre == 'undefined')
		var pre = '';
	// Check customer ref
	var rqOk = false;
	if(ref[pre + 'customerref'].value == '' || (ref[pre + 'customerref'].value != '' && !isNaN(ref[pre + 'customerref'].value))) {
		// Check salutation
		if((typeof ref[pre + 'salutation'].options != 'undefined' && ref[pre + 'salutation'].options[ref[pre + 'salutation'].selectedIndex].value != '') || (ref[pre + 'salutation'].value != '')) {
			rqOk = true;
			// Check all required fields
			for(i=0; i<rqFields.length; i++) {
				if(typeof ref[pre + rqFields[i]] != 'undefined') {
					var fval = (ref[pre + rqFields[i]].localName == 'select' ? ref[pre + rqFields[i]].options[ref[pre + rqFields[i]].selectedIndex].value : ref[pre + rqFields[i]].value);
					if(fval == '') {
						// Field has no value, throw error
						alert(rqTexts[i]);
						rqOk = false;
						break;
					} else {
						// Reqular expression match on required field if necessary
						if(rqRegExp[i] != '') {
							if(fval.search(rqRegExp[i]) == -1) {
								// Field doesn't match, throw error
								alert(rqRegExpErr[i]);
								rqOk = false;
								break;
							}
						}
					}
				}
			}
			// Validate the field values
			if(rqOk) {
				rqOk = false;
				if(isNaN(ref.town.value)) {
					if((typeof ref[pre + 'county'].options != 'undefined' && ref[pre + 'county'].options[ref[pre + 'county'].selectedIndex].value != '') || (ref[pre + 'county'].value != '')) {
						if(ref[pre + 'email'].value != '' && isValidEmail(ref[pre + 'email'].value)) {
							if(pre == 'bus' || (pre == 'dom' && (ref.q1.options[ref.q1.selectedIndex].value == 'yes' || (ref.q1.options[ref.q1.selectedIndex].value == 'no' && ref.q2.options[ref.q2.selectedIndex].value != '')))) {
								if(pre == 'dom' && ref.q1.options[ref.q1.selectedIndex].value == 'no' && !ref.q3.checked && typeof q3ErrTxt != 'undefined')
									alert(q3ErrTxt); // Var set in template/conservation/dsp_formcontents.cfm
								else {
									if((ref[pre + 'hippo'].value != '0' && !isNaN(ref[pre + 'hippo'].value)) || (ref[pre + 'hog'].value != '0' && !isNaN(ref[ref + 'hog'].value)) || (ref[pre + 'conservationleaflet'].value != '0' && !isNaN(ref[pre + 'conservationleaflet'].value))) {
										if(typeof ref['tandc'] == 'undefined' || (typeof ref['tandc'] != 'undefined' && ref['tandc'].checked))
											return confirm('Submit order form?');
										else
											alert('You must indicate that you agree to the terms and conditions for the order to proceed');
									} else
										alert('You must select at least one product to order');
								}
							} else
								alert('Please complete the questions section');
						} else
							alert('Please specify a valid email address');
					} else
						alert('Please select a county');
				} else
					alert('Town should not contain numbers');
			}
			return rqOk;
		} else {
			alert('Please enter your title');
		}
		return rqOk;
	} else {
		if(ref[pre + 'customerref'].value != '' && isNaN(ref[pre + 'customerref'].value)) {
			alert('Please specify a valid customer reference number');
			return false;
		}
	}
}

// WCSELECT()
// Water Conservation form selection
function wcSelect(pre) {
	if(openTip != '') {
		// Close any open tool tip
		document.getElementById('infotip' + openTip).style.display = 'none';
		openTip = '';
	}
	document.getElementById('wcdomestic').style.display = (pre == 'dom' ? 'block' : 'none');
	document.getElementById('wcbusiness').style.display = (pre == 'bus' ? 'block' : 'none');
	return (pre == 'dom' ? wcAnswerQ(pre) : false);
}

// WCANSWERQ()
// Water Conservation form, called when questions are answered
function wcAnswerQ(pre) {
	var q1 = document.getElementById('q1');
	var q2 = document.getElementById('q2');
	var q2num = document.getElementById('q2num');
	var q2lab = document.getElementById('q2lab');
	var q2ii = document.getElementById('infoiconq2');
	var q3 = document.getElementById('q3');
	var q3lab = document.getElementById('q3lab');
	// Enable products section
	var q1val = q1.options[q1.selectedIndex].value;
	wcEnableProducts(pre, (q1val == 'yes' || (q1val == 'no' && q2.options[q2.selectedIndex].value != '' && q3.checked)));
	// Enable Q2/Q3 if Q1 is "no"
	var qEn = (q1val == 'no');
	q2.className = (qEn ? 'wcenabled' : 'wcdisabled');
	q2.disabled = !qEn;
	q2num.className = q2.className;
	q2num.disabled = !qEn;
	q2lab.className = q2.className;
	q2lab.disabled = !qEn;
	// Q3
	q3.className = q2.className;
	q3.disabled = !qEn;
	q3lab.className = q2.className;
	q3lab.disabled = !qEn;
	// Q2 Info Icon
	if(q2ii) {
		q2ii.className = q2.className;
		q2ii.children[0].className = q2.className;
		q2ii.disabled = !qEn;
		q2ii.children[0].disabled = !qEn;
	}
	return false;
}

// WCENABLEPRODUCTS()
// Water Conservation form, enable/disable product details
function wcEnableProducts(pre, en) {
	// Disable dropdowns
	var enArr = new Array('hippo','hog','conservationleaflet');
	for(i = 0; i < enArr.length; i++) {
		var el = document.getElementById(pre + enArr[i]);
		el.disabled = !en;
		el.className = (en ? 'wcenabled' : 'wcdisabled');
		// Label
		el = document.getElementById(pre + enArr[i] + 'text');
		el.disabled = !en;
		el.className = (en ? 'wcenabled' : 'wcdisabled');
		// Info icons
		el = document.getElementById('infoicon' + pre + enArr[i]);
		if(el) {
			el.disabled = !en;
			el.className = (en ? 'wcenabled' : 'wcdisabled');
			el.firstChild.disabled = !en;
			el.firstChild.className = (en ? 'wcenabled' : 'wcdisabled');
		}
	}
	return false;
}

// EMAILFRIENDVALIDATE()
// Email a Friend form validation
function emailfriendvalidate(ref) {
	var frmValid = false;
	if (ref.emafSendName.value != '' || ref.emafSendEmail.value != '') {
		if (ref.emafRecName.value != '' || ref.emafRecEmail.value != '') {
			if (isValidEmail(ref.emafSendEmail.value)) {
				if (isValidEmail(ref.emafRecEmail.value)) {
					frmValid = true;
				}
				else
					alert('Please ensure that your friend\'s email address is valid');
			}
			else
				alert('Please ensure that your email address is valid');
		}
		else
			alert('Please give your friend\'s name and email address');
	}
	else
		alert('Please give your name and email address');
	return(frmValid);
}

// ISVALIDEMAIL()
// Check email address is valid
function isValidEmail(em) {
	var allvalid = true;
	if (em.length > 0) {
		if (window.RegExp) {
			var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
			var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$";
			var reg1 = new RegExp(reg1str);
			var reg2 = new RegExp(reg2str);
			if (!reg1.test(em) && reg2.test(em)) var allvalid = true; else var allvalid = false;
		}
		else {
			var emailok = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz���������������������������������������������������������������������0123456789-@.'#�$()-_\t\r\n\f";
			if (!validlength(em, 5)) allvalid = false;
			if (em.indexOf ('@') < 1) allvalid = false;
			if (em.lastIndexOf ('.') < (em.indexOf ('@') + 2)) allvalid = false;
			if (em.lastIndexOf ('.') > (em.length - 3)) allvalid = false;
			for (i = 0; i < em.length; i++) {
				ch = em.charAt(i);
				for (j = 0; j < emailok.length; j++) {
					if (ch == emailok.charAt(j)) break;
					if (j == emailok.length) {
						allvalid = false;
						break;
					}
				}
			}
		}
		if (!allvalid) return(false); else return(true);
	}
}

// FORMATNUM()
function formatNum(value){
	value = "" + value <!--- convert value to string --->
	precision = 2; <!--- Decimal places --->
	width = 9; <!--- Formatted width in characters --->
	padding = "";
	for(p=0;p<width;p++) padding+=" "; <!--- Make a padding string --->      
	var whole = "" + Math.round(value * Math.pow(10, precision));
	var decPoint = whole.length - precision;
	if(decPoint != 0){
		result = whole.substring(0, decPoint);
		result += ".";
		result += whole.substring(decPoint, whole.length);
	}else{
		result = whole;
	}
	result = padding+result;<!--- Left pad numbers so they line up --->
	result = result.substring(result.length-width, result.length);		   
	return result;
}

// METERREADVALIDATE()
// Meter Reading form validation
function meterreadvalidate(ref) {
	// Arrays of required fields (and error messages if not completed), along with regular expression testing for fields
	rqFields = new Array("customerref","firstname","surname","telno","email","reading","readingdate");
	rqTexts = new Array("Please enter your customer reference number","Please enter your first name","Please enter your surname","Please enter your telephone number","Please enter an email address","Please enter your meter reading", "Please enter the date of your meter reading");
	rqRegExp = new Array("(^[0-9]{10}$)","(^[A-Za-z0-9 -]+$)","(^[A-Za-z0-9 -]+$)","(^[0-9() +]+$)","(^[A-Za-z0-9_\\.-]+@([A-Za-z0-9]+([\\.\\-][A-Za-z0-9]+)*\\.)+[A-Za-z]{2,7}$)","(^[0-9]{1,7}$)", "(^(((((0[1-9])|(1\\d)|(2[0-8]))\/((0[1-9])|(1[0-2])))|((31\/((0[13578])|(1[02])))|((29|30)\/((0[1,3-9])|(1[0-2])))))\/((20[0-9][0-9])|(19[0-9][0-9])))|((29\/02\/(19|20)(([02468][048])|([13579][26]))))$)");
	rqRegExpErr = new Array("Your customer reference number should contain 10 digits","Please enter your first name","Please enter your surname","Please enter a valid phone number","Please enter a valid email address","Your meter reading should consist of up to 7 digits", "Please enter a valid date in the format dd/mm/yyyy");
	// Check all required fields
	rqOk = true;
	for(i=0; i<rqFields.length; i++) {
		if(ref[rqFields[i]].value == '') {
			// Field has no value, throw error
			alert(rqTexts[i]);
			rqOk = false;
			break;
		} else {
			// Reqular expression match on required field if necessary
			if(rqRegExp[i] != '') {
				if(ref[rqFields[i]].value.search(rqRegExp[i]) == -1) {
					// Field doesn't match, throw error
					alert(rqRegExpErr[i]);
					rqOk = false;
					break;
				} else {
					// Validate customer reference number (using check digit)
					if(rqFields[i] == 'customerref' && ref.customerref.value.substring(0,8) != validateRef(ref.customerref.value)) {
						alert('Please specify a valid customer reference number');
						rqOk = false;
						break;
					}
				}
			}
		}
	}
	return rqOk;
}

// VALIDATEREF()
// Return a customer reference with check digit (based on SWW's own code)
function validateRef(ref) {
	// Set a few vars
	var conV3 = "12345678900";
	var weightList = new Array("1","2","5","3","6","4","8","7","10","9");
	var dblTotal = 0;
	// Chop string at 7 characters and reverse
	var tmpRef = ref.substring(0,7).split("").reverse().join("");
	var intWeight = 0;
	//	Calculate total weighting
	for(var intCt = 0; intCt < tmpRef.length; intCt++) {
		intWeight = weightList[intCt];
		dblTotal = dblTotal + (tmpRef.substring(intCt, intCt+1) * intWeight);
	}
	// Calculate check digit position in V3
	var dblV1 = parseInt(dblTotal / 11);
	var dblV2 = parseInt(11 - (dblTotal - (dblV1 * 11)));
	// Return reference with check digit from V3
	return (tmpRef.split("").reverse().join("") + conV3.substring(dblV2-1, dblV2));
}

// CHARCT()
// Limit an input field to a given number of characters
function charCt(fld,lim,ctfld) {
	if(fld.type && (fld.type == "textarea" || fld.type == 'text')) {
		// Set default limit if not supplied
		limit = (lim) ? lim : 500;
		// Get real field length (where return = 2 chars as it'll be converted to ". ")
		var realLen = fld.value.length;
		for(i=0; i<fld.value.length; i++)if(fld.value.toString().charCodeAt(i) == 10) realLen++;
		// Restrict characters
		if(realLen > limit)
			fld.value = fld.value.substring(0, limit);
		else
			// Set count field value (if present)
			if(ctfld)
				ctfld.value = limit - realLen;
	}
}

// DISPLAYBLOCK()
// Sets the display and visibility status of an element
function displayBlock(b,a) {
	b.style.display = (a == 1) ? 'block' : 'none';
	b.style.visibility = (a == 1) ? 'visible' : 'hidden';
}

// SHOWHIDE()
// Show/hide or toggle a specified block
function showHide(blk,act) {
	var sBlk = document.getElementById(blk);
	if(sBlk) {
		// Display/hide the block
		if(sBlk.style.display == 'none' || act == 1)
			displayBlock(sBlk, 1);
		else if(sBlk.style.display != 'none' || act == 0)
			displayBlock(sBlk, 0);
	}
	return false;
}

// SHARELINKS() - Show/hide the Share links block
function shareLinks(act) {
	return showHide('sharelinks',act);
}

// PERSONALISEMENU() - Show/hide the Personalise Home menu
function personaliseMenu(act) {
	return showHide('personalisemenu',act);
}

// PERSONALISESWITCH() - Respond to a checkbox click in the personalise menu
function personaliseSwitch(id) {
	iCM.PersonalHomePage.Toggle('-'+id+'0');
}

// SHOWNEWSIMG()
// Rollover news image
function showNewsImg(img) {
	if(newsImageItemShow) {
		for(var i = 1; i <= newsImageItemShow; i++) {
			var id = newsImageID + i;
			var el = document.getElementById(id);
			// Display the specified image, hide all others
			if(el && i == img)
				displayBlock(el, 1);
			else if(el)
				displayBlock(el, 0);
		}
	}
	return false;
}

// SHOWNEWS()
// Show/hide news items
function showNews(v) {
	newsItemEnd = (newsItemEnd + v);
	newsItemEnd = (newsItemEnd < newsItemStart) ? newsItemStart : (newsItemEnd > newsItemMax) ? newsItemMax : newsItemEnd;
	for(var i = newsItemStart; i <= newsItemMax; i++) {
		var id = newsItemID + i;
		var el = document.getElementById(id);
		// Display all news items up to the specified one, hide all after it
		if(el && i <= newsItemEnd)
			displayBlock(el, 1);
		else if(el)
			displayBlock(el, 0);
	}
	return false;
}

// SHOWACCORDTAB()
// Show/hide accordion tabs
function showAccordTab(t,b) {
	// Set a few vars for display
	var divArr = new Array('left', 'right', 'back');
	var swapClass = (accordionTabList[accordionTabList.length-1] == t) ? 'middle' : 'bottom';
	// Loop through tab elements
	for(i = 0; i < accordionTabList.length; i++) {
		var el = document.getElementById('accordtab' + accordionTabList[i]);
		var eli = document.getElementById('accordimg' + accordionTabList[i]);
		if(el && accordionTabList[i] == t) {
			// Display the specified tab, change the arrow
			displayBlock(el, 1);
			eli.src = './images/common/part/arrow_down'+b+'.gif';
		} else if(el) {
			// Hide other tabs, reset the arrow
			displayBlock(el, 0);
			eli.src = './images/common/part/arrow_left'+b+'.gif';
		}
	}
	// If showing the bottom tab, we need to change classes for the curve and heading
	for(i = 0; i < divArr.length; i++) {
		elSW = document.getElementById('swap' + divArr[i]);
		if(elSW)
			elSW.className = 'part' + swapClass + divArr[i];
		for(j = 0; j < accordionTabList.length; j++) {
			elSH = document.getElementById('show' + divArr[i] + accordionTabList[j]);
			if(elSH)
				elSH.className = 'accordion' + ((accordionTabList[accordionTabList.length-1] == t && accordionTabList[j] == t) ? 'bot' : '') + 'select' + divArr[i];
		}
	}
	return false;
}

// SHOWGALLERYIMG()
// Show/hide gallery images
// (requires galleryArticles array of IDs to be defined)
function showGalleryImg(img, rel) {
	// "Relative" select, ie. go to previous/next
	if(typeof rel != "undefined" && rel) {
		var ptr = (galSel + img);
		ptr = (ptr < 0) ? (galleryArticles.length - 1) : (ptr >= galleryArticles.length ? 0 : ptr);
		img = galleryArticles[ptr];
		galSel = ptr;
	}
	// Loop through big images to turn off all but the one we want
	for(i = 0; i < galleryArticles.length; i++) {
		var shHd = (galleryArticles[i] == img) ? 1 : 0;
		var hvCls = (galleryArticles[i] == img) ? "hover" : "";
		// Get the main image, overlay <img> and opacity <span>
		var el = document.getElementById('galBigImg' + galleryArticles[i]);
		var elOv = document.getElementById('galOverlay' + galleryArticles[i]);
		var elOp = document.getElementById('galOpacity' + galleryArticles[i]);
		// Show/hide the image, and set the class on overlay and opacity
		if(el) displayBlock(el, shHd);
		if(elOv) elOv.className = 'overlay' + hvCls;
		if(elOp) elOp.className = 'opacity' + hvCls;
	}
	return false;
}

// SHOWGALLERYBUTTONS()
// Show/hide the gallery next/previous buttons
var lastSel = -1;
function showGalleryButtons(act, ovr, img) {
	// Get button elements and show them
	var p = document.getElementById("galleryPrevious");
	var n = document.getElementById("galleryNext");
	if(p)
		displayBlock(p, act);
	if(n)
		displayBlock(n, act);
	// Set button over image
	if(typeof img != "undefined") {
		var b = document.getElementById(img);
		if(b)
			b.src = b.src.replace((act == 0 ? "_on." : "_off."), (act == 0 ? "_off." : "_on."));
	}
	// Respond to action
	if(act) {
		if(typeof ovr != "undefined" && ovr)
			// Mouse moved from gallery image to arrow, so set selected to what it was before
			galSel = lastSel;
		else
			// Store currently selected image
			lastSel = galSel;
	} else
		galSel = -1;
}

// ROTATEGALLERYIMG()
// Loop through the gallery images at a timed interval
// (requires galleryArticles array of IDs to be defined)
function rotateGalleryImg(img,int) {
	if(galSel == -1)
		// Change image if not hovering on it
		showGalleryImg(galleryArticles[img++]);
	else
		img = (galSel + 1);
	setTimeout(("rotateGalleryImg(" + (img == galleryArticles.length ? 0 : img) + "," + int + ")"), int);
}

// RESIZEIFRAME()
// Dynamically resize the height of IFRAMEs to their content
function resizeIFrame() {
	var e = document.getElementsByTagName("iframe");
	if(e.length) {
		// Loop through iframe elements
		for(var i = 0; i < e.length; i++) {
			var con = e[i].contentWindow || e[i].contentDocument;
			// Only proceed if it's a part
			if(e[i].className == 'partiframe') {
				try {
					if(con.document.body) {
						var ht = con.document.body.scrollHeight;
						// Set height
						if(ht != 0 && e[i].height != ht)
							e[i].height = ht;
					}
				} catch(e) {}
			}
		}
	}
	// Call again on timeout
	setTimeout("resizeIFrame();", 500);		
}

// GETAJAXDATE
// Return a date string used for Ajax requests to prevent caching
function getAjaxDate() {
	var td = new Date();
	return(td.getTime());
}

// GETXMLHTTP
// Create an instance of XMLHttpRequest 
function getXMLHttp() {
	var xmlHttp;
	try {
		xmlHttp = new XMLHttpRequest();
	} catch(e) {
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				return false;
			}
		}
	}
	return xmlHttp;
}

// REWRITEWIDGETLINKS()
// Ensure all links in the widget have target=_top
// Added functionality to include GA tracking code to links
function rewriteWidgetLinks() {
	var e = new Array();
	var divs = document.getElementsByTagName('div');
	var cn = new RegExp("(^|\\s)rightnowinline(\\s|$)");
	for (d = 0, c = 0; d < divs.length; d++) {
		if (cn.test(divs[d].className)) {
			e[c] = divs[d];
			c++;
		}
	}
	for (w=0; w<e.length; w++){
		rnks = e[w];
		if(rnks != null && rnks.innerHTML != null && rnks.innerHTML.length != 0) {
			var alk = rnks.getElementsByTagName('a');
			if(alk.length) {
				for (var i = 0; i < alk.length; i++) {
					alk[i].target = "_top";
					var destination = alk[i].href;
					alk[i].setAttribute('onclick', 'recordOutboundLink(this, \'Outbound Links\', \'' + destination + '\');return false;');
				}
			}
		}
	}
	var rhrnks = document.getElementById('rnksWidget');
	if(rhrnks != null && rhrnks.innerHTML != null && rhrnks.innerHTML.length != 0) {
		var rhalk = rhrnks.getElementsByTagName('a');
		if(rhalk.length) {
			for (var j = 0; j < rhalk.length; j++) {
				rhalk[j].target = "_top";
				var destination = rhalk[j].href;
				rhalk[j].setAttribute('onclick', 'recordOutboundLink(this, \'Outbound Links\', \'' + destination + '\');return false;');
			}
		}
	}
}

// SHOWINFOTIP()
// Display a specified info link tooltip
var openTip = '';
var onTip = false;
var onTipTimer = null;
function showInfoTip(ev, id, el) {
	if(typeof el == 'undefined' || !document.getElementById('infoicon' + el).disabled) {
		// Close open tip
		if(openTip != '' && openTip != id)
			document.getElementById('infotip' + openTip).style.display = 'none';
		// Get window width and height
		var ww = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth);
		var wh = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight);
		// Get tip to open 
		var tt = document.getElementById('infotip' + id);
		if (tt.style.display == 'block') {
			// Already open, hide it
			tt.style.display = 'none';
		} else {
			// Position relative to mouse
			lv = mouseX(ev) - (tt.offsetWidth / 4);
			tv = mouseY(ev) + 12;
			lv = (lv < 2 ? 2 : ((lv + tt.offsetWidth) > ww ? (lv - (tt.offsetWidth / 2)) : lv));
			tt.style.left = (lv + 'px');
			tt.style.top = (tv + 'px');
			// Show it
			tt.style.display = 'block';
			openTip = id;
			// Scroll to it (if it's off the page)
			var scrOfX = ww + (window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft);
			var scrOfY = wh + (window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop);
			var ttR = ((tt.offsetLeft + tt.offsetWidth) + 8);
			var ttB = ((tt.offsetTop + tt.offsetHeight) + 8);
			if(ttR > scrOfX || ttB > scrOfY) {
				ttR = (ttR - ww);
				ttB = (ttB - wh);
				window.scrollTo((ttR > 0 ? ttR : 0), (ttB > 0 ? ttB : 0));			
			}
		}
	}
	return false;
}
// Get mouse X-coord
function mouseX(evt) {
	return evt.clientX ? evt.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) : evt.pageX;
}
// Get mouse Y-coord
function mouseY(evt) {
	return evt.clientY ? evt.clientY + (document.documentElement.scrollTop || document.body.scrollTop) : evt.pageY;
}
// Mouse on tip status
function mouseTip(s) {
	clearTimeout(onTipTimer);
	if(!s) {
		if(onTip) {
			// Wait 1 second and check again
			onTipTimer = setTimeout('mouseTip(false);', 1000);
		} else {
			// Mouse is off the icon and tip; close the tip
			if(openTip != '')
				document.getElementById('infotip' + openTip).style.display = 'none';
		}
	}
	onTip = s;
	return false;
}

// SHOWINFOICONS()
// Make the info icon links visible
function showInfoIcons() {
	var elArr = document.getElementsByClassName('infoicon');
	for (var i = 0; i < elArr.length; i++) {
		elArr[i].style.display = 'inline';
		// Kill the alt-text tooltip in IE
		if(elArr[i].children[0] && elArr[i].children[0].children[0])
			elArr[i].children[0].children[0].alt = '';
	}
}

// EXTERNAL LINKS
// Add tracking to all links marked as external in the body content
function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i < anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href")) {
			if(anchor.getAttribute("rel") == "external") {
				var destination = anchor.href;
				anchor.setAttribute('onclick', 'recordOutboundLink(this, \'Outbound Link\', \'' + destination + '\');return false;');
			}
			if(anchor.getAttribute("rel") == "top") {
				anchor.target="_top";
			}
		}
	}
}

// ONLINEEVENTSSEARCH
// Refresh iframe with search
function onlineEventsSearch(uuid) {
	var srch = document.getElementById('search_' + uuid);
	var stab = document.getElementById('showtabs_' + uuid);
	// Only proceed if search is present, and has a non-default value
	if(srch) {
		if(srch.value != '' && srch.value != 'Enter postcode or location') {
			var safeSrchVal = srch.value.replace(/<\S[^><]*>/g, '');
			// Get show tabs selections (if applicable)
			var stabstr = '';
			if(stab && stab.value != '') {
				var stabparts = stab.value.split(',');
				var stabselct = 0;
				for(var i=0; i< stabparts.length; i++) {
					var c = document.getElementById('showtabs_' + uuid + '_' + stabparts[i]);
					if(c)
						stabstr = (stabstr + (stabstr != '' ? '&' : '') + 'tab' + stabparts[i] + (c.checked ? "=true" : "=false" ));
					stabselct += (c.checked ? 1 : 0);
				}
			}
			// If show tabs selections are present, but none checked, tell user
			if(stab && stab.value != '' && stabselct == '')
				alert('Please select at least one checkbox');
			else {
				// Start breaking down the iframe's query string
				var ifrm = document.getElementById('oe_' + uuid);
				if(ifrm) {
					// Split out into parts
					var isrcparts = ifrm.src.split('?');
					if(isrcparts.length >= 2) {
						// Loop through each parameter
						var params = isrcparts[1].split(/[&;]/g);
						for(var i=params.length-1; i >= 0; i--) {
							// If SEARCH, replace it
							if(params[i].toLowerCase().substring(0,7) == 'search=')
								params[i] = ('search=' + encodeURIComponent(safeSrchVal));
							// If TABSxxx, remove it (as we're specifying these separately)
							if(stab && stabstr != '' && params[i].toLowerCase().substring(0,3) == 'tab')
								params.splice(i, 1);
						}
						// Replace iframe src
						var newisrc = (isrcparts[0] + '?' + stabstr + '&' + params.join('&'));
						ifrm.src = newisrc;
					}
				}
			}
		} else
			alert('Please enter a postcode or location');
	}
	return false;
}

// SHOWJS()
// Display any elements that depend on javascript
function showJS() {
	var shEl = document.getElementsByClassName('js');
	for(var i=0; i < shEl.length; i++) { 
		shEl[i].style.display = (shEl[i].localName == 'tr' ? 'table-row' : 'block');
	}
}

// NAVIGATION SUB-MENUS
// Based on Simple Drop-Down Menu v2.0 by javascript-array.com
// Variables
var nvm_timeout = 500;
var nvm_closetimer = 0;
var nvm_menuitem = 0;

// Open menu
function nvmopen(id) {	
	nvmcancelclosetime();
	// Close open item
	if(nvm_menuitem)
		nvm_menuitem.style.visibility = 'hidden';
	// Show selected item
	nvm_menuitem = document.getElementById(id);
	var pos = nvmgetpos(document.getElementById(id + 'par'));
	nvm_menuitem.style.left = pos.x + "px";
	nvm_menuitem.style.top = pos.y + "px";
	nvm_menuitem.style.visibility = 'visible';
}

// Close menu
function nvmclose() {
	if(nvm_menuitem)
		nvm_menuitem.style.visibility = 'hidden';
}

// Close timer
function nvmclosetime() {
	nvm_closetimer = window.setTimeout(nvmclose, nvm_timeout);
}

// Cancel close timer
function nvmcancelclosetime() {
	if(nvm_closetimer) {
		window.clearTimeout(nvm_closetimer);
		nvm_closetimer = null;
	}
}

// Get position of parent link
function nvmgetpos(el) {
	var pos = new Object();
	pos.x = 0;
	pos.y = 0;
	if (el.getBoundingClientRect) {
		var viewportElement = document.documentElement;  
		var box = el.getBoundingClientRect();
		var scrollLeft = (typeof viewportElement.scrollLeft == 'undefined' ? 0 : viewportElement.scrollLeft);
	    var scrollBottom = (typeof viewportElement.scrollBottom == 'undefined' ? 0 : viewportElement.scrollBottom);
	    pos.x = box.left + scrollLeft;
	    pos.y = box.bottom + scrollBottom;
	}
	return pos;
}

// Close layer when click-out
document.onclick = nvmclose;

// FEATURELISTGROUP
// Ensure user selected a grouping
function featureListGroup() {
	var flg = document.getElementById('featlistgroupby');
	return (flg.options[flg.selectedIndex].value != -1 ? true : false);
}
