// 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;
	}
}





// Water Conservation form validation
function waterconvalidate(ref) {
	// Arrays of required fields (and error messages if not completed), along with regular expression testing for fields
	rqFields = new Array("initials","surname","address1","town","county","postcode");
	rqTexts = new Array("Please enter your initials","Please state your surname", "Please enter your address", "Please enter your town", "Please enter your county", "Please specify your postcode");
	rqRegExp = new Array("(^([A-Za-z]{1,3})$)","(^([A-Za-z\-]{1,})$)","","","","(^([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}$)");
	rqRegExpErr = new Array("Initials should only contain letters","Surname should only contain letters (or hyphens)","","","","Please provide a valid UK postcode");
	// Check salutation
	if(ref.salutation.options[ref.salutation.selectedIndex].value!='') {
		rqOk = true;
		// Check all required fields
		for(i=0; i<rqFields.length; i++) {
			if(eval('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(eval("ref."+rqFields[i]+".value.search('"+rqRegExp[i]+"')") ==-1) {
						// Field doesn't match, throw error
						alert(rqRegExpErr[i]);
						rqOk = false;
						break;
					}
				}
			}
		}
		// Validate the field values
		if(rqOk) {
			if(isNaN(ref.town.value) && isNaN(ref.county.value)) {
				if((ref.hippo.value != '' && !isNaN(ref.hippo.value)) || (ref.hog.value != '' && !isNaN(ref.hog.value)) || (ref.conservationleaflet.value != '' && !isNaN(ref.conservationleaflet.value))) {
					// If hippo or hog values exceed 10, telephone number is required
					phoneReq = (ref.hippo.value > 10 || ref.hog.value > 10) ? true : false;
					if(phoneReq && ref.telno.value == '') {
						alert("You must state your phone number when requesting more than 10 of Hippo or Hog");
						return false;
					}
					else {
						if(ref.telno.value != '' && ref.telno.value.search('(^[0-9A-Za-z() +:]+$)') == -1) {
							alert("Please enter a valid telephone number");
							return false;
						}
						else {
							return confirm('Submit order form?');
						}
					}
				}
				else {
					alert("You must specify a numeric quantity for at least one of Hippo, Hog, or Conservation Leaflet");
					return false;
				}
			}
			else {
				alert("Town and county should not contain numbers");
				return false;
			}
		}
		else
			return false;
	}
	else {
		alert("Please specify your title");
		return false;
	}
}

// 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);
}

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);
	}
}

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
function showGalleryImg(img) {
	// 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;
}

// RESIZEIFRAME()
// Dynamically resize the height of IFRAMEs to their content
function resizeIFrame() {
	var e = document.getElementsByTagName("iframe");
	for(var i = 0; i < e.length; i++) {
		if(e[i].contentWindow.document.body) {
			var ht = e[i].contentWindow.document.body.scrollHeight;
			if(e[i].height != ht) e[i].height = ht;
		}
	}
}

// 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
var rnksHTML = '';
function rewriteWidgetLinks() {
	var rnks = document.getElementById('rnksWidget');
	if(rnks != null && rnks.innerHTML != null && rnks.innerHTML.length != 0 && rnks.innerHTML != rnksHTML) {
		var alk = document.getElementsByTagName('a');
		if(alk.length) {
			for (var i = 0; i < alk.length; i++) {
				alk[i].target = "_top";
			}
			rnksHTML = rnks.innerHTML;
		}
	}
}
