var gAlerted = "";
var gChanged = "";

var charLT = '<';
var charGT = '>';
var charSQ = "'";
var charDQ = '"';
var blank = '';

var gPopUpWindow = null;
var windowURL = null;
var windowx = null;
var windowy = null;
var windoww = null;
var windowh = null;
var newx = '';
var newy = '';
var current_session = "";
var isBirdseye = false;
var mapType = 'H';

var ezoom = 99;
var panelUsed = "false";
var calDate;
var dateFormat = 'EU';
var markerFeature;
var kmlUrl;
var clickNumber = 0;

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

isNav = (navigator.appName.indexOf("Netscape") != -1) ? true : false;
isIE = (navigator.appName.indexOf("Microsoft") != -1) ? true : false;
isOpera = (navigator.appName.indexOf("Opera") != -1) ? true : false;

/* This function displays an alert */
function doAlert(field, msg, doIt) {

/* Don't alert option */
if (doIt != true) return;

/* Stop focus being drawn if another alert is in progress */
if ((gAlerted != "") && (gAlerted != field.name)) return;

/* Stop loop of alerts in Navigator */
if ((isNav == true) && (gChanged != "")) return;

gAlerted = field.name; // resetAlert should be called by onChange event
gChanged = field.name;

field.select();
alert(msg);
field.focus();
}

/********************************************************************************/

/* This function displays a message */
function doMessage(field, msg) {

/* Stop focus being drawn if another alert is in progress */
if ((gAlerted != "") && (gAlerted != field.name)) return;

/* Stop loop of alerts in Navigator */
if ((isNav == true) && (gChanged != "")) return;

gAlerted = field.name; // resetAlert should be called by onChange event
gChanged = field.name;
alert(msg);
}

/********************************************************************************/
function resetAlert() {
gAlerted = "";
gChanged = "";
}

/********************************************************************************/

function isBeforeToday(datestr) {

var strDay;
var strMonth;
var strYear;
var now;
var nowDays;
var targetDays;

   targetDate = isValidDate(datestr);
   if (targetDate != null) {
       now = new Date();
       strDay = now.getDate();
       strMonth = now.getMonth();
       /* Months start counting at 0 */
       if (strMonth < 12) {strMonth = strMonth + 1;}
       strYear = now.getFullYear();
       nowDays = getDaysFromValue(strDay,strMonth,strYear);
       strDay = targetDate.substr(0, 2);
       strMonth = targetDate.substr(3, 2);
       strYear = targetDate.substr(6); 
       targetDays = getDaysFromValue(strDay,strMonth,strYear);
       if (targetDays < nowDays)
          return true;
       else
          return false;
       }
   else {
   return false;
       }
   }

function isNotAfterToday(datestr) {

var strDay;
var strMonth;
var strYear;
var now;
var nowDays;
var targetDays;

   targetDate = isValidDate(datestr);
   if (targetDate != null) {
       now = new Date();
       strDay = now.getDate();
       strMonth = now.getMonth();
       /* Months start counting at 0 */
       if (strMonth < 12) {strMonth = strMonth + 1;}
       strYear = now.getFullYear();
       nowDays = getDaysFromValue(strDay,strMonth,strYear);
       strDay = targetDate.substr(0, 2);
       strMonth = targetDate.substr(3, 2);
       strYear = targetDate.substr(6); 
       targetDays = getDaysFromValue(strDay,strMonth,strYear);
       if (targetDays <= nowDays)
          return true;
       else
          return false;
       }
   else {
   return false;
       }
   }


function getDaysFromValue(strDay,strMonth,strYear) {  

var returnValue = 0;

/* Months start counting at 0 */
if (strMonth > 0) {
   strMonth = strMonth - 1;
   }

/* Find number of days since 01/01/1970 */
var oDate = new Date(Date.UTC(strYear, strMonth, strDay));
returnValue = Math.floor(oDate.getTime()/(1000*60*60*24));
return returnValue;
}

/********************************************************************************/

function validateMultiLine(fieldName, required, maxLength) {
var thisField = fieldName;
var newValue = null;

if (required == true) {
   if (isBlank(thisField.value) == true) {
      // alert("You must specify a value for this item.");
       return false;
       }
   }

/* Do not validate blank values */
if (isBlank(thisField.value) == true) {
    return true;
    } 

/* Validate maximum length */
if (isBlank(maxLength) == false) {
   if (isValidLength(thisField.value, maxLength) == false) {
       doAlert(thisField, "Length must be less than or equal to " + maxLength, true);
       return false;
       }
    } 

return true;
}

/********************************************************************************/

/* Aggregate Functions */

function doCount() {
var count = 0;
var i;

// alert("In doCount: " + arguments[0].value + ", " + arguments[1].value + ", " + arguments[2].value);
for (i = 0; i < arguments.length; i++) {
    if (arguments[i].value != '')
       count++;
    }
// alert("count = " + count);
return count;
}

function doSum() {
var sum = 0;
var decommaNo = 0;
var newValue = 0;
var i;

// alert("In doSum: " + arguments[0].value + ", " + arguments[1].value + ", " + arguments[2].value);
for (i = 0; i < arguments.length; i++) {
    decommaNo = arguments[i].value.replace(/,/g, "");
    newValue = parseFloat(decommaNo);
    if (newValue == decommaNo)
       sum = sum + newValue;
    }
// alert("sum = " + sum);
return parseNumber(sum);
}

function doAvg() {
var count = 0;
var sum = 0;
var avg = 0;
var decommaNo = 0;
var newValue = 0;
var i;

// alert("In doAvg: " + arguments[0].value + ", " + arguments[1].value + ", " + arguments[2].value);
for (i = 0; i < arguments.length; i++) {
    if (arguments[i].value != '')
       count++;
    decommaNo = arguments[i].value.replace(/,/g, "");
    newValue = parseFloat(decommaNo);
    if (newValue == decommaNo)
       sum = sum + newValue;
    }
if (count > 0)
   avg = sum / count;
// alert("count = " + count + ", sum = " + sum + ", avg = " + avg);
return parseNumber(avg);
}

/********************************************************************************/

function validateField(fieldName, validationType, required, returnFocus, minValue, maxValue, pattern, patternMsg, roundMode) {
var thisField = fieldName;
var newValue = null;

/* Set default values for optional parameters */
if (arguments.length < 9) roundMode = '';
if (arguments.length < 8) patternMsg = '';
if (arguments.length < 7) pattern = '';
if (arguments.length < 6) maxValue = '';
if (arguments.length < 5) minValue = '';
if (arguments.length < 4) returnFocus = true;

if (required == true) {
   if (isBlank(thisField.value) == true) {
       // alert("You must specify a value for this item.");
       return false;
       }
   }

/* Do not validate blank values */
if (isBlank(thisField.value) == true) {
    return true;
    } 

if (validationType == "DATE") {
   newValue = isValidDate(thisField.value);
   if (newValue == null) {
       doAlert(thisField, "Invalid date specified. Please specify date in format dd/mm/yyyy.", returnFocus);
       return false;
       }
   else {
       fieldName.value = newValue;
       return true;
       } 
   }
else if (validationType == "PASTDATE") {
   newValue = isValidDate(thisField.value);
   if (newValue == null) {
       doAlert(thisField, "Invalid date specified. Please specify date in format dd/mm/yyyy.", returnFocus);
       return false;
       }
   else if (isNotAfterToday(newValue)) {
       fieldName.value = newValue;
       return true;
       } 
   else {
       doAlert(thisField, "Date cannot be in the future.", returnFocus);
       return false;
       }
   }
else if (validationType == "TIME") {
   newValue = thisField.value;
   if (returnFocus && newValue.length < 3)
      newValue = newValue + ":00";
   else if (returnFocus && newValue.indexOf(':') == -1)
      newValue = newValue.substr(0, newValue.length-2) + ":" + newValue.substr(newValue.length-2, newValue.length);
   else if (newValue.indexOf(':') == -1)
      newValue = toTime(newValue);
   if (isValidTime(newValue) == false) {
      doAlert(thisField, "Invalid time specified. Please specify times in format hh:mm.", returnFocus);
      return false;
      }
   fieldName.value = newValue;
   return true;
   }
else if (validationType == "EMAIL") {
   if (isValidEmail(thisField.value) == false) {
       doAlert(thisField, "Invalid email address specified. Please try again.", returnFocus);
       return false;
       }
   }
else if (validationType == "URL") {
   if (isValidURL(thisField.value) == false) {
       doAlert(thisField, "Invalid URL specified. Please try again.", returnFocus);
       return false;
       }
   }
else if (validationType == "UPPER") {
   newValue = thisField.value.toUpperCase();
   fieldName.value = newValue;
   return true;
   }
else if (validationType == "INTEGER") {
   newValue = isValidInteger(thisField.value.replace(/,/, ''),roundMode);
   if (newValue == null) {
       doAlert(thisField, "Invalid number specified. Please enter a whole number.", returnFocus);
       return false;
       }
   else {
       fieldName.value = newValue;
       } 
   }
else if (validationType == "NUMBER") {
   newValue = isValidNumber(thisField.value.replace(/,/, ''),2);
   if (newValue == null) {
       doAlert(thisField, "Invalid number specified. Please try again.", returnFocus);
       return false;
       }
   else {
       fieldName.value = newValue;
       } 
   }
else if (validationType == "MONEY") {
   newValue = isValidMoney(thisField.value.replace(/,/, ''));
   if (newValue == null) {
       doAlert(thisField, "Invalid money format specified. Please specify money in format 2500, 2,500, or 2.50.", returnFocus);
       return false;
       }
   else if ((newValue < 0) || (newValue.indexOf("-") == 0)) {
       doAlert(thisField, "Amounts of money may not be less than zero. Please try again.", returnFocus);
       fieldName.value = newValue;
       return false;
       }
   else {
       fieldName.value = newValue;
       } 
   }
else if (validationType == "PATTERN") {
   if (isValidPattern(thisField.value,pattern) == false) {
       doAlert(thisField, patternMsg, returnFocus);
       return false;
       }
   }

/* Validate minimum value */
if (isBlank(minValue) == false) {
   if (checkMin(thisField.value.replace(/,/, ''), minValue.replace(/,/, '')) == false) {
       doAlert(thisField, "Value must be greater than or equal to " + minValue, returnFocus);
       return false;
       }
    } 

/* Validate maximum value */
if (isBlank(maxValue) == false) {
   if (checkMax(thisField.value.replace(/,/, ''), maxValue.replace(/,/, '')) == false) {
       doAlert(thisField, "Value must be less than or equal to " + maxValue, returnFocus);
       return false;
       }
    } 

return true;
}

