//
// userManagement.js
//
// Author: Susan Brindley
// Created: 26/07/2004
// Version: 1.8
//
// PURPOSE
// -------
// Holds all of the JavaScript functions used in the registration pages.
//
// 
// HISTORY
// -------
// 26/07/2004 1.0 SB	File Created by extracting all existing registration 
//                    JavaScript functions and collecting them in this file.
// 23/09/2004	1.1	SB	Removed validation for mail address from testAndSubmitChange
//										following removal of mail field from the change form.
// 02/11/2004	1.2	SB 	Various bug fixes for form validation. Bug fix for change
//										form to create a virtual form that is used to submit just 
//										changed fields.
// 30/11/2004	1.3	SB	Changes to reflect request from Alan Thompson and Simon
//										Wardrobe to prevent users from changing their names online.
//										Removed mustfillin calls in testAndSubmitChange for cn and sn.
// 03/12/2004	1.4	SB	Added in changes to test for correct values for pensionnumber
//										and employeenumber.
// 13/12/2004	1.5	SB	Added in changes to remove leading zeros from pensionnumber
//										and employeenumber. Only remove leading zeros from employeenumber
//										if the employeenumber is a number (i.e. isNaN returns false)
// 11/03/2005 1.6 RHC Included validation for password to be alphanumeric
//
// 15/06/2005 1.7 RHC Amended the DOB code to work properly in any timezone
//
// 22/02/2006 1.8 RHC Include leading zeros in pensionnumber and employeenumber.
//                    These fields are uniformly 6 characters in the Pension Data,
//                    unless the employee number ends in X (7 characters).

ns6 = (document.getElementById)? true:false
ns4 = (document.layers)? true:false
ie4 = (document.all)? true:false

// GLOBALS
// *******
// GLOBAL ARRAYS FOR DATE HANDLING
var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var monthName = new Array("January","February","March","April","May","June",
                          "July","August","September","October","November",
                          "December");
var changedFields = new Array();


// ****************************************************************************
// GENERAL FUNCTIONS
// ****************************************************************************

// *********
// getObject
// *********
// INPUTS
//  name        the name or ID for an object
//
// OUTPUTS
//	objectRef   a reference to the object identified by name
//
// PURPOSE
//  Returns the object referenced by name.
//	
//  
function getObject(name)
{
	if (ie4)
		return document.all[name];
	else if (ns6)
		return document.getElementById(name);
	else
		return document.layers[name];
}


// ****************************************************************************
// LOGIN PAGE FUNCTIONS
// ****************************************************************************

// ************
// submitForm
// ************
// INPUTS
//  formObject	the object that represents the form that is being submitted
//
// OUTPUTS
//	NONE
//
// PURPOSE
//  Submits the login form.
//	
//  
function submitForm(formName)
{
	var formObject =  document.forms[formName];
	
	formObject.submit(); 
}


// ****************************************************************************
// REGISTRATION PAGE FUNCTIONS
// ****************************************************************************

// **********
// mustfillin
// **********
// INPUTS
//  field       the name or ID for a form input object
//
// OUTPUTS
//	boolean     true - means the form object has a value
//              false - means that the form object has no value
//
// PURPOSE
//  Tests that the form object supplied by field has a value.
//	
//  
function mustfillin(field) 
{
	var fieldValue = field.value;
	var fieldType = field.type;
	
	if ( ( fieldValue == null ) || ( fieldValue == '' ) || ( fieldValue.length == 0 ) )
  {
    alert ("Please complete all required fields.\n* denotes a required field.");
    //alert('Field name [' + field.name + '] Field type [' + fieldType + ']' );
    return false ;
  }
  else
    return true ;
}

