<!--

// $Id: lib.js,v 1.4 2007/04/27 16:21:57 daver Exp $

// for use to find out if the server is live when html only pages
var sLiveHostName = 'www.southeasternrailway.co.uk';

function LiveHost()
{
	if (window.location.hostname==sLiveHostName) return true;
	return false;
}


//library of useful js functions

function Reload(oForm)
{
        oForm.submit();
}

//trim string
function TrimString(sStr) 
{
	sStr = this != window? this : sStr;
	return sStr.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function Empty(sStr)
{
	if(TrimString(sStr) == '')
		return true;
	else
		return false;
}

function RetrieveRadioVal(oRadio)
{
	if(oRadio.length) {
		for(var i = 0; i < oRadio.length; i++) {
			if (oRadio[i].checked)
				return oRadio[i].value;
		}
		return '';
	}
	else
		return oRadio.value;
}

function popUp(sUrl, sWidth, sHeight)
{
	var oWin;
	openPop(oWin, 'popup', sUrl, sWidth, sHeight, true);
}

/*

Added by Dave, usage:

Use on forms to provide automatic validation, uses name and type attributes to decide how to check variables
Will convert underscores to spaces, so naming a field 'field_one' will produce the output 'field one' if an error is encountered
Put special characters at the beginning of an inputs name to denote the kind of checking that will take place
By default zero lengths/null values are checked, special behaviour codes are listed below

U : (unchecked) Denotes that field should not be checked at all
C : (contents-only) Denotes that field should only be checked if it is non-empty,this should be combined with another code otherwise its pretty useless, for instance a name of CEemail will be checked for email validity only if non-empty
E : (email) Check field is a valid email address
D : (date) Check field is a valid date in DD-MM-(YY or YYYY)
T : (time) Check field is a valid time value
I : (integer) Check field is a valid integer
F : (float) Check field is a valid floating point number
N : (username) Check field is a valid username
P : (password) Check field is a valid password

Hidden, image, reset and submit inputs are ignored by default

The suffix variable is used in the event of error messages, and should be something like 'for this item'
Examples:

To use in a form put "onsubmit='return ValidateForm(this, 'for this user')'"

name = "CEuser_email"

Will check for a valid email address only if non-empty and will produce the following error message (if used with the onsubmit above)
"Please enter a valid user email for this user"

name = "Iuser_age"
Will check for numerical values and will produce the following error message (if used with the onsubmit above)
"Please enter a valid user age for this user"

*/
function ValidateForm(oForm, sSuffix)
{
	//check each input for empty values
	var sError = '';
	var oEmailRegex = /^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/;
	var oDateRegex = /^[0-9]{1,2}(\-|\/)[0-9]{1,2}\1([0-9]{2}|[0-9]{4})$/;
	var oTimeRegex = /^[0-9]{2}:[0-9]{2}$/;
	var oIntegerRegex = /^[0-9\s]+$/;
	var oFloatRegex = /^[0-9]+\.*[0-9]*$/;
	var oUsernameRegex = /^[a-zA-Z0-9_]{5,20}$/;
	var oPassRegex = /^[a-zA-Z0-9]{4,20}$/;
	var aVowels = new Array('a','e','i','o','u','A','E','I','O','U');
	
	for(i=0; i< oForm.length; i++)
	{
		var bDoCheck = true;
		sName = oForm.elements[i].name;
		while(sName.indexOf('_') != -1)
		{
			sName = sName.replace('_',' ');
		}
		sType = oForm.elements[i].type;
		sValue = oForm.elements[i].value;
		if(sType == 'submit' || sType == 'reset' || sType == 'hidden' || sType == 'image')
			bDoCheck = false;
		else if(sType == 'application/x-xstandard')
		{
			bDoCheck = false;
			sName = oForm.elements[i].id.replace("_editor", "");
			if(TrimString(sValue) == '')
				sError += 'Please enter a '+sName+' '+sSuffix+'\n';
			
		}
		else if(sName.charAt(0) == 'U')
			bDoCheck = false;
		else if(sName.charAt(0) == 'C')
		{
			sName = sName.substring(1);
			//Ignore if empty
			if(TrimString(sValue) == '')
				bDoCheck = false;
		}
		if(bDoCheck)
		{
			if(sType == 'select-one' || sType == 'radio' || sType == 'select-multiple')
			{
				if(!sValue)
					sError += 'Please select '+sName+' '+sSuffix+'\n';
			}
			else if(sName.charAt(0) == 'E' && !oEmailRegex.test(sValue))
				sError += 'Please enter a valid '+sName.substring(1)+'\n';
			else if(sName.charAt(0) == 'D' && !oDateRegex.test(sValue))
				sError += 'Please enter a valid '+sName.substring(1)+'\n';
			else if(sName.charAt(0) == 'T' && !oTimeRegex.test(sValue))
				sError += 'Please enter a valid '+sName.substring(1)+'\n';
			else if(sName.charAt(0) == 'I' && !oIntegerRegex.test(sValue))
				sError += 'Please enter a valid '+sName.substring(1)+'\n';
			else if(sName.charAt(0) == 'F' && !oFloatRegex.test(sValue))
				sError += 'Please enter a valid '+sName.substring(1)+'\n';
			else if(sName.charAt(0) == 'N' && !oUsernameRegex.test(sValue))
				sError += 'Please enter a valid '+sName.substring(1)+'\n';
			else if(sName.charAt(0) == 'P' && !oPassRegex.test(sValue))
				sError += 'Please enter a valid '+sName.substring(1)+'\n';
			else if(TrimString(sValue) == '')
			{
				var sArticle = 'a';
				for(i=0; i<aVowels.length; i++)
				{
					if(sName.charAt(0) == aVowels[i]) sArticle = 'an';
				}
				sError += 'Please enter '+sArticle+' '+sName+' '+sSuffix+'\n';
			}
		}
	}
	if(sError == '')
		return true;
	else
	{
		alert(sError);
		return false;
	}
}

//validate text fields
function ValidateText (field, minLength, maxLength, testReg) {
	
	var fieldLength = TrimString(field.value).length;
	
	if (fieldLength < minLength) return false;
	if ((maxLength > 0) && (fieldLength > maxLength)) return false;
	
	if ((fieldLength > 0) && testReg && !field.value.match(testReg)) return false;
	
	return true;
	
}



//validate that a radio input has been checked
function ValidateRadio (field) {
	
	var i;
	//alert(field);
	for (i = 0; i < field.length; i++) {
		if (field[i].checked) return true;
	}
	
	return false;
	
}



//validate that a select box has been selected
function ValidateSelect (field) {
	
	if (field[field.selectedIndex].value.length < 1) return false;
	
	return true;
	
}



//remove all text and elements from within an element
function EmptyTag (tag) {
	
	var tempNode;
	var last = tag.childNodes.length - 1;
	
	for (var i = last; i >= 0; i--) {
		tempNode = tag.childNodes[i];
		if ((tempNode.nodeType == 1) || (tempNode.nodeType == 3)) {
			tag.removeChild(tempNode);
		}
	}
	
}



//takes a string and converts it to a document fragment, converts newlines to <BR> tags
function CreateDocFrag (str) {
	
	var docFrag = document.createDocumentFragment();
	
	var lines = str.split('\n');
	for (var i = 0; i < lines.length; i++) {
		
		docFrag.appendChild(document.createTextNode(lines[i]));
		docFrag.appendChild(document.createElement('BR'));
		
	}
	
	return docFrag;
	
}



//writes an error message inside a specified tag
function WriteMsg (tag, str, color) {
	
	EmptyTag(tag);
	
	tag.appendChild(CreateDocFrag(str));
	
	tag.style.color = color;
	tag.style.fontWeight = 'bold';
	
}




var tlPop = null;
var imgPop = null;


//open pop-up window
function openPop(winPop, winName, url, popWidth, popHeight, scrolling){
  
  if (scrolling === true) scrolling = 'yes';
  
  var leftPos = (screen.availWidth - popWidth) / 2;
  var rightPos = (screen.availHeight - popHeight) / 2;
  
  var details = "height=" + popHeight + ",width=" + popWidth + ",left=" + leftPos + ",top=" + rightPos + ",status=no,resizable=yes,titlebar=no,toolbar=no,location=no,scrollbars=" + scrolling + ",directories=no";
  
  if (winPop && winPop.open && !winPop.closed){
    winPop.resizeTo(popWidth, popHeight);				//only works in IE
    winPop.location = url;
    winPop.focus();
  }
  else { 
    winPop = window.open(url, winName, details);
    winPop.focus();
  }
  return winPop;
}


//close pop-up window
function closePop(winPop){
  if (winPop && winPop.open && !winPop.closed){
    winPop.close();
  }
}


//view img
function viewImg(imgSrc, pathToViewer, width, height, bg) {
   
   var imgPop, viewUrl, pop_w, pop_h;
   if (imgSrc.lastIndexOf('/') != (imgSrc.length - 1)) {
      viewUrl  = (pathToViewer) ? pathToViewer : '';
      viewUrl += 'view_img.php?image=' + escape(imgSrc);
      viewUrl += (bg) ? ('&bg=' + escape(bg)) : '';
      pop_w	= (width)? width + 30 : 380;
      pop_h	= (height)? height + 30 : 310;
      openPop(imgPop, 'imgPop', viewUrl, pop_w, pop_h, false);
   } else {
      alert('No image selected');
   }
   return false;
   
}


//new function added by Dave
function checkDate(e)
{
	//checks a date for mysql YYYY-MM-DD format
	date = TrimString(e.value);
	var error = '';
	if(date.length != 10)
	{
		error = 'Dates must be YYYY-MM-DD format, your date is too short';
	}
	else
	{
		var ok = true;
		var errorChars = '';	
		for(i=0; i<date.length; i++)
		{
			if(i==4 || i==7)
			{
				if(date.charCodeAt(i) != 45)
				{
					ok = false;
					errorChars = errorChars + date.charAt(i);
				}
			}
			else if(date.charCodeAt(i)<=47 || date.charCodeAt(i)>=58)
			{
				ok = false;
				errorChars = errorChars + date.charAt(i);
			}
		}
		if(!ok)
			error = 'Dates must be YYYY-MM-DD format\nThe following false characters were found: '+errorChars;
	}
	return error;
}


function ChangeCssRule(modStyleSheet, modSelector, modProperty, newValue) {        
   
   var strCSS = (document.all) ? 'rules' : 'cssRules';
   var modRule;
   var i = 0;
   
   var modRules = modStyleSheet[strCSS];
   
   while (modRule = modRules[i]) {
      if (modRule.selectorText == modSelector) {
         modRule.style[modProperty] = newValue;
         break;
      } else {
         i++;
      }
   }
}


/*
Date Validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
Checks that the entered date is real.
*/

// Declare valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s)
{
	var i;
  for (i = 0; i < s.length; i++){   
      // Check that current character is number.
      var c = s.charAt(i);
      if (((c < "0") || (c > "9"))) return false;
  }
  // All characters are numbers.
  return true;
}

function stripCharsInBag(s, bag)
{
	var i;
  var returnString = "";
  // Search through string's characters one by one.
  // If character is not in bag, append to returnString.
  for (i = 0; i < s.length; i++){   
      var c = s.charAt(i);
      if (bag.indexOf(c) == -1) returnString += c;
  }
  return returnString;
}

function daysInFebruary (year)
{
	// February has 29 days in any year evenly divisible by four,
  // EXCEPT for centurial years which are not also divisible by 400.
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) 
{
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
	} 
	return this;
}