/********************************************************************************/

function isBlank(str) {
	if ((str==null) || (str==""))
		return true;
	for (i = 0; i < str.length; i++) {
		if (str.charAt(i) != " ")
			return false;
	}
	return true;
}

/********************************************************************************/

// Check that the number of characters in a string is between a max and a min
function isValidLength(string, max) {
	if (string.length > max) return false;
	else return true;
}

/********************************************************************************/

function isValidInteger(strNumber,roundMode) {
	var decommaNo;
	var tmpNo;
	var temp;
	var dotpos;

        if (arguments.length < 2) roundMode = '';
        if ((roundMode != 'U') && (roundMode != 'u') && (roundMode != 'D') && (roundMode != 'd')) roundMode = '';

        //Check value is numeric
	decommaNo = strNumber.replace(/,/g, "");
        tmpNo = parseFloat(decommaNo);
	if(tmpNo != decommaNo)
	   {return null;}

        //Round to nearest integer
        if ((roundMode == 'U') || (roundMode == 'u'))
          tmpNo = Math.ceil(tmpNo);
        else if ((roundMode == 'D') || (roundMode == 'd'))
          tmpNo = Math.floor(tmpNo);
        else
          tmpNo = Math.round(tmpNo);

	//Take off trailing decimals
	temp = new String(tmpNo);
	dotpos = temp.indexOf(".");
	if(dotpos != -1) {
	   temp = temp.substr(0,dotpos);
	   }
	return temp;
}

/********************************************************************************/

function isValidNumber(strNumber,decimals) {
	var decommaNo;
	var tmpNo;
	var temp;
	var dotpos;
	var powerofTen;

	if (arguments.length < 2) decimals = 2;		// Default number of decimal places to display
	decommaNo = strNumber.replace(/,/g, "");
        tmpNo = parseFloat(decommaNo);
	if(tmpNo != decommaNo)
	   {return null;}
	powerofTen = Math.pow(10,decimals);
	temp = new String((Math.round(decommaNo * powerofTen)) /powerofTen);
	dotpos = temp.indexOf(".");
	if(dotpos == -1) {
	   temp = temp + ".0000000000".substr(0,decimals + 1);
	   }
	else if(dotpos >= (temp.length - decimals)) {
	   temp = temp + "0000000000".substr(0,decimals + 1 + dotpos - temp.length);
	   }
	return temp;
}

/********************************************************************************/

function isValidMoney(strNumber) {
	var decommaNo;
	var tmpNo;
	var temp;
	var dotpos;

	decommaNo = strNumber.replace(/,/g, "");
        tmpNo = parseFloat(decommaNo);
	if(tmpNo != decommaNo)
	   {return null;}

	dotpos = strNumber.indexOf(".");
	if (dotpos == 0){
	  strNumber = "0" + strNumber;
	  dotpos += 1;
	  }

	if (dotpos == -1)
	   {return strNumber + ".00";}
	else if (dotpos == (strNumber.length - 1))
	   {return strNumber + "00";}
	else if (dotpos == (strNumber.length - 2))
	   {return strNumber + "0";}
	else if (dotpos == (strNumber.length - 3))
	   {return strNumber;}
	else /* Too many decimals */
	   {temp = new String((Math.round(decommaNo * 100)) /100);
	    return temp;}
}

/********************************************************************************/

function parseNumber(strNumber,decimals) {
	var numberToParse = strNumber;
	var tmpNo;
	var temp;
	var dotpos;
	var powerofTen;

	if (arguments.length < 2) decimals = 2;		// Default number of decimal places to display
        tmpNo = parseFloat(numberToParse);
	if(tmpNo != numberToParse) {
	   numberToParse = "0";
	   }
	powerofTen = Math.pow(10,decimals);
	temp = new String((Math.round(numberToParse * powerofTen)) /powerofTen);
	dotpos = temp.indexOf(".");
	if(dotpos == -1) {
	   temp = temp + ".0000000000".substr(0,decimals + 1);
	   }
	else if(dotpos >= (temp.length - decimals)) {
	   temp = temp + "0000000000".substr(0,decimals + 1 + dotpos - temp.length);
	   }
	return temp;
}

/********************************************************************************/

// Checks if value is within range
function checkMin(strNumber, min){
	var tmpMin;
	
	tmpMin = parseFloat(min);
			
	if((!min&&min!=0)||tmpMin!=min)
		{min = -(1/0);}
	
	
	if(Math.max(min,strNumber) != strNumber)
		{return false;}
	else
		{return true;}
	
}

/********************************************************************************/

// Checks if value is within range
function checkMax(strNumber, max){
	var tmpMax;
	
	tmpMax = parseFloat(max);
			
	if((!max&&max!=0)||tmpMax!=max)
		{max = (1/0);}
	
	if(Math.min(max,strNumber) != strNumber)
		{return false;}
	else
		{return true;}
	
}

/********************************************************************************/

// Checks if string follows pattern
function isValidPattern(str, pattern) {

var regExp = new RegExp(pattern, "");
return regExp.test(str);
}

/********************************************************************************/

// Simple URL validation
function isValidURL(url){
	return true;
}

/********************************************************************************/

// Check that an email address is valid based on RFC 821 (?)
function isValidEmail(address) {
        address = trimString(address);
	if (address.indexOf('@') < 1) return false;
	var name = address.substring(0, address.indexOf('@'));
	var domain = address.substring(address.indexOf('@') + 1);
        if (isBlank(domain) == true)
            return false;
	if (name.indexOf('(') != -1 || name.indexOf(')') != -1 || name.indexOf('<') != -1 || name.indexOf('>') != -1 || name.indexOf(',') != -1 || name.indexOf(';') != -1 || name.indexOf(':') != -1 || name.indexOf('\\') != -1 || name.indexOf('"') != -1 || name.indexOf('[') != -1 || name.indexOf(']') != -1 || name.indexOf(' ') != -1) return false;
	if (domain.indexOf('(') != -1 || domain.indexOf(')') != -1 || domain.indexOf('<') != -1 || domain.indexOf('>') != -1 || domain.indexOf(',') != -1 || domain.indexOf(';') != -1 || domain.indexOf(':') != -1 || domain.indexOf('\\') != -1 || domain.indexOf('"') != -1 || domain.indexOf('[') != -1 || domain.indexOf(']') != -1 || domain.indexOf(' ') != -1) return false;
	return true;
}

/********************************************************************************/

function fromTime(timeStr) {

if (timeStr == null) return 0;
if (timeStr == 0) return 0;

var timePat = /^(\d{1,2}):(\d{2})$/;

var matchArray = timeStr.match(timePat);
if (matchArray == null) {
return 0;
}

return parseInt(isValidInteger(matchArray[1], '') * 60) + parseInt(matchArray[2]);
}

/********************************************************************************/

function toTime(intStr) {

// Converts minutes since midnight into time
// Need to add '' strings to turn integers into strings

var mins = isValidInteger('' + intStr);
if (mins == null || mins < 0) 
   return '';

mins = mins % 1440;
var hrs = '' + isValidInteger('' + mins/60, 'D');
if (hrs.length == 1)
   hrs = '0' + hrs;

mins = '' + mins % 60;
if (mins.length == 1)
   mins = '0' + mins;

return hrs + ":" + mins;
}

/********************************************************************************/

function isValidTime(timeStr) {

// Checks if time is in HH:MM format.
var timePat = /^(\d{1,2}):(\d{2})$/;
var matchArray = timeStr.match(timePat);

if (matchArray == null) {
return false;
}

hour = matchArray[1];
minute = matchArray[2];

if (hour < 0  || hour > 23) {
return false;
}
if (minute<0 || minute > 59) {
return false;
}
return true;
}

/********************************************************************************/

function trimString(instr) {

var outstr;
outstr = instr;
// Trim leading spaces
while (outstr.charAt(0)==" "){
    outstr = outstr.substr(1);
    }
// Trim trailing spaces
while (outstr.charAt(outstr.length - 1)==" "){
    outstr = outstr.substr(0,outstr.length - 1);
    }
return outstr;
}

/********************************************************************************/

function isValidDate(datestr) {

var strDatestyle = dateFormat;
var strDate;
var strDateArray;
var strDay="";
var strMonth="";
var strYear="";
var intday;
var intMonth;
var intYear;
var booFound = false;
var strSeparatorArray = new Array("-","/","."," ");
var intElementNr;
strDate = trimString(datestr);

for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
   if (booFound && strSeparatorArray[intElementNr]==" ") {
      }
   else if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
      strDateArray = strDate.split(strSeparatorArray[intElementNr]);
      if (strDateArray.length != 3) {
          return null;
          }
      else {
      if (strDatestyle == "EU") {
          strDay = trimString(strDateArray[0]);
          strMonth = trimString(strDateArray[1]);
          strYear = trimString(strDateArray[2]);
          }
      else       {
          strDay = trimString(strDateArray[1]);
          strMonth = trimString(strDateArray[0]);
          strYear = trimString(strDateArray[2]);
      }
      }      
      booFound = true;
      }
    }

if (booFound == false) {
   if (strDate.length>5) {
    if (strDatestyle == "EU") {
       strDay = strDate.substr(0, 2);
       strMonth = strDate.substr(2, 2);
       strYear = strDate.substr(4);
       }
       else{
       strMonth = strDate.substr(0, 2);
       strDay = strDate.substr(2, 2);
       strYear = strDate.substr(4);
       }
    }
   }

// Pad day and month with leading zero
if (strDay.length == 1) {
   strDay = "0" + strDay;
   }
if (strMonth.length == 1) {
   strMonth = "0" + strMonth;
   }

var tempDay;
var tempMonth;

if (strDay.charAt(0) == "0"){
   tempDay = strDay.substr(1);
   }
else
   tempDay = strDay;

if (strMonth.charAt(0) == "0"){
   tempMonth = strMonth.substr(1);
   }
else
   tempMonth = strMonth;

if (isValidInteger(tempDay) == null) {
   return null;
   }
if (isValidInteger(tempMonth) == null) {
   return null;
   }
if (isValidInteger(strYear) == null) {
   return null;
   }

intday = parseInt(strDay, 10);
intMonth = parseInt(strMonth, 10);
intYear = parseInt(strYear, 10);


if (intYear < 100) {
   if (intYear >=30) {
       intYear = intYear +  1900;
       }
   else {
       intYear = intYear +  2000;
       }
   }

if (intMonth>12 || intMonth<1) {
   return null;
   }

if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
   return null;
   }

if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
   return null;
   }

if (intMonth == 2) {
   if (intday < 1) {
      return null;
      }
   if (LeapYear(intYear) == true) {
      if (intday > 29) {
         return null;
         }
      }
   else {
      if (intday > 28) {
         return null;
         }
      }
   }

if (strDatestyle == "US") {
   return strMonth + "/" + strDay + "/" + intYear;
   }
else {
   return strDay + "/" + strMonth + "/" + intYear;
   }
}

/********************************************************************************/

function LeapYear(intYear) {
if (intYear % 100 == 0) {
if (intYear % 400 == 0) { return true; }
}
else {
if ((intYear % 4) == 0) { return true; }
}
return false;
}

function show_help(message) {
       alert(message);
}

/********************************************************************************/

function getCheckboxValue(formName, elementName, uncheckedValue) {

if (arguments.length < 3) uncheckedValue = 'No';
if (arguments.length < 2) return null;
if (formName == null || formName == '') formName = 'NonStopGov';
var el = document.forms[formName][elementName];
var value;

if (el == null)
    value = uncheckedValue;
else {
   var checkedValue = el.value;
   if (el.checked)
     value = checkedValue;
   else
     value = uncheckedValue;
   }

return value;
}

/********************************************************************************/

function getRadioValue(formName, elementName) {

if (arguments.length < 2) return null;
if (formName == null || formName == '') formName = 'NonStopGov';
var el = document.forms[formName][elementName];
var value = '';

if (el==null) 
   return value;

for(var i=0; i<el.length; i++) { 
  if(el[i].checked) 
    value = el[i].value; 
  }

return value;
}


/********************************************************************************/

function getItemValue(formName, sequence, uncheckedValue) {

if (uncheckedValue == null || uncheckedValue == '') uncheckedValue = 'No';
if (formName == null || formName == '') formName = 'NonStopGov';

var element = document.getElementById('p_' + sequence);

/*check if the element is a radio item*/
if (element==null) 
element = document.getElementById('p_' + sequence+'_0');

var type = element.type;

if(type=="checkbox"){
return getCheckboxValue(formName,'p_' + sequence,uncheckedValue)}
else 
if(type=="radio"){
return getRadioValue(formName, 'p_' + sequence)}
else { 
return document.getElementById('p_' + sequence).value;}

}
/********************************************************************************/

function getDays(fieldName) {  /* N.B. This function only accepts dates in format dd/mm/yyyy */

var strDate = fieldName.value;
var strDay;
var strMonth;
var strYear;
var returnValue = 0;

/* Return zero for blank values */
if ((isBlank(strDate) == true) || (strDate.length <= 7)) {
    return returnValue;
    } 

/* Otherwise assume date is valid and set up day, month, year */
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(3, 2);
strYear = strDate.substr(6); 

/* Months start counting at 0 */
if (strMonth > 0) {
   strMonth = strMonth - 1;
   }

/* Find number of days since 01/01/1970 */
var oDate = new Date(Date.UTC(strYear, strMonth, strDay));
returnValue = Math.floor(oDate.getTime()/(1000*60*60*24));
return returnValue;
}

/********************************************************************************/

function getModifiedDate(fieldValue, modifier) {

var strDate = fieldValue;
var strDay;
var strMonth;
var strYear;
var returnValue = 0;
var pDate;
var temp = "";
var i;
var separators = "-/. ";

modifier = modifier.toUpperCase();

/* Do IsNull detection */
if (modifier == "ISNULL"){
   if ((strDate == null) || (strDate == ""))
      return true;
   else
      return false;
   }

if (modifier == "ISNOTNULL"){
   if ((strDate == null) || (strDate == ""))
      return false;
   else
      return true;
   }

/* Return zero for blank values */
if ((isBlank(strDate) == true) || (strDate.length <= 7)) {
    return 0;
    } 

/* Return zero for invalid date format */
strDate = isValidDate(strDate);
if (strDate == null) {
    return 0;
    } 

/* Make date object */
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(3, 2);
strYear = strDate.substr(6); 
/* Months start counting at 0 */
if (strMonth > 0) {
   strMonth = strMonth - 1;
   }
pDate = new Date(Date.UTC(strYear, strMonth, strDay));


if ((arguments.length < 2) || (modifier == null)) {
   /* Find number of days since 01/01/1970 */
   returnValue = Math.floor(pDate.getTime()/86400000); // Number of millisec in a day 1000*60*60*24 = 86400000
   }
else {
   returnValue = "";
   for (i = 0; i < modifier.length; i++) {
      if (separators.indexOf(modifier.substr(i,1)) == -1) {
         temp = temp + modifier.substr(i,1);
         }
      else { // separator found
         returnValue = returnValue + actOnModifier(pDate,temp) + modifier.substr(i,1);
         temp = "";
         }
      }
   if (temp.length > 0) {
      returnValue = returnValue + actOnModifier(pDate,temp);
      }
   }

if (returnValue == "") returnValue = 0;
return returnValue;

}

/********************************************************************************/

function actOnModifier(pDate, modifier) {

var output = "";
var today;

if ((arguments.length < 2) || (modifier == null)) {
   return "";
   }

modifier = modifier.toUpperCase();

if (modifier == "ISNULL"){
   if (pDate == null)
      return true;
   else
      return false;
   }


if (!pDate)
   return 0;

switch (modifier) {
   case 'DD':
   case 'D':
      output = pDate.getDate();
      break;
   case 'MM':
   case 'M':
      output = pDate.getMonth() + 1;
      break;
   case 'YYYY':
   case 'Y':
      output = pDate.getFullYear();
      break;
   case 'YY':
      output = pDate.getFullYear();
      output = output.toString();
      output = output.substr(2);
      break;
   case 'DAYS':
      output = Math.floor(pDate.getTime()/86400000);
      break;
   case 'AGE':
      // Return age today in years
      today = new Date();
      if (Math.floor(today.getTime()/86400000) <= Math.floor(pDate.getTime()/86400000))
         output = 0;
      else {
         output = today.getFullYear() - pDate.getFullYear();
         if ((pDate.getMonth() > today.getMonth()) || 
          (((pDate.getMonth() == today.getMonth()) && (pDate.getDate() > today.getDate())))) { 
            output = output - 1;
            }
         if (output < 0) output = 0;
         }
      break;
   }

return output;

}

/********************************************************************************/

function isNull(fieldValue){

var data = fieldValue;

   if ((data == null) || (data == ""))
      return true;
   else
      return false;
}

function isNotNull(fieldValue){

var data = fieldValue;

   if ((data != null) && (data != ""))
      return true;
   else
      return false;
}

/********************************************************************************/

function isNullCheckbox(formName, elementName) {

if (arguments.length < 2) return true;
if (formName == null || formName == '') formName = 'NonStopGov';
var el = document.forms[formName][elementName];

if (el.checked)
  return false;
else
  return false;
}

function isNotNullCheckbox(formName, elementName) {

if (arguments.length < 2) return false;
if (formName == null || formName == '') formName = 'NonStopGov';
var el = document.forms[formName][elementName];

if (el.checked)
  return true;
else
  return true;
}

/********************************************************************************/

function isNullRadio(formName, elementName) {

if (arguments.length < 2) return true;
if (formName == null || formName == '') formName = 'NonStopGov';
var el = document.forms[formName][elementName];
var value = true;

for(var i=0; i<el.length; i++) { 
  if(el[i].checked) {
    value = false; 
    break;
    }
  }

return value;
}

function isNotNullRadio(formName, elementName) {

if (arguments.length < 2) return false;
if (formName == null || formName == '') formName = 'NonStopGov';
var el = document.forms[formName][elementName];
var value = false;

for(var i=0; i<el.length; i++) { 
  if(el[i].checked) {
    value = true; 
    break;
    }
  }

return value;
}

/********************************************************************************/

function updateField(fieldName,strData,req){
   fieldName.value = strData;
}

/********************************************************************************/

function closePopUp() {
if (gPopUpWindow){
    gPopUpWindow.close();
    gPopUpWindow = null;
    }
}

function new_window(url,helpUrl,title,x,y,w,h, closepanel){

/*helpUrl not used anymore*/

 if(panelUsed == "true" && closepanel)
  {
	closePanel();
  }

if ((arguments.length < 7) || (h == '') || isNaN(h)) h = 200;
if(h < 10) h = 10;
if(h > screen.availHeight - 100) h = screen.availHeight - 100;
if ((arguments.length < 6) || (w == '') || isNaN(w)) w = 200;
if(w < 10) w = 10;
if(w > screen.availWidth - 100) w = screen.availWidth - 100;

if(windowx = null) windowx = 0;
if(windowy = null) windowy = 0;
if(windoww = null) windoww = screen.availWidth;
if(windowh = null) windowh = screen.availHeight;

if (isIE){
    windowx = screenLeft;
    windowy = screenTop;
    }
else if (isNav){
    windowx = screenX;
    windowy = screenY;
    }

if ((arguments.length < 5) || (y == '') || isNaN(y)) y = (screen.availHeight - h - 70) / 2;
if(y < 0) y = 0;
if(y + h > screen.availHeight) y = (screen.availHeight - h - 70)/2;
if(y < 0) y = 0;

if ((arguments.length < 4) || (x == '') || isNaN(x)) x = (screen.availWidth - w / 2);
if(x < 0) x = 0;
if(x + w > screen.availWidth) x = (screen.availWidth - w)/2;

if ((arguments.length < 3) || (title.length<1)) title = "Record Actions";

if(arguments.length < 1) url = "";

var features_list = "left=" + x + ",top=" + y + ",screenX=" + x + ",screenY=" + y + ",width=" + w + ",height=" + h + ",resizable, scrollbars, menubar=no, toolbar=no, location=no, directories=no, dependent, alwaysRaised";

var window_name = title;
window_name = window_name.replace(/\s+|[^A-Z]/gi,"_"); 

closePopUp(); // Close previous pop-up window

var new_handle = null;

new_handle = window.open(url,window_name,features_list);

new_handle.focus();

gPopUpWindow = new_handle;

return new_handle;
}

function load(url){
location=url;
}

function openerLoad(url){
window.opener.location=url;
}


function textPopup(myname,mytext,w,h,myurl){
 if(panelUsed == "true")
  {
	closePanel();
  }
if(arguments.length < 5) myurl = "";
{LeftPosition=(screen.width)?(screen.width-w)/2:100;
 TopPosition=(screen.height)?(screen.height-h)/2:100;}
settings='width='+ w + ',height='+ h + ',top=' + TopPosition + ',left=' + LeftPosition + ',scrollbars=no,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no,dependent=yes,alwaysRaised=yes';
gPopUpWindow=window.open(myurl,myname,settings);
gPopUpWindow.load = self.load;
if (mytext.length > 0)
 gPopUpWindow.document.write(mytext);
gPopUpWindow.load = self.load;
gPopUpWindow.document.close;
gPopUpWindow.focus();
}

function textCounter(field, maxlimit, txtN) {
   var mystring = 'Space for ' + (maxlimit-field.value.length)+' characters remaining';
   if (field.value.length > maxlimit) {
	field.value = (field.value.substring(0, maxlimit));
        mystring = 'No more space available';
	}
   else if (field.value.length < maxlimit - 200) {
	mystring = '';
	}
   document.getElementById([txtN]).innerHTML = mystring;
   }


function focusForm() { 

  // First format all tooltips
  formatAllTooltips();

  // This is a fix for Mozilla to do with Proceed
  // button not enabling when using browser's back button
  allObjs = document.getElementById('Next');
	if(allObjs != null)
	{
	  allObjs.disabled = false;
	}
  // do this in a timer so it works even when the
  // document contains javascript write commands
  setTimeout("setFocus()", 250); 
}

function setFocus() {

  // If there is a NonStopGov form in the doc...
  if (document.NonStopGov) {

    theElems = document.NonStopGov.elements;

    if (theElems == null)
      return;

    // loop over the elements until finding a non-hidden one
    for (i = 0; i < theElems.length; i++) {
      theElem = theElems[i];
      if (theElem.type && theElem.type == "hidden" ) {
        continue;
      }
      if (theElem.type && theElem.disabled == true) {
        continue;
      }
      // focus on the first non-hidden and non-disabled element found
      theElem.focus();
      break;
    }
  }
}


function formatAllTooltips()
{
      // hide span elements
      allObjs = document.getElementsByTagName("span");
      for(i=0; i<allObjs.length; i++) 
	{ 
      if(allObjs[i].id.indexOf("Help") > 0)
         hideEl(allObjs[i].id);
	}	

      // show a elements
      allObjs = document.getElementsByTagName("a");
	for(i=0; i<allObjs.length; i++)
	{ 
      if(allObjs[i].id.indexOf("Help") > 0)
         showEl(allObjs[i].id);
	}
}

function setRadioValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

var fieldseq = 0;

function selectValue(readOnly) {
  var i;
  var el;
  var firstFieldSeq = fieldseq;
  for (i = 1; i < arguments.length; i++) {
     fieldseq++;
     el = document.forms['NonStopGov']['p_' + fieldseq];
     var radioLength = el.length;
     if (el.type == 'checkbox') {
        if (arguments[i] != null && (arguments[i] == 'True' || arguments[i] == 'true' || 
                                     arguments[i] == 'Yes' || arguments[i] == 'YES' || arguments[i] == 'yes' || 
                                     arguments[i] == 'Y' || arguments[i] == 'y'))
           el.checked = true;
        }
     else if (el.type == 'radio' || (el.type == undefined && radioLength != undefined)) {
        if(arguments[i] != null)
           setRadioValue(el, arguments[i]);
        }
     else
        el.value = arguments[i];
     // Default to read only if requested
     if (readOnly != null && readOnly=='true')
        el.readOnly = true;
     else if (readOnly != null && readOnly=='false')
        el.readOnly = false;
     }
  closePopUp();
  el = document.forms['NonStopGov']['p_' + firstFieldSeq];
  if (el != null)
     el.focus();
  }

/* Functions to support tabs */
isNav = (navigator.appName.indexOf("Netscape") != -1) ? true : false;
isIE = (navigator.appName.indexOf("Microsoft") != -1) ? true : false;
isOpera = (navigator.appName.indexOf("Opera") != -1) ? true : false;

toplevel="4";

function dashChanges(num)
{
  toplevel++;
  var box = "box" + num;

  if (isIE)
  {
    document.all[box].style.zIndex = toplevel;
    i=1;
    for (i=1; i<10; i++)
    {
      var mytab="tab" + i;
      var cont="box" + i;
      if (document.all(mytab) == null)
         break;
      if (document.all(mytab).className == "tabselected") {
          document.all(mytab).className = "tabdisplayed";
          document.all[cont].className = "dashcontents";
          }
      if (document.all(mytab).className == "tabhidden" && i == num) 
      {
        dashChanges(1);
      }
      else if (i == num) 
      {
        document.all(mytab).className = "tabselected";
	document.all[cont].className = "dashcontentsselected";
      }
    }
  }
  if (isNav || isOpera)
  {
    document.getElementById(box).style.zIndex = toplevel;
    i=1;
    for (i=1; i<10; i++)
    {
      var mytab="tab" + i;
      var cont="box" + i;
      if (document.getElementById(mytab) == null)
         break;
      if (document.getElementById(mytab).className == "tabselected") {
         document.getElementById(mytab).className = "tabdisplayed";
         document.getElementById(cont).className = "dashcontents";
         }

      if (document.getElementById(mytab).className == "tabhidden" && i == num) 
      {
        dashChanges(1);
      }
      else if (i == num) 
      {
        document.getElementById(mytab).className = "tabselected";
	document.getElementById(cont).className = "dashcontentsselected";
      }
    }
  }
};

function DoChanges(num)
{
  if(panelUsed == "true")
  {
	closePanel();
  }

  toplevel++;
  var box = "box" + num;

  /* Store the last tab in a cookie */
  setCookie("lastTab", num);

  if (isIE && self.document.all[box] != null)
  { 
    self.document.all[box].style.zIndex = toplevel;
    i=1;
    for (i=1; i<12; i++)
    {
      var mytab="tab" + i;
      var cont="box" + i;
      if (self.document.all(mytab).className == "tabselected") {
          self.document.all(mytab).className = "tabdisplayed";
          self.document.all[cont].className = "contents";
          }
      if (self.document.all(mytab).className == "tabhidden" && i == num) 
      {
        DoChanges(1);
      }
      else if (i == num) 
      {
        self.document.all(mytab).className = "tabselected";
	self.document.all[cont].className = "contentsselected";
      }
    }
  }
  if ((isNav || isOpera) && self.document.getElementById(box) != null)
  {
    self.document.getElementById(box).style.zIndex = toplevel;
    i=1;
    for (i=1; i<12; i++)
    {
      var mytab="tab" + i;
      var cont="box" + i;
      if (self.document.getElementById(mytab).className == "tabselected") {
         self.document.getElementById(mytab).className = "tabdisplayed";
         self.document.getElementById(cont).className = "contents";
         }

      if (self.document.getElementById(mytab).className == "tabhidden" && i == num) 
      {
        DoChanges(1);
      }
      else if (i == num) 
      {
        self.document.getElementById(mytab).className = "tabselected";
	self.document.getElementById(cont).className = "contentsselected";
      }
    }
  }
};

function initialiseTab()
{
var num = getCookie("lastTab");
if (num == null)
    num == 1;
DoChanges(num);
if (num == 11)
   showGrid();
}

// Automatically attach a listener to the window onload, to convert the trees
addEvent(window,"load",convertTrees);

// Utility function to add an event listener
function addEvent(o,e,f){
	if (o.addEventListener){ o.addEventListener(e,f,true); return true; }
	else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
	else { return false; }
}

// utility function to set a global variable if it is not already set
function setDefault(name,val) {
	if (typeof(window[name])=="undefined" || window[name]==null) {
		window[name]=val;
	}
}

// Full expands a tree with a given ID
function expandTree(treeId) {
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	expandCollapseList(ul,nodeOpenClass);
}

// Fully collapses a tree with a given ID
function collapseTree(treeId) {
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	expandCollapseList(ul,nodeClosedClass);
}

// Expands enough nodes to expose an LI with a given ID
function expandToItem(treeId,itemId) {
	var ul = document.getElementById(treeId);
	if (ul == null) { return false; }
	var ret = expandCollapseList(ul,nodeOpenClass,itemId);
	if (ret) {
		var o = document.getElementById(itemId);
		if (o.scrollIntoView) {
			o.scrollIntoView(false);
		}
	}
}

// Performs 3 functions:
// a) Expand all nodes
// b) Collapse all nodes
// c) Expand all nodes to reach a certain ID
function expandCollapseList(ul,cName,itemId) {
	if (!ul.childNodes || ul.childNodes.length==0) { return false; }
	// Iterate LIs
	for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
		var item = ul.childNodes[itemi];
		if (itemId!=null && item.id==itemId) { return true; }
		if (item.nodeName == "LI") {
			// Iterate things in this LI
			var subLists = false;
			for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
				var sitem = item.childNodes[sitemi];
				if (sitem.nodeName=="UL") {
					subLists = true;
					var ret = expandCollapseList(sitem,cName,itemId);
					if (itemId!=null && ret) {
						item.className=cName;
						return true;
					}
				}
			}
			if (subLists && itemId==null) {
				item.className = cName;
			}
		}
	}
}

// Search the document for UL elements with the correct CLASS name, then process them
function convertTrees() {
	setDefault("treeClass","mktree");
	setDefault("nodeClosedClass","liClosed");
	setDefault("nodeOpenClass","liOpen");
	setDefault("nodeBulletClass","liBullet");
	setDefault("nodeLinkClass","bullet");
	setDefault("preProcessTrees",true);
	if (preProcessTrees) {
		if (!document.createElement) { return; } // Without createElement, we can't do anything
		uls = document.getElementsByTagName("ul");
		for (var uli=0;uli<uls.length;uli++) {
			var ul=uls[uli];
			if (ul.nodeName=="UL" && ul.className==treeClass) {
				processList(ul);
			}
		}
	}
}

// Process a UL tag and all its children, to convert to a tree
function processList(ul) {
	if (!ul.childNodes || ul.childNodes.length==0) { return; }
	// Iterate LIs
	for (var itemi=0;itemi<ul.childNodes.length;itemi++) {
		var item = ul.childNodes[itemi];
		if (item.nodeName == "LI") {
			// Iterate things in this LI
			var subLists = false;
			for (var sitemi=0;sitemi<item.childNodes.length;sitemi++) {
				var sitem = item.childNodes[sitemi];
				if (sitem.nodeName=="UL") {
					subLists = true;
					processList(sitem);
				}
			}
			var s= document.createElement("SPAN");
			var t= '\u00A0'; // &nbsp;
			s.className = nodeLinkClass;
			if (subLists) {
				// This LI has UL's in it, so it's a +/- node
				if (item.className==null || item.className=="") {
					item.className = nodeClosedClass;
				}
				// If it's just text, make the text work as the link also
				if (item.firstChild.nodeName=="#text") {
					t = t+item.firstChild.nodeValue;
					item.removeChild(item.firstChild);
				}
				s.onclick = function () {
					this.parentNode.className = (this.parentNode.className==nodeOpenClass) ? nodeClosedClass : nodeOpenClass;
					return false;
				}
			}
			else {
				// No sublists, so it's just a bullet node
				item.className = nodeBulletClass;
				s.onclick = function () { return false; }
			}
			s.appendChild(document.createTextNode(t));
			item.insertBefore(s,item.firstChild);
		}
	}
}

// Function to block the Enter key from submitting
function blockEnter() {
  return !(window.event && window.event.keyCode == 13); }

// Google maps function to show markers on top
function markerOnTop(marker,b) {
   return GOverlay.getZIndex(marker.getPoint().lat());
   }

function markerNotOnTop(marker,b) {
   return -GOverlay.getZIndex(marker.getPoint().lat());
   }

// Function to load Google maps for location selection purposes
var inPolygon = 'unknown';

function zoomMap(mapProvider, longitude, lat, zoom) {
   if(mapProvider == 'googleNativeR')
      map.setCenter(new GLatLng(lat, longitude), G_NORMAL_MAP.getMaximumResolution(), G_NORMAL_MAP);
   else if (mapProvider == 'googleNativeH')
      map.setCenter(new GLatLng(lat, longitude), G_HYBRID_MAP.getMaximumResolution(), G_HYBRID_MAP);
   else if(mapProvider == 'msNativeR') {
      map.SetMapStyle(VEMapStyle.Road);
      map.SetCenterAndZoom(new VELatLong(lat, longitude), parseInt(zoom));
      }
   else if(mapProvider == 'msNativeH') {
      map.SetMapStyle(VEMapStyle.Hybrid);
      map.SetCenterAndZoom(new VELatLong(lat, longitude), parseInt(zoom));
      }
   else if(mapProvider == 'msNativeB') {
      if (map.IsBirdseyeAvailable())
         map.SetMapStyle(VEMapStyle.Birdseye);
      map.SetCenterAndZoom(new VELatLong(lat, longitude), parseInt(zoom));
      }
   else 
      map.setCenter(new OpenLayers.LonLat(longitude, lat), zoom);
   }

function selectMapPoint(mapProvider, longitude, lat, zoom, dataURL, dataURLParams) {
  zoomMap(mapProvider, longitude, lat, zoom);
  var url = dataURL;
  var params = dataURLParams + '&long=' + longitude + '&lat=' + lat;
  var ajax = new Ajax.Updater(
                   {success: 'resultDiv'},
                   url,
                   {method: 'get', parameters: params, evalScripts: true, 
                    onFailure: '$("resultDiv").innerHTML = "Sorry. Our mapping facility does not support your browser. Please select an                                address using the Find Adress facility instead.");'});
  }

function getGMap(longitude, lat, zoom, dataURL, dataURLParams, allowSelect) {

   GEvent.clearListeners(map, 'click');
   GEvent.clearListeners(map, 'addoverlay');
   map.clearOverlays();

   if (parseInt(zoom) < 99)
      map.setCenter(new GLatLng(lat, longitude), parseInt(zoom), G_NORMAL_MAP);
   else if(mapType == 'R')
      map.setCenter(new GLatLng(lat, longitude), G_NORMAL_MAP.getMaximumResolution(), G_NORMAL_MAP);
   else if(mapType == 'H')
      map.setCenter(new GLatLng(lat, longitude), G_HYBRID_MAP.getMaximumResolution(), G_HYBRID_MAP);
 
   // Act upon click but not if not allowed...
   if (allowSelect) {
        GEvent.addListener(map, 'click', mapClick);
        GEvent.addListener(map, 'dblclick', onDoubleClick);
    }
    // This is to introduce the doubleclick zoom in functionality, but distiguish between two single clicks and double clicks
     function mapClick(overlay, point) 
         { 
           ++clickNumber;
         	 if (clickNumber == 1) 
         	 {
         			window.setTimeout(function() {	onSingleClick(overlay, point)},350);	
         	 }
         }
        function onDoubleClick(overlay, point)
			  {
            clickNumber = 2;
			  }
			  function onSingleClick(overlay, point)
			  {
			  
             if (point && clickNumber == 1) {
                var url = dataURL;
                var params = dataURLParams + '&long=' + point.x + '&lat=' + point.y;
                var ajax = new Ajax.Updater(
                   {success: 'resultDiv'},
                   url,
                   { method: 'get', parameters: params, evalScripts: true, 
                    onFailure: '$("resultDiv").innerHTML = "Sorry. Our mapping facility does not support your browser. Please select an address using the Find Adress facility instead.");'});
                }
               
             clickNumber = 0;
        }
        
}

// Act upon click but ignore if not allowed...
var birdseyeview = function() {
if ((parseInt(ezoom) == 99) && isBirdseye == true)
   {  if(map.GetMapStyle() != VEMapStyle.Birdseye)
	{  map.SetMapStyle(VEMapStyle.Birdseye);
      }
      map.SetZoomLevel(2);
      
   }
}

// Function to load Virtual Earth maps for location selection purposes
function getMSMap(longitude, lat, zoom, dataURL, dataURLParams, allowSelect) {

map.DeleteAllShapes();

   ezoom = zoom;
   if (parseInt(zoom) < 99)
    {  
	 map.SetMapStyle(VEMapStyle.Road);
       map.SetCenterAndZoom(new VELatLong(lat, longitude), parseInt(zoom));
    }
   else if (map.IsBirdseyeAvailable() && isBirdseye == true)
   { 
      map.SetCenterAndZoom(new VELatLong(lat, longitude), 17);
	if(map.GetMapStyle() != VEMapStyle.Birdseye) 
	{  
         map.SetMapStyle(VEMapStyle.Birdseye);
         map.SetCenterAndZoom(new VELatLong(lat, longitude), 2);
      }
   }
   else
   {  if(mapType == 'H')
	map.SetMapStyle(VEMapStyle.Hybrid);
	else if(mapType == 'R')
		map.SetMapStyle(VEMapStyle.Road);
      map.SetCenterAndZoom(new VELatLong(lat, longitude), 19);
   }

   if (allowSelect) {
	map.DetachEvent('onclick', ajaxMapClick);
	map.DetachEvent('onclick', formUpdate);
	if(kmlUrl != null && kmlUrl != '')
	{
		var shapeLayer = new VEShapeLayer();
		var shapeSpec = new VEShapeSourceSpecification(VEDataType.ImportXML,kmlUrl, shapeLayer);     
		map.ImportShapeLayerData(shapeSpec, null, false);
	}
      ajaxMapClick = function(e) 
       {
var x = e.mapX;  var y = e.mapY; pixel = new VEPixel(x, y); latLon = map.PixelToLatLong(pixel);
          if (latLon && diff < 300) 
          { 
		if((map.GetMapStyle() == VEMapStyle.Birdseye) && isBirdseye == true) {	   
			map.SetMapStyle(VEMapStyle.Hybrid);
			map.SetZoomLevel(17); 
                       latLon = map.PixelToLatLong(pixel);
		}

             var url = dataURL;
             var params = "";
		if(isBirdseye == true)
		{
              params = dataURLParams + '&long=' + latLon.Longitude + '&lat=' + latLon.Latitude;
	
		}
		else //if (map.GetMapStyle() == VEMapStyle.Hybrid)
		{
		  params = dataURLParams + '&long=' + latLon.Longitude + '&lat=' + latLon.Latitude;
		}
             var ajax = new Ajax.Updater(
                {success: 'resultDiv'},
                url,
                {method: 'get', parameters: params, evalScripts: true, onFailure: '$("resultDiv").innerHTML = "Sorry. Our mapping facility does not support your browser. Please select an address using the Find Address facility instead.");'});

          }

        };
      }
	map.AttachEvent('onclick', ajaxMapClick);
   }


// Function to load Google maps for location selection purposes
function loadGMapSelect(initLong, 
                        initLat, 
                        initZoom, 
                        initAddressId, 
                        dataURL, 
                        dataURLParams,
                        allowSelect,
                        streetFunction) {

   if (initAddressId) {
             var url = dataURL;
             var params = dataURLParams;
             if (initAddressId != 'POINT')
                 params = params + '&AddressId=' + initAddressId;
             else
                 params = params + '&long=' + initLong + '&lat=' + initLat;
             var ajax = new Ajax.Updater(
                {success: 'resultDiv'},
                url,
                {method: 'get', parameters: params, evalScripts: true, onFailure: '$("resultDiv").innerHTML = "Sorry. Our mapping facility does not support your browser.");'});
             }

   else {
      getGMap(initLong, initLat, initZoom, dataURL, dataURLParams, allowSelect);
      if (streetFunction) {
         var t_function = streetFunction;
         t_function(map);
         }
      }

   }

function ajaxRequest1(p_url, p_paras) {
             var ajax = new Ajax.Updater(
                {success: 'resultDiv1'},
                p_url,
                {method: 'get', parameters: p_paras, evalScripts: true, onFailure: '$("resultDiv1").innerHTML = "Sorry. We were unable to complete your request");'});
       }

function ajaxRequest2(p_url, p_paras) {
             var ajax = new Ajax.Updater(
                {success: 'resultDiv2'},
                p_url,
                {method: 'get', parameters: p_paras, evalScripts: true, onFailure: '$("resultDiv2").innerHTML = "Sorry. We were unable to complete your request");'});
       }

// Function to load Virtual Earth maps for location selection purposes
function loadMSMapSelect(initLong, 
                        initLat, 
                        initZoom, 
                        initAddressId, 
                        dataURL, 
                        dataURLParams,
                        allowSelect,
                        streetFunction) {
   if (initAddressId) {
             var url = dataURL;
             var params = dataURLParams;
             if (initAddressId != 'POINT')
		    params = params + '&AddressId=' + initAddressId;
             else
                params = params + '&long=' + initLong + '&lat=' + initLat;
	 
             var ajax = new Ajax.Updater(
                {success: 'resultDiv'},
                url,
                {method: 'get', parameters: params, evalScripts: true, onFailure: '$("resultDiv").innerHTML = "Sorry. Our mapping facility does not support your browser.");'});
       }

   else {
      getMSMap(initLong, initLat, initZoom, dataURL, dataURLParams, allowSelect);
      if (streetFunction) {
         var t_function = streetFunction;
         t_function(map);
         }
      }

   }

// Function to load WMS maps for location selection purposes
function loadWMSMapSelect(map,
                        initLong, 
                        initLat, 
                        initZoom, 
                        initAddressId, 
                        dataURL, 
                        dataURLParams,
                        allowSelect,
                        streetFunction) {

   if (initAddressId) {
             var url = dataURL;
             var params = dataURLParams;
             if (initAddressId != 'POINT')
                 params = params + '&AddressId=' + initAddressId;
             else
                 params = params + '&long=' + initLong + '&lat=' + initLat;
             var ajax = new Ajax.Updater(
                {success: 'resultDiv'},
                url,
                {method: 'get', parameters: params, evalScripts: true, onFailure: '$("resultDiv").innerHTML = "Sorry. Our mapping facility does not support your browser.");'});
       }

   else {

      map.setCenter(new OpenLayers.LonLat(initLong, initLat), initZoom); 

      // Act upon click but not if no data url
      if (allowSelect) {
        map.events.register('click', map, function(e) {
             var lonlat = map.getLonLatFromViewPortPx(e.xy);
             var url = dataURL;
             var params = dataURLParams + '&long=' + parseNumber(lonlat.lon, 8).toString() + '&lat=' + parseNumber(lonlat.lat, 8).toString();
             var ajax = new Ajax.Updater(
                {success: 'resultDiv'},
                url,
                {method: 'get', parameters: params, evalScripts: true, onFailure: '$("resultDiv").innerHTML = "Sorry. Our mapping facility does not support your browser. Please select an address using the Find Adress facility instead.");'});
             }
          );
        }

      if (streetFunction) {
         var t_function = streetFunction;
         t_function(map);
         }
      }

   }

var timerID = 0;
var timerStartMillisecs;
 
function initialiseTimer(startsecs) {
  timerStartMillisecs = 0;
  if (startsecs)
      timerStartMillisecs = startsecs * 1000;
  setTimer(false);
}

function setTimer(increment) {

  if(timerID) {
     clearTimeout(timerID);
     timerID  = 0;
     }

  var tInterval = getCookie("lastContactInterval");
  if(!tInterval)
     tInterval   = 1000;
  else
     tInterval = tInterval/1;




  var   tNow = new Date();
  var   tStart = new Date();
  var   tDisplay = new Date();
  tStart.setTime(tNow.getTime()-tInterval);
  tDisplay.setTime(timerStartMillisecs + tInterval);

  if (increment) {
     tInterval = tInterval/1 + 1000;
     setCookie("lastContactInterval", tInterval);
     }

  if ((document.theTimer != null) && (document.theTimer.theTime != null)) {
     if (tDisplay.getSeconds() <= 9)
          document.theTimer.theTime.value = "" + tDisplay.getMinutes() + ":0" + tDisplay.getSeconds();
     else
          document.theTimer.theTime.value = "" + tDisplay.getMinutes() + ":" + tDisplay.getSeconds();
     if (tDisplay.getHours() > 0)
          document.theTimer.theTime.value = "" + tDisplay.getHours() + ":" + document.theTimer.theTime.value;
     }

  timerID = setTimeout("setTimer(true)", 1000);
}
 
 
function clearTimer() {
   if(timerID) {
      clearTimeout(timerID);
      timerID  = 0;
   }
 
   setCookie("lastContactInterval", 0);
}

function disableButtons(fieldName) {
var thisField = fieldName;
for (i = 0; i < thisField.form.length; i++) {
  var tempobj = thisField.form.elements[i]; 
  if (tempobj.type.toLowerCase() == 'submit' ||  
      tempobj.name.toLowerCase() == 'gotopage' || 
      tempobj.type.toLowerCase() == 'reset') 
        tempobj.disabled = true;
  }
}

/* exclude submit and buttons from form paras */
function getSelectedFormParas()
{
   var paras = Form.serialize($('NonStopGov'));
   var elements = Form.getElements($('NonStopGov')); 
   for (var i = 0; i < elements.length; i++) { 
       var element = $(elements[i]); 
       var origvalue = element.name+'=';
       var newvalue = 'x_'+element.name+'=';
       if (element.type.toLowerCase() == 'button' || element.type.toLowerCase() == 'submit')
          paras = paras.replace(origvalue, newvalue);

       }
   return paras;
}

/* code for displaying yahoo panels */
function panelInit() { 
   panelUsed = "true";
YAHOO.nsg.container.panel = new YAHOO.widget.Panel("panel", 
          {visible: false, constraintoviewport: true, zIndex : 99, underlay: "none",
           effect: {effect:YAHOO.widget.ContainerEffect.FADE, duration:0.25}});
				
}

function calInit() {
YAHOO.nsg.container.calendar = new YAHOO.widget.Calendar("calendar","calContainer",{navigator: true});
YAHOO.nsg.container.calPanel = new YAHOO.widget.Panel("calPanel", 
          {visible: false, width: "180px", height: "220px", draggable: true, constraintoviewport: true, zIndex : 99, underlay: "none",
           effect: {effect:YAHOO.widget.ContainerEffect.FADE, duration:0.25}});				
YAHOO.nsg.container.calendar.render();
YAHOO.nsg.container.calPanel.render();
YAHOO.nsg.container.calPanel.hide();
YAHOO.nsg.container.calendar.selectEvent.subscribe(handleSelect, YAHOO.nsg.container.calendar, true);
}

function handleSelect(type,args,obj) {
var dates = args[0]; 
var date = dates[0];
var year = date[0], month = date[1], day = date[2];

if(dateFormat == 'US')
  document.getElementById(calDate).value = month + "/" + day + "/" + year;
else
  document.getElementById(calDate).value = day + "/" + month + "/" + year;
  
validateField(document.getElementById(calDate), 'DATE');
if(typeof resetAllItems == 'function') { 
resetAllItems(); 
} 
YAHOO.nsg.container.calendar.hide();
YAHOO.nsg.container.calPanel.hide();
}


function XYPos(e) {
   YAHOO.nsg.container.panel.cfg.setProperty("xy", [YAHOO.util.Event.getPageX(e),YAHOO.util.Event.getPageY(e)]);
   YAHOO.nsg.container.panel.show();
   }

function closePanel(e) {
   YAHOO.nsg.container.panel.hide();
   }

function ScreenXY(e) {
   if (typeof(window.innerWidth) == 'number') {
      var height = window.innerHeight * 0.75;
      height = height + "px";
      var width = "90%";
      YAHOO.nsg.container.panel.cfg.setProperty("width", width);
      YAHOO.nsg.container.panel.cfg.setProperty("height",height);
      YAHOO.nsg.container.panel.cfg.setProperty("overflow", "visible");
      }
   else if (document.documentElement && 
           (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
	   YAHOO.nsg.container.panel.cfg.setProperty("width",'90%');
           YAHOO.nsg.container.panel.cfg.setProperty("height", document.documentElement.clientHeight*0.75);
           YAHOO.nsg.container.panel.cfg.setProperty("overflow", "visible");
           }
   else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
	   YAHOO.nsg.container.panel.cfg.setProperty("width",'90%');
           YAHOO.nsg.container.panel.cfg.setProperty("height", document.body.clientHeight*0.75);
           YAHOO.nsg.container.panel.cfg.setProperty("overflow", "visible");
           }	
   } 

function correctPNG() 
{   var arVersion = navigator.appVersion.split("MSIE")   
    var version = parseFloat(arVersion[1])   
    if ((version >= 5.5) && (document.body.filters))   
    {  for(var i=0; i<document.images.length; i++)      
       {   var img = document.images[i]         
           var imgName = img.src.toUpperCase()         
           if (imgName.substring(imgName.length-3, imgName.length) == "PNG" && imgName.indexOf('/ICON') > -1)        
           {  var imgID = (img.id) ? "id='" + img.id + "' " : ""            
              var imgClass = (img.className) ? "class='" + img.className + "' " : ""            
              var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "            
              var imgStyle = "display:inline-block;" + img.style.cssText            
              if (img.align == "left") imgStyle = "float:left;" + imgStyle            
              if (img.align == "right") imgStyle = "float:right;" + imgStyle            
              if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle            
              var strNewHTML = "<span " + imgID + imgClass + imgTitle            
                               + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"            
                               + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"            
                               + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"            
                                img.outerHTML = strNewHTML            
					  i = i-1         
           }      
       }   
    }
 }

function resetSlots(sessions, session, seqnum, appointmentSlots)
{

      var output = true;
      k = 1;
      l = 0;
      if(current_session == "")
           current_session = session;

	allObjs = document.getElementsByTagName('input');
	for(i=0; i<allObjs.length; i++) 
	{ 
             if((current_session != session) || appointmentSlots > 1) // if the focus is on a different location
             {
		     if(allObjs[i].type == 'checkbox' && allObjs[i].id == session && allObjs[i].value == seqnum)
		     {	
		         allObjs[i].checked = true; // uncheck everything except the selected one
                     	
		     } 
		     else if (allObjs[i].type == 'checkbox' && allObjs[i].disabled == false)
		     {
			   allObjs[i].checked = false; // uncheck everything except the selected one
		     }
                       
            }
            
	}
       while(appointmentSlots > 1 && k < appointmentSlots && l < allObjs.length) // to choose consecutive slots automatically
       	{
           if(allObjs[l].type == 'checkbox' && allObjs[l].id == session && allObjs[l].name == 'sessionSeq' + (seqnum + k))
	   {   
 	       	if(allObjs[l].disabled == true) // if there are existing bookings along the way, then warn.
		{
			alert('Could not select required consecutive slots');
                        output = false;
                        break;
                }
	       	else 
               	{
               		allObjs[l].checked = true;
	        	k++;
		}
           }
        
	 l++;
        }
	if(k < appointmentSlots && output) // if reached end of slots for location
	{
		alert('No further slots available for this date and location');
        }

	if(current_session != session)
     current_session = session;

}

function requiredItems()
{
      var inform = "";

      allObjs = document.getElementsByTagName('select');
	for(i=allObjs.length-1; i>=0; i--) 
	{ 
	   if(allObjs[i].id.indexOf('required') > 0)
         { if(allObjs[i].value == '')
	     {	
		   inform = allObjs[i];
	     }
         }
	}	

     if(inform == "")
     {
       allObjs = document.getElementsByTagName('textarea');
 	 for(i=allObjs.length-1; i>=0; i--) 
	 { 
	   if(allObjs[i].id.indexOf('required') > 0)
         { if(allObjs[i].value == '')
	     {	
		   inform = allObjs[i];
	     }
         }
	 }
     }

     if(inform == "")
     {
       allObjs = document.getElementsByTagName('input');
	 for(i=allObjs.length-1; i>=0; i--) 
	 { 
	   if(allObjs[i].id.indexOf('required') > 0)
         { if(allObjs[i].value == '')
	     {	
               inform = allObjs[i];
	     }
	     }
       }
     }

	if(inform != "")
	{
	    inform.focus();
	    alert('This field must be specified');
	    return false;
	}

}


function hideEl(id) {
	//safe function to hide an element with a specified id
	if (document.getElementById(id))
	    document.getElementById(id).style.display = 'none';
	else if (document.id != null) {
		if (document.layers) // Netscape 4
		   document.id.display = 'none';
		else // IE 4
		   document.all.id.style.display = 'none';
		}
	}

function showEl(id) {
	//safe function to show an element with a specified id	  
	if (document.getElementById(id))
	    document.getElementById(id).style.display = 'inline';
	else if (document.id != null) {
		if (document.layers) // Netscape 4
		   document.id.display = 'inline';
		else // IE 4
		   document.all.id.style.display = 'inline';
		}
	}

// Have to do this to ensure focus
function FCKeditor_OnComplete(fckEditor)
{
  fckEditor.EditorWindow.focus();
  fckEditor.Focus();
}

var tl;
function onLoadTimeline(pxmlUrl, pStart, pUnit) {
            var eventSource = new Timeline.DefaultEventSource();
            var theme = Timeline.ClassicTheme.create();
            theme.event.label.width = 500;
            theme.event.bubble.width = 300; 
            theme.event.bubble.height = 95; 
            var bandInfos;
            if (pUnit && pUnit == "DAY")
               bandInfos = [  
                          Timeline.createBandInfo(
                          { showEventText: false,
                            eventSource:    eventSource,
                            date: pStart, 
                            width: "20%", 
                            intervalUnit: Timeline.DateTime.DAY, 
                            intervalPixels: 50,
                            theme: theme })
                          ,
                          Timeline.createBandInfo(
                          { eventSource:    eventSource, 
                            date: pStart, 
                            width: "80%", 
                            intervalUnit: Timeline.DateTime.HOUR, 
                            intervalPixels: 40,
                            theme: theme })
                        ]; 
            else
               bandInfos = [ 
                          Timeline.createBandInfo(
                          { showEventText: false,
                            eventSource:    eventSource,
                            date: pStart, 
                            width: "20%", 
                            intervalUnit: Timeline.DateTime.WEEK, 
                            intervalPixels: 50,
                            theme: theme })
                          ,
                          Timeline.createBandInfo(
                          { eventSource:    eventSource, 
                            date: pStart, 
                            width: "80%", 
                            intervalUnit: Timeline.DateTime.DAY, 
                            intervalPixels: 100,
                            theme: theme })
                        ]; 
  
            bandInfos[0].syncWith = 1;
            bandInfos[1].highlight = true;
            
            tl = Timeline.create(document.getElementById("tl"), bandInfos, Timeline.HORIZONTAL);
            tl.loadXML(pxmlUrl, function(xml, url) { eventSource.loadXML(xml, url); });
            }

var resizeTimerID = null;
function onResize() {
            if (resizeTimerID == null) {
                resizeTimerID = window.setTimeout(function() {
                    resizeTimerID = null;
                    tl.layout();
                }, 500);
            }
        }

 var markerClick = function (evt) {
                if (this.popup == null) {
                    this.popup = this.createPopup(true);
                    map.addPopup(this.popup);
                    this.popup.show();
                } else {
                    this.popup.toggle();
                }
                currentPopup = this.popup;
                OpenLayers.Event.stop(evt);
            };

function setMarker(ll, popupClass, popupContentHTML, icon, t_rowno, overflow) {

            markerFeature = new OpenLayers.Feature(markersLayer, ll); 
            markerFeature.closeBox = true;
            markerFeature.popupClass = popupClass;
            markerFeature.data.popupContentHTML = popupContentHTML;
            markerFeature.data.overflow = (overflow) ? "auto" : "hidden";
          
        }

function LocationHandler(p) {
         window.location = window.location + "&lat=" + p.coords.latitude + "&long=" + p.coords.longitude;
         return true;
         }