// ***************
// mustfillinRadio
// ***************
// INPUTS
//  formObject		the name or ID for a form input object
//
// OUTPUTS
//	boolean     	true - means the form object has a value
//              	false - means that the form object has no value
//
// PURPOSE
//  Tests that the form radio object supplied by field has a value.
//	
//  
function mustfillinRadio(formObject) 
{
	var fieldValue = '';

	for (var i=0; i < formObject.length; i++)
	{
		if (formObject[i].checked)
	  {
	  	fieldValue = formObject[i].value;
    	//alert('Field name [' + formObject[i].name + '] Field type [' + formObject[i].type + ']' );
	  }
	}
	
	if ( formObject[0].name == 'bitsbytes' )
	{
		if ( ( fieldValue == null ) || ( fieldValue == '' ) || ( fieldValue.length == 0 ) )
	  {
	    alert ("Please enter a value for the Bits and Bytes newsletter option.");
	   	//alert('Field name [' + formObject[0].name + '] Field type [' + formObject[0].type + ']' );
	    return false ;
	  }
	  else
	  {
	  	return true;
	  }
	}
	else if ( ( fieldValue == null ) || ( fieldValue == '' ) || ( fieldValue.length == 0 ) )
  {
    alert ("Please complete all required fields.\n* denotes a required field.");
   	//alert('Field name [' + formObject[0].name + '] Field type [' + formObject[0].type + ']' );
    return false ;
  }
  else
    return true ;
}

// **************
// checkPasswords
// **************
// INPUTS
//  fieldPassword         the form password field
//  fieldPasswordConfirm  the form password confirm field
//
// OUTPUTS
//	boolean     true - means that the password value and the confirmation 
//                password value match
//              false - means that the password value and the confirmation 
//                password value do not match
//
// PURPOSE
//  Tests that the values supplied for the password and the confirmation 
//  password match.
//	
//  
function checkPasswords( fieldPassword, fieldPasswordConfirm)
{
	//alert('fieldPassword [' + fieldPassword + '] fieldPassword.value [' + fieldPassword.value + ']');
	//alert('fieldPasswordConfirm [' + fieldPasswordConfirm + '] fieldPasswordConfirm.value [' + fieldPasswordConfirm.value + ']');
	
	var patternMatch = false;
	var numberCharSet = "0123456789";
	var alphaCharSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var validPasswordChars = numberCharSet + alphaCharSet;

	if (fieldPassword.value != fieldPasswordConfirm.value)
	{
		alert("The values input for the password and confirm password must be identical");
		return false;
	}
	
	if (fieldPassword.value.length<6)
	{
		alert("The password must contain at least 6 characters.");
		return false;		
	}
  
  patternMatch = testValidChars(fieldPassword.value,validPasswordChars);  
	if (patternMatch == false)
	{
		alert("The password must only contain alphanumeric characters");
		return false;		
	}

	return true;
}

// ************
// processEmail
// ************
// INPUTS
//  formObject	the object that represents the form that is being submitted
//
// OUTPUTS
//	boolean     true - means that the email address was valid
//              false - means that the email address was invalid
//
// PURPOSE
//  Tests that a valid email address has been supplied and then sets the
// $reserved_email form field that is used by the PostAckMsgLogic class to
// send messages out to the user.
//	
//  
function processEmail( formObject )
{
	var emailOK = false;
	
	emailOK = checkEmail ( formObject.mail );
	
	if ( emailOK )
	{
		if (formObject.mail.value != formObject.mailConfirm.value)
		{
			alert("The values input for the E-mail address and confirm E-mail address must be identical");
			emailOK = false;
		}
		else
		{
			// set the $reserved_email value
			formObject.$reserved_email.value = formObject.mail.value;
			//alert("Set $reserved_email [" + formObject.$reserved_email.value + "]");
		}
	}


	return ( emailOK );
}


// *******************
// testAndSubmitChange
// *******************
// INPUTS
//	formName				the DOM name of the form that the user has entered data on.
//
// OUTPUTS
//	NONE
//
// PURPOSE
//  Performs all of the testing of the form. If all of the tests are successful
//  then the form is submitted.
//	
//  
function testAndSubmitChange(formName) 
{

	var formObject =  document.forms[formName];
  var validateEntries = false;
  var validatePassword = true; // Passwords are not mandatory
  var password = formObject.userpassword;
  var passwordConfirm = formObject.passwordConfirm;
  
  validateEntries = ( 
    	mustfillinRadio(formObject.listingtype) &&	
    	mustfillinRadio(formObject.bitsbytes) );

  if ( validateEntries )
  {  
	  // Build the address strings
  	//
  	validateAddress = testAddress(formObject);
	}
	
	// Check to see if we need to validate the password entries
	//
	//alert("password [" + password + "] passwordConfirm [" + passwordConfirm + "]");
	
	if ( ( ( password.value != null ) && ( password.value != "" ) )
				|| ( ( passwordConfirm.value != null ) && ( passwordConfirm.value != "" ) ) ) 
	{
  	validatePassword = checkPasswords(password, passwordConfirm); 
  }

	//alert("validateEntries [" + validateEntries + "] validatePassword [" + validatePassword + "]");
        	
	if ( ( validateEntries ) && ( validateAddress ) && ( validatePassword ) )
	{
		// 02/11/2004 SB Now build the string that will hold the names of the 
		// form elements that have been changed.
		// 
		for ( fieldName in changedFields )
		{
			if ( changedFields[fieldName] != null )
			{
				//alert('changedFields[' + fieldName + '] = [' + changedFields[fieldName] + ']');
		  	formObject.updateProperties.value += fieldName;		
		  	formObject.updateProperties.value += '\n';		
		  }
		}
		//alert('changed [' + formObject.updateProperties.value + ']');
		
		formObject.submit();
	}	
    	
}

// ************
// handleChange
// ************
// INPUTS
//  formFieldObject	the object that has been changed
//
// OUTPUTS
//	NONE
//
// PURPOSE
//  Submits the login form.
//	
//  
function handleChange(formFieldObject)
{
	//alert('formFieldObject [' + formFieldObject.form.name + '] value [' + formFieldObject.value + '] name [' + formFieldObject.name + ']');
	// Set the forms changed field to have this form object in it
	//
	var formObject =  document.forms[formFieldObject.form.name];

	changedFields[formFieldObject.name] = 'changed';
	
	// See if this field is the userpassword field. If so then we need to flag that
	// the hidden password field (used by LDAP) has been changed
	//
	if ( ( formFieldObject.name == 'userpassword' ) || 
			( formFieldObject.name == 'passwordConfirm' ) )
	{
		if ( ( formFieldObject.value != null ) && 
					( formFieldObject.value != "" ) && 
						( formFieldObject.value.length > 0 )  )
		{
			changedFields['password'] = 'changed';
		}
		else
		{
			changedFields['password'] = null;
			changedFields[formFieldObject.name] = null;
		}
	  // We must set the password hidden form field to force an update to the password
	  // attribute. This is because the userpassword field was intended to be used 
	  // but there are problems with the JNDI implementation that mean that it cannot
	  // be used. Refer to the CDDES for details.
	  //
	  formObject.password.value = formFieldObject.value;
	  //alert('userpassword NEW [' + formObject.userpassword.value + ']');
	  //alert('password  NEW [' + formObject.password.value + ']');
	}

	// See if we have changed one of the address fields
	//
	if ( ( formFieldObject.name == 'address1' ) || 
				( formFieldObject.name == 'address2' ) || 
					( formFieldObject.name == 'address3' ) )
	{
		changedFields['street'] = 'changed';
	}

}

// *************************
// testAndSubmitRegistration
// *************************
// INPUTS
//  formName		the DOM name of the form.
//
// OUTPUTS
//	NONE
//
// PURPOSE
//  Performs all of the testing of the form. If all of the tests are successful
//  then the form is submitted.
//	
//  
function testAndSubmitRegistration(formName) 
{

	var formObject =  document.forms[formName];
  var validateEntries = false;
  var validateDate = false;
  var validateAddress = false;

  validateEntries = (
    	mustfillin(formObject.cn) && 
    	mustfillin(formObject.sn) && 
    	mustfillin(formObject.mail) && 
    	mustfillin(formObject.userpassword) && 
    	mustfillin(formObject.passwordConfirm) &&	 
    	mustfillinRadio(formObject.gender) &&	
    	mustfillinRadio(formObject.listingtype) &&	
    	mustfillinRadio(formObject.bitsbytes) &&	
    	checkPensionPersonalNumbers(formObject) &&
    	processEmail(formObject) &&
    	checkPasswords(formObject.userpassword, formObject.passwordConfirm) ); 

  if ( validateEntries  )
  {  
	  // Build the date and address strings
	  //
	  validateAddress = testAddress(formObject);
	    	
	  validateDate = (
	    	mustfillin(formObject.dob_day) &&	    		    	   	
	    	mustfillin(formObject.dob_month) &&	    		    	   	
	    	mustfillin(formObject.dob_year) &&	    	
	    	buildDate(formObject) );
  }

	//alert("validateEntries [" + validateEntries + "] validateAddress [" + validateAddress + "] validateDate [" + validateDate + "]");      	
	if ( ( validateEntries ) && ( validateAddress ) && ( validateDate ) )
	{
		formObject.submit();
	}	
    	
}

// *****************
// resetRegisterForm
// *****************
// INPUTS
//  formName		the DOM name of the form.
//
// OUTPUTS
//	NONE
//
// PURPOSE
//  Resets the registration form.
//	
//  
function resetRegisterForm(formName) 
{
	var formObject = document.forms[formName];
	formObject.reset();
}

// *********
// buildDate
// *********
// INPUTS
//  formObject	the object that represents the form that is being submitted
//
// OUTPUTS
//	boolean   	true - if the date of birth is a valid date; false otherwise.
//
// PURPOSE
//  Constructs a date value from entries supplied on a form. Checks to ensure 
//  that the date is valid, and if it is sets the value of the dob hidden
//  input field to be the value of the date in millisecs since 01/01/1970.
//	
//	NOTE: The date of birth year cannot be later than the current year, and we 
//	allow for people with a maximum age of 120.
//  
function buildDate(formObject) 
{
	//var formObject = document.forms['registerForm'];
	var validDate = false;
	var message = '';
	today = new Date();
	var year = today.getYear();
	if ( year < 1000 ) 
	{
		year += 1900;
	}

  dob_day = new Number(formObject.dob_day.value);
  dob_month = new Number(formObject.dob_month.value);
  dob_year = new Number(formObject.dob_year.value);

	//alert ('year [' + dob_year + '] month [' + dob_month + '] day [' + dob_day + ']');
  if ( isNaN(dob_day) )
  {
	  message += '  - Invalid day supplied. Please input a value between 1 and 31.\n\n';
  }
  if ( isNaN(dob_month) )
  {
	  message += '  - Invalid month supplied. Please input a value between 1 and 12.\n\n';
  }
  if ( isNaN(dob_year) )
  {
		message += '  - Invalid year supplied. Please input a year of the format yyyy, for example 1964.\n\n';
  }

	if ( ( ( message == null ) || ( message == '' ) || ( message.length == 0 ) )
  	&& ( ( dob_day != 0 ) && ( dob_month != 0 ) && ( dob_year != 0 ) ) )
  {
    //alert('Start date provided.');
    if ( ! CheckDaysInMonth( dob_day,dob_month,dob_year ) )
    {
		  message += '  - Invalid number of days selected for the date of birth. ' +
		            'In the year ' + dob_year + ' ' + monthName[dob_month-1] + 
		            ' only had ' + monthDays[dob_month-1] +
		            ' days. Please input a valid date.\n\n';
	  }
	  if ( ( dob_month != 0 ) && ( ( dob_month < 1 ) || ( dob_month > 12 ) ) )
	  {
		  message += '  - Invalid month supplied. Please input a value between 1 and 12.\n\n';
	  }
	  if ( ( dob_year != 0 ) && ( ( dob_year < year-120 ) || ( dob_year > year ) ) )
	  {
		  message += '  - Invalid year supplied. Please input a year of the format yyyy, for example 1964.\n\n';
	  }	  
  }
  else
  {
	  if ( dob_day == 0 )
	  {
		  message += '  - Invalid day supplied. Please input a value between 1 and 31.\n\n';
	  }
	  if ( dob_month == 0 )
	  {
		  message += '  - Invalid month supplied. Please input a value between 1 and 12.\n\n';
	  }
	  if ( dob_year == 0 )
	  {
			message += '  - Invalid year supplied. Please input a year of the format yyyy, for example 1964.\n\n';
	  }
	}
	
	if ( ( message != null ) && ( message != '' ) && ( message.length > 0 ) )
  {    
    message = '*  The following errors occured with the date(s) you supplied:\n\n' + message + '\n\n';  
    alert(message);
    validDate = false;
  }
  else
  {
    // Convert the date to a Date object
    dateOfBirth = BuildDateObject(dob_day,dob_month,dob_year);
    
    //alert('dateOfBirth getTime [' + dateOfBirth.getTime() + ']');    

    // Initialise the value so that if we fail validation, this value doesn't 
    // keep getting added to
    //
    formObject.dob.value = "";
    		
  	formObject.dob.value = dateOfBirth.getTime();
    
    validDate = true;
  }    

  return validDate;
}
 
// ***********
// testAddress
// ***********
// INPUTS
//  formObject	the object that represents the form that is being submitted
//
// OUTPUTS
//	boolean   	true - if the address passes the validation tests; false otherwise.
//
// PURPOSE
//  Tests to ensure that at least one address field (i.e. one of the 
//	address1, address2 or address3 fields) have been completed AND that
//	at least one other address field has been completed apart from the country.
//  
function testAddress(formObject) 
{
	var validAddress = true;
	var message = '';
	var street = '';
	var town = formObject.town.value;
	var county = formObject.county.value;
	var postalcode = formObject.postalcode.value;
	var isTown = false;
	var isCounty = false;
	var isPostalCode = false;

	//alert('town [' + town + ']');  
	//alert('county [' + county + ']');
	//alert('postalcode [' + postalcode + ']');
	//alert('is town [' + isTown + ']');  
	//alert('is county [' + isCounty + ']');
	//alert('is postalcode [' + isPostalCode + ']');
	
  buildAddress(formObject);
	street = formObject.street.value;

  if ( ( street == null ) || ( street == '') || ( street.length == 0 ) )
  {
  	message += '-  You must enter at least one Address field.\n';
  }

	// Now test the other address values
	//
  if ( ( town != null ) && ( town != '') && ( town.length >0 ) )
  {
  	isTown = true;
  }
  if ( ( county != null ) && ( county != '') && ( county.length > 0 ) )
  {
  	isCounty = true;
  }
  if ( ( postalcode != null ) && ( postalcode != '') && ( postalcode.length > 0 ) )
  {
  	isPostalCode = true;
  }

	//alert('is town [' + isTown + ']');  
	//alert('is county [' + isCounty + ']');
	//alert('is postalcode [' + isPostalCode + ']');

	if ( ( ! isTown ) && ( ! isCounty ) && ( ! isPostalCode ) )
	{
  	message += '-  You must enter at least one of Town, County or Post Code.\n';
  }
		
	if ( ( message != null ) && ( message != '' ) && ( message.length > 0 ) )
  {    
    message = '*  The following errors occured with the address you supplied:\n\n' + message + '\n\n';  
    alert(message);
    validAddress = false;
  }

	return ( validAddress );
}			 

// ****************
// CheckDaysInMonth
// ****************
// INPUTS
//  day     day of month; value 1-31
//  month   month; value 1-12
//  year    the year in yyyy format
//
// OUTPUTS
//	true or false depending whether validation is passed or not.
//
// PURPOSE
//    Makes sure that the number of days specified is allowed for the
//  particular month. The year value is needed to check whether the
//  year is a leap year - i.e. if 28 or 29 days are allowed in Feb
//	
//  
function CheckDaysInMonth(day,month,year)
{
  //alert('CheckDaysInMonth day [' + day + '] month [' + month + '] year [' +  year + ']');
  
  var daysOK = true;
  month -= 1;

  
  // See if we have a valid date
  if ( month == 1 )
  {
    // month is Feb - check for a leap year
    monthDays[1] = leapYearTest(year); 
  }

  //alert('CheckDaysInMonth day [' + day + '] monthDays [' + month + '] is [' +  monthDays[month] + ']');

  if ( day > monthDays[month] )
  {
		daysOK = false;
	}

  return daysOK;
}

// ************
// leapYearTest
// ************
// INPUTS
//  year    the year in yyyy format
//
// OUTPUTS
//	Integer holding the number of days in February - 29 for a leap year; 
//    otherwise returns 28.
//
// PURPOSE
//    Check whether the year is a leap year - i.e. if 28 or 29 days are 
//  allowed in Feb
//	
//  
function leapYearTest(year)
{
  //alert('leapYearTest [' + year + ']');
  
	// Leap year test - on start date
	if ( (year%4==0 && year%100!=0 ) || (year%400==0) ) 
	{
	  return (29); 
	}
	else 
	{
		return (28);
  }
}

// ***************
// BuildDateObject
// ***************
// INPUTS
//	day     format DD
//  month   format MM
//  year    format YYYY
//
// OUTPUTS
//	NONE
//
// PURPOSE
//  Creates a Date object from a Numeric day,month,year,hour,min,sec
//	RHC - 15/06/2005 - Added the timeZone code. Previously the hour could be wrong
//  
function BuildDateObject(day,month,year)
{
  //alert('BuildDateObject DAY');

  var curdate = new Date();
  var timeoffset = curdate.getTimezoneOffset() / 60;
  var timezoneHour = 12 - timeoffset;
  
  new_date = new Date(year, month-1, day, timezoneHour, 12, 12);
  
  // alert('new date getTime [' + new_date.getTime() + ']');    
  return ( new_date );
}


// ************
// buildAddress
// ************
// INPUTS
//  formObject	the object that represents the form that is being submitted
//
// OUTPUTS
//	NONE
//
// PURPOSE
//  Constructs an address value from entries supplied on a form.
//  There are 3 address fields on the registration form. This routine
//  consolidates these values into one address line of the format:
//    address1, address2, address3
//	
//  
function buildAddress(formObject) 
{
	//var formObject = document.forms['registerForm'];
	address = new Array();
	address[0] = formObject.address1.value;
	address[1] = formObject.address2.value;
	address[2] = formObject.address3.value;

  // Initialise the value so that if we fail validation, this value doesn't 
  // keep getting added to
  //
  formObject.street.value = "";
  //alert('formObject.street[' + formObject.street.value + ']');

  for ( i = 0; address[i] != null; i++ )
  {
    //alert('address[' + i + '] has value [' + address[i] + ']');
    if ( address[i] != "" )
    {
      if ( i != 0 )
        if ( ( formObject.street.value != null ) && ( formObject.street.value != "" ) )
          formObject.street.value += ", ";
        
      formObject.street.value += address[i];
    }
    //alert('formObject.street[' + formObject.street.value + ']');
  }
  
  //alert('Address is [' + formObject.street.value + ']');
}

// ***************************
// checkPensionPersonalNumbers
// ***************************
// INPUTS
//  formObject    a reference to the form that we are validating; expect the
//								form to have pensionnumber and employeenumber fields.
//
// OUTPUTS
//	result      true if the pension number and personal number are OK;
//							false otherwise.
// PURPOSE
//    Makes sure that if the personal number and the pension number have been 
//	supplied they are validated against the current criteria.
//	
//  
function checkPensionPersonalNumbers(formObject)
{
  //alert('checkPensionPersonalNumbers [' + formObject + ']');
  
  var message = '';
  var patternMatch = false;
  var result = true;

	message += checkPensionNumber(formObject.pensionnumber);    	   	
	message += checkPersonalNumber(formObject.employeenumber);    	   	

	if ( ( message != null ) && ( message != '' ) && ( message.length > 0 ) )
	{
		alert(message);
		result = false;
	}

	return(result);
}


// ******************
// checkPensionNumber
// ******************
// INPUTS
//  formObject    a reference to the particular object on a form that we are examining
//
// OUTPUTS
//	message       Will have empty value if the items are OK; otherwise
//                will contain an error message string giving details of
//                failures.
// PURPOSE
//    Makes sure that a pension number is numeric (i.e. only contain characters 0-9); 
// positive; not greater than 6 characters in length and is a whole number.
//	
//  
function checkPensionNumber(formObject)
{
  //alert('checkPensionNumber [' + formObject + ']');
  
  var message = '';
  var tmpMessage = '';
  var patternMatch = false;
  var result = true;
  var numberCharSet = "0123456789";
  var this_item_value = formObject.value;
  //alert('this_item_value before trim [' + this_item_value + ']');  
	//this_item_value = removeLeadingChar ( this_item_value, '0' );
  //alert('this_item_value after trim [' + this_item_value + ']');  

  formObject.value = this_item_value;
  
  if ( ( this_item_value != null ) && ( this_item_value != '' ) && ( this_item_value.length > 0 ) )
  {

	  // rhc 21/02/2006 Add leading 0s to ensure that there are 6 characters in the number.
	  // This is how the Pension Data is now presented (previously leading 0s were removed).
	  //alert('this_item_value before add [' + this_item_value + ']');  
		this_item_value = addLeadingChar ( this_item_value, '0', 6 );
  	//alert('this_item_value after add [' + this_item_value + ']');  
  	formObject.value = this_item_value;

    //alert('this_item_value [' + this_item_value + ']');  

    patternMatch = testValidChars(this_item_value,numberCharSet);
    
    //alert('patternMatch [' + patternMatch + ']');  

    if( patternMatch == false )
    {
      tmpMessage += '    - can only contain numeric characters.\n';
    }

    if ( this_item_value < 0 )
    {
      tmpMessage += '    - must be a positive number.\n';
    }

    if ( this_item_value.length > 6 )
    {
      tmpMessage += '    - must not contain more than 6 numeric characters.\n';
    }

    if ( ( tmpMessage != null ) && ( tmpMessage != '' ) && ( tmpMessage.length > 0 ) )
    {
      tmpMessage = '*  The Pension Number:\n' + tmpMessage + '\n\n';
      message += tmpMessage;
    }
    
    //alert('tmpMessage [' + tmpMessage + ']');  
  }    

  //alert('message [' + message + ']');  

	
  return (message);
}


// *******************
// checkPersonalNumber
// *******************
// INPUTS
//  formObject    a reference to the particular object on a form that we are examining
//
// OUTPUTS
//	message       Will have empty value if the items are OK; otherwise
//                will contain an error message string giving details of
//                failures.
// PURPOSE
//    Makes sure that a personal number contains alpha-numeric characters 
//	(i.e. characters 0-9a-zA-Z); is positive; is not greater than 7 characters.
//	
//  
function checkPersonalNumber(formObject)
{
  //alert('checkPersonalNumber [' + formObject + ']');
  
  var message = '';
  var tmpMessage = '';
  var patternMatch = false;
  var result = true;
  var numberCharSet = "0123456789";
  var alphaCharSet = "abcdefghijklmnopqrstuvwxyz";
  var validPersonalNumberChars = numberCharSet + alphaCharSet;
  var this_item_value = formObject.value.toLowerCase();

  //alert('this_item_value before trim [' + this_item_value + ']');
  // Test to see if the personal number is a numeric. If it is then we need to 
  // remove the leading zeros. This is to cater for the fact that the csv file
  // of pensioner data holds personal numbers that are numeric only without 
  // leading zeros, but holds personal numbers that contain alhpa characters 
  // with leading zeros. Thus normalise for one case.
  //
  //if ( ! isNaN ( this_item_value ) ) 
  //{
	  //this_item_value = removeLeadingChar ( this_item_value, '0' );
  	//alert('this_item_value after trim [' + this_item_value + ']');  
  	//formObject.value = this_item_value;
  //}
  
	//message += '    - still testing so not submitted.\n';
  if ( ( this_item_value != null ) && ( this_item_value != '' ) && ( this_item_value.length > 0 ) )
  {
	  // rhc 21/02/2006 Add leading 0s to ensure that there are 6 characters in the number.
 	  // If the number ends in "X" then there will be 7 characters in the number.
  	// This is how the Pension Data is now presented (previously leading 0s were removed).
  	if (this_item_value.charAt(this_item_value.length - 1) == 'x')
  	{
  		  //alert('this_item_value before add [' + this_item_value + ']');  
				this_item_value = addLeadingChar ( this_item_value, '0', 7 );
  			//alert('this_item_value after add [' + this_item_value + ']');  
  			formObject.value = this_item_value;
		}
		else
  	{
  		  //alert('this_item_value before add [' + this_item_value + ']');  
				this_item_value = addLeadingChar ( this_item_value, '0', 6 );
  			//alert('this_item_value after add [' + this_item_value + ']');  
  			formObject.value = this_item_value;
		}
    //alert('this_item_value [' + this_item_value + ']');  

    patternMatch = testValidChars(this_item_value,validPersonalNumberChars);
    
    //alert('patternMatch [' + patternMatch + ']');  

    if( patternMatch == false )
    {
      tmpMessage += '    - can only contain alpha-numeric characters.\n';
    }

    if ( this_item_value < 0 )
    {
      tmpMessage += '    - must be a positive number.\n';
    }

    if ( this_item_value.length > 7 )
    {
      tmpMessage += '    - must not contain more than 7 alpha-numeric characters.\n';
    }

    if ( ( tmpMessage != null ) && ( tmpMessage != '' ) && ( tmpMessage.length > 0 ) )
    {
      tmpMessage = '*  The Personal Number:\n' + tmpMessage + '\n\n';
      message += tmpMessage;
    }
    
    //alert('tmpMessage [' + tmpMessage + ']');  
  }    

  //alert('message [' + message + ']');  

    
  return (message);
}


// **************
// testValidChars
// **************
// INPUTS
//  inputString   a string that will be tested to see if it contains the characters 
//                listed in charList
//  charList      a string containing a list of characters that can exist in the 
//                input string.
// OUTPUTS
//  result        true is all of the characters in the input string match a 
//                character in the charList; false otherwise.
// PURPOSE
//    This routine gets around bugs in IE5.0 and IE5.5 non-SP2 browsers that do
//  not support JavaScript version 1.2, even though this should be supported in
//  all versions of IE4.0 upwards!
//	
//  
function testValidChars(inputString,charList)
{
  var result = true;
  
  // For each character in the inputString test to see that
  // it exists in the charList
  //
	for ( var i=0; i<inputString.length; i++ )
	{
		if ( charList.indexOf(inputString.substr(i,1)) < 0 )
		{
			result = false;
			break;
		}
  }
  
  return result;
}

// **********
// trimString
// **********
// INPUTS
//  str   				input string to be trimmed
//  trimChar      The character to trim from teh start and end of the string.
// OUTPUTS
//  str		        the trimmed version of the input str
// PURPOSE
//    This function will remove the supplied trimChar from teh start and 
//	end of the supplied str.
//	
// 
function trimString (str, trimChar) 
{
  str = removeLeadingChar ( str, trimChar );
  
  str = removeTrailingChar ( str, trimChar );
  
  return str;
}

// *****************
// removeLeadingChar
// *****************
// INPUTS
//  str   				input string to be trimmed
//  trimChar      The character to trim from teh start and end of the string.
// OUTPUTS
//  str		        the trimmed version of the input str
// PURPOSE
//    This function will remove the supplied trimChar from the start of the 
//	supplied str.
//	
// 
function removeLeadingChar (str, trimChar) 
{
  while (str.charAt(0) == trimChar)
    str = str.substring(1);
  
  return str;
}


// ******************
// removeTrailingChar
// ******************
// INPUTS
//  str   				input string to be trimmed
//  trimChar      The character to trim from the end of the string.
// OUTPUTS
//  str		        the trimmed version of the input str
// PURPOSE
//    This function will remove the supplied trimChar from the end of the 
//	supplied str.
//	
// 
function removeTrailingChar (str, trimChar) 
{
 
  while (str.charAt(str.length - 1) == trimChar)
    str = str.substring(0, str.length - 1);
  
  return str;
}

// **************
// addLeadingChar
// **************
// INPUTS
//  str   				input string to be added to
//  addChar       The character to add to the start of the string.
//  addLength     The required length of the string.
// OUTPUTS
//  str		        the added version of the input str
// PURPOSE
//    This function will add the supplied addChar from the start of the 
//	supplied str up to the supplied length.
//	
// 
function addLeadingChar (str, addChar, addLength) 
{
  while (str.length < addLength)
    str = addChar + str;
  
  return str;
}