function isDate(dtStr) 
{
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strDay=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : dd/mm/yyyy");
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month");
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day");
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date");
		return false;
	}
	return true;
}


function nowGbDate() {
   
   var nowDate = new Date();
   
   var nowD = new String(nowDate.getDate());
   var nowM = new String(nowDate.getMonth() + 1);
   var nowY = new String(nowDate.getYear());
   
   var dateReturn = '';
   dateReturn += (nowD.length == 1) ? ('0' + nowD) : nowD;
   dateReturn += '/' + ((nowM.length == 1) ? ('0' + nowM) : nowM);
   dateReturn += '/' + nowY;
   
   return dateReturn;
   
}


// single rollover --

function rollover(imageSource, whichImage, imageWidth, imageHeight ,statusText) {
if (document.images) {
	image = new Image(imageWidth,imageHeight);
	image.src = imageSource;
	
	swapImage(whichImage);
	//window.status=statusText;
}
}

function unRollover(imageSource, whichImage, statusText) {
if (document.images) {
	replaceImage(imageSource, whichImage);
	//returnStatus(statusText);
}
}

function swapImage(whichImage) {
document.images[whichImage].src = image.src;
}

function replaceImage(imageSource, whichImage) {

alert(imageSource);
document.images[whichImage].src = imageSource;
}