function appendLocation() {
         // test to see if the location API is supported
         if (geo_position_js.init())
            geo_position_js.getCurrentPosition(LocationHandler, null);
         }

function getBrowserLocation(p_loki_key) {
  if (geo_position_js.init())
     geo_position_js.getCurrentPosition(useBrowserLocation, null);
  else if (p_loki_key != null) {
     var loki = new LokiAPI();
     loki.onSuccess = function(location) {
         useBrowserLocation(location.longitude, location.latitude);
         };
     loki.onFailure = function(error, msg) {alert('Sorry. We are unable to establish your current location');};
     loki.setKey(p_loki_key);
     loki.requestLocation(true,loki.NO_STREET_ADDRESS_LOOKUP);
     }
  }

var postcode = '';
var country = '';
var baseUrl='';
var account_code='';
var license_code='';
var machine_id='';
var item_seq = 0; 
var nsg_city = new Array();
var nsg_state= new Array();
var nsg_postcode = new Array();
var nsg_addr = new Array();

function pcaByPostcodeBegin(p_country, p_item_seq, p_account_code, p_license_code, p_machine_id)
   {
      postcode = document.getElementById("selectpostcode").value;
      item_seq=p_item_seq+2;
      country = p_country;
      account_code=p_account_code;
      license_code=p_license_code;
      machine_id=p_machine_id;
      var scriptTag = document.getElementById("pcaScriptTag");
      var headTag = document.getElementsByTagName("head").item(0);
      var strUrl = "";
      
      document.getElementById("divLoading").style.display = '';
      
      //Build the url
      strUrl = "http://services.postcodeanywhere.co.uk/inline.aspx?postcode=" + escape(postcode);
      if (country && country == "GB") {
          strUrl += "&action=" + escape("lookup");
          strUrl += "&type=" + escape("by_postcode");
          }
      else {
          strUrl += "&action=" + escape("international");
          strUrl += "&type=" + escape("fetch_streets");
          strUrl += "&country=" + escape(country);
          }
      strUrl += "&account_code=" + escape(account_code);
      strUrl += "&license_code=" + escape(license_code);
      strUrl += "&machine_id=" + escape(machine_id);
      strUrl += "&callback=pcaByPostcodeEnd";
      
      //Make the request
      if (scriptTag)
         {
            //The following 2 lines perform the same function and should be interchangeable
            headTag.removeChild(scriptTag);
            //scriptTag.parentNode.removeChild(scriptTag);
         }
      scriptTag = document.createElement("script");
      scriptTag.src = strUrl
      scriptTag.type = "text/javascript";
      scriptTag.id = "pcaScriptTag";
      headTag.appendChild(scriptTag);
   }

function pcaByPostcodeEnd()
   {
	document.getElementById("divLoading").style.display = 'none';
	  
      //Test for an error
      if (pcaIsError)
         {
            //Show the error message
            document.getElementById("selectaddress").style.display = 'none';
            alert(pcaErrorMessage);
         }
      else
         {
            //Check if there were any items found
            if (pcaRecordCount==0)
               {
                  document.getElementById("selectaddress").style.display = 'none';
                  alert("Sorry, no matching items found. Please try another postcode.");
               }
            // Uk lookup
            else if (country && country == "GB")
               {
                  document.getElementById("selectaddress").style.display = 'none';
                  if (pcaRecordCount < 2)
               	     document.getElementById("selectaddress").size = 2;
                  else if (pcaRecordCount > 6)
               	     document.getElementById("selectaddress").size = 6;
		  else
	             document.getElementById("selectaddress").size = pcaRecordCount;
		  document.getElementById("selectaddress").style.display = '';
		  for (i=document.getElementById("selectaddress").options.length-1; i>=0; i--) {
			document.getElementById("selectaddress").options[i] = null;
			}
		  for (i=0; i<pca_id.length; i++) {
			document.getElementById("selectaddress").options[document.getElementById("selectaddress").length] = new Option(pca_description[i], pca_id[i]);
                        }
               }
            // Other countries street lookup
            else
               {
               document.getElementById("selectaddress").style.display = 'none';
                  if (pcaRecordCount < 2)
                  {
                     var addr = pca_street[0];
                     if (pca_district[0] != null)
                        addr += "\n" + pca_district[0];
               document.getElementById("p_"+item_seq).value=addr;
               item_seq = item_seq + 1;
                     document.getElementById("p_"+item_seq).value=pca_city[0];
               item_seq = item_seq + 1;
                     document.getElementById("p_"+item_seq).value=pca_state[0];
               item_seq = item_seq + 1;
                     document.getElementById("p_"+item_seq).value=pca_postcode[0];
                   
                     document.getElementById("selectaddress").size = 2;
                     return false;
               }
                  else if (pcaRecordCount > 6)
               	     document.getElementById("selectaddress").size = 6;
                  else
                     document.getElementById("selectaddress").size = pcaRecordCount;
                     document.getElementById("selectaddress").style.display = '';
                   for (i=document.getElementById("selectaddress").options.length-1; i>=0; i--) {
                               document.getElementById("selectaddress").options[i] = null;
          }
          // null out the old values when doing a re-search
          nsg_city = new Array();
          nsg_state= new Array();
          nsg_postcode = new Array();
          nsg_addr = new Array();
          
                  for (i=0; i<pca_street.length; i++) {
                    
                   var option_addr = pca_street[i];
                   
                    if (pca_district[i] != null && pca_district[i] != '')
                       option_addr += ", " + pca_district[i];
                        
                    document.getElementById("selectaddress").options[document.getElementById("selectaddress").length] = new Option(option_addr, "p_"+i);
                    
                    var addr = pca_street[i];
                    if (pca_district[i] != null)
                        addr += "\n" + pca_district[i];
                        
                    nsg_addr[i] = addr;
                    nsg_city[i] = pca_city[i];
                    nsg_state[i] = pca_state[i];
                    nsg_postcode[i] = pca_postcode[i];
   }

               }
          }
   }

function pcaFetchBegin(p_country)
   {
   
      country = p_country;
      if (country && country == "GB")
   {
      var address_id = document.getElementById("selectaddress").value;
      var scriptTag = document.getElementById("pcaScriptTag");
      var headTag = document.getElementsByTagName("head").item(0);
      var strUrl = "";

      //Build the url
      strUrl = "http://services.postcodeanywhere.co.uk/inline.aspx?action=fetch";
      strUrl += "&id=" + escape(address_id);
      strUrl += "&account_code=" + escape(account_code);
      strUrl += "&license_code=" + escape(license_code);
      strUrl += "&machine_id=" + escape(machine_id);
      strUrl += "&callback=pcaFetchEnd";

      //Make the request
      if (scriptTag)
         {
            //The following 2 lines perform the same function and should be interchangeable
            headTag.removeChild(scriptTag);
            //scriptTag.parentNode.removeChild(scriptTag);
         }
      scriptTag = document.createElement("script");
      scriptTag.src = strUrl
      scriptTag.type = "text/javascript";
      scriptTag.id = "pcaScriptTag";
      headTag.appendChild(scriptTag);
      }
      else
      {
          var street_id = document.getElementById("selectaddress").value;
          street_id = street_id.substring(2, street_id.length);
      
          document.getElementById("p_"+item_seq).value=nsg_addr[street_id];
          item_seq = item_seq + 1;
          document.getElementById("p_"+item_seq).value=nsg_city[street_id];
          item_seq = item_seq + 1;
          document.getElementById("p_"+item_seq).value=nsg_state[street_id];
          item_seq = item_seq + 1;
          document.getElementById("p_"+item_seq).value=nsg_postcode[street_id];
      }
      document.getElementById("selectaddress").style.display = 'none';
      
   }

function pcaFetchEnd()
   {
      //Test for an error
      if (pcaIsError)
         {
            //Show the error message
            alert(pcaErrorMessage);
         }
      else
         {
            //Check if there were any items found
            if (pcaRecordCount==0)
               {
                  alert("Sorry, no matching items found");
               }
            else if (country && country == "GB")
               {
      		 var addr = pca_line1[0];
                   if (pca_line2[0] != null)
                      addr += "\n" + pca_line2[0];
                   if (pca_line3[0] != null)
                      addr += "\n" + pca_line3[0];
                   document.getElementById("p_"+item_seq).value=addr;
                   item_seq = item_seq + 1;
                   document.getElementById("p_"+item_seq).value=pca_post_town[0];
                   item_seq = item_seq + 1;
                   document.getElementById("p_"+item_seq).value=pca_county[0];
                   item_seq = item_seq + 1;
                   document.getElementById("p_"+item_seq).value=pca_postcode[0];
               }
         }
   }

/* Frame resize function - to be called from within the frame after its been loaded. Does not work for chrome currently */
function resizeFrame(frameId)
{
  var docHt = 0;
  if (self.parent.document.getElementById(frameId)) {
     if (self.parent.document.getElementById(frameId).contentDocument && self.parent.document.getElementById(frameId).contentDocument.documentElement) {
        docHt = self.parent.document.getElementById(frameId).contentDocument.documentElement.scrollHeight + 40;
        if (!docHt || docHt < 400 || docHt == "undefined") docHt = 600;
        self.parent.document.getElementById(frameId).style.height = docHt + 'px';
        }
     else if (self.parent.document.getElementById(frameId).Document && self.parent.document.getElementById(frameId).Document.body && self.parent.document.getElementById(frameId).Document.body.scrollHeight) {
        docHt = self.parent.document.getElementById(frameId).Document.documentElement.scrollHeight + 10;
        if (!docHt || docHt <400 || docHt == "undefined") docHt = 600;
        self.parent.document.getElementById(frameId).style.height = docHt + 'px';
        }
     }
}