function returnStatus(statusText) {
	changeStatus(statusText);
	window.defaultStatus='Thameslink';
}

function changeStatus(statusText) {
	window.status=statusText;
}

function preloadImg(imgSrc) 
{
   var preLoad = new Image;
   preLoad.src = imgSrc; 
}

function formRollover(oElement, sImage)
{
	oElement.src = sImage;
}

function swapImg(oImgTag, sImage)
{
	oImgTag.src = sImage;
}


//function to set a select input
function setSelect(frm, selName, selValue)
{
   var sel;
   var i;
   if (sel = document.getElementById(selName)) {
      for (i = 0; i < sel.options.length; i++) {
         if (sel.options[i].value == selValue) sel.options[i].selected = true;
      }
   }
   return;
}

//function to set a radio button on
function setRadio(frm, radName, radValue)
{
   var i;//alert(frm.elements[1].value);
   for (i = 0; i < frm.elements.length; i++) {
      if (frm.elements[i].type == 'radio' && frm.elements[i].name == radName && frm.elements[i].value == radValue) frm.elements[i].checked = true;
   }
   return;
}


//function to test whether a value is in an array
function inArray(val, testArray) {
   
   var found = false;
   var i;
   for (i = 0; i < testArray.length; i++) {
      if (testArray[i] == val) {
         found = true;
         break;
      }
   }
   return found;
   
}

// function to open address lookup window
/*
function addLookUp(sColor)
{
	var oForm = document.MainForm;
	var oWin;
	openPop(oWin, 'lookup', 'address_lookup.php?p='+oForm.postcode.value+'&amp;c='+sColor, '300', '133', true);
}
*/

//-->