//////////////////////////////////////////////////////////////////  
// File name - common.js   
// Purpose - common validation routines  
// Creation date -   
// Version 1.0  
// Author -   
// Amendments  
// Date:  
// Who:  
// Change:   
/////////////////////////////////////////////////////////////////  
// constants
LETTERS_AND_NUMBERS_ONLY = 'A';
LETTERS_NUMBERS_AND_SPACES_ONLY='B';
LETTERS_NUMBERS_SPACES_AND_PUNCTUATION_ONLY='C';
LETTERS_AND_SPACES_ONLY='D';
MIN_PASSWORD_LENGTH = 6;
MAX_PASSWORD_LENGTH = 20;		// max length of user password
DATE_LENGTH = 10;		// max letters and chars in a date

///////////////////////////////////////////////////////////////////
// Name : validateURL
// Action : validates a URL
// Arguments :	url as a string, optional, which can be 'Y' or 'N'
//		This is because if optional is 'Y', an empty url is allowed
//		allowed.
// Returns : true if OK else false
/////////////////////////////////////////////////////////////////////
function validateURL(url,optional)
{
	optional = optional.toUpperCase();
	// no URL enetered
	if(url=="")
	{
		if(optional=="Y")
		{
			return true;
		}
		else
		{
			if(optional=="N")
			{
				return false;
			}
			else
			{
				alert("URL field set to invalid mode")
				return false;
			}
		}
	}
	// check that string starts with "http://www" plus some more
	
	return true;
}
///////////////////////////////////////////////////////////////// 
// Name : validateSuggestionForm()
// Action : Validates suggestion for
// Arguments: form
// returns: true if valid else false
///////////////////////////////////////////////////////////////// 
function validateSuggestionForm(suggestform)
{

	// check name
	if(stringCheck(suggestform.inputname.value,1,60,"B") == false)
	{
		alert("Invalid name - please check");
		suggestform.inputname.focus();
		return false;
	}
	// check e-mail (if one has been supplied)
	if(suggestform.email.value == "")
	{
		//if(!validateEmail(suggestform.email.value,'N'))
		//{
			alert("Email or phone number must be supplied");
			suggestform.email.focus();
			return false;		
		//}
	}
	
	
	if(textareaCheck(suggestform.suggestion) == false)
	{
		alert("Invalid suggestion - please check");
		suggestform.suggestion.focus();
		return false;
	}
				 
	return true;
}

///////////////////////////////////////////////////////////////// 
// Name : loadImages()
// Action : Preload images 
// Arguments: none 
// returns: none
///////////////////////////////////////////////////////////////// 
function loadImages()
{
	// not yet written
}

///////////////////////////////////////////////////////////////// 
// Name : putImages()
// Action : Put images on index page
// Arguments: none 
// returns: HTML string that displays images
///////////////////////////////////////////////////////////////// 
function putImages()
{
	// not yet written
}
///////////////////////////////////////////////////////////////// 
// Name : textAreaCheck
// Action : checks something hsa been put into a text area
// Arguments: text area 
// returns: true or false
///////////////////////////////////////////////////////////////// 
function textareaCheck(input)
{
 	if(input.value.length == 0)
 	{
 	 	return false;
 	}
	return true;
}
//*****************************************************************
// Name : stringCheck
// Action : validates a string
// Arguments :	String to check
// 		minlength of string
//		maxlength of string
//		mode (described below)
// Returns : true if OK else false
//*****************************************************************
function stringCheck(string,minlength,maxlength,mode)
{
	if(string.value == "")
	{
	 	return false;
	}
	// ensure string is not too short
	if(string.length < minlength)
	{
	 	return false;
	 }
	// ensure string is not too long
	if(string.length > maxlength)
	{
		return false;
	}

	// depending on mode, set invalid string accordingly
	// current modes
	// defined at top of file
	// LETTERS_AND_NUMBERS_ONLY = 'A';
	// LETTERS_NUMBERS_AND_SPACES_ONLY='B';
	// LETTERS_NUMBERS_SPACES_AND_PUNCTUATION_ONLY='C';
	// LETTERS_AND_SPACES_ONLY='D';
	// any other letter, allow anything
 	mode = mode.toUpperCase();
	switch(mode)
	{
	 	case LETTERS_AND_NUMBERS_ONLY: invalidChars = " `¬£$%^&*()_+-={}[]:@~;'#|<>?!,./\"\\";
	 		 	  break;
		case LETTERS_NUMBERS_AND_SPACES_ONLY: invalidChars = "`¬£$%^&*()_+-={}[]:@~;'#|<>?!,./\"\\";
	 		 	  break;
		case LETTERS_NUMBERS_SPACES_AND_PUNCTUATION_ONLY: invalidChars = "¬%^{}[]@~#|<>/\"\\";
	 		 	  break;
		case LETTERS_AND_SPACES_ONLY: invalidChars = "`¬£$%^&*()_+-={}[]:@~;'#|<>?!,./\"\\0123456789";
	 		 	  break;				  				  
		default:  invalidChars = ""; // allow any
	}
	// check for invalid characters
	for(i=0; i < invalidChars.length; i++)
	{
		badChar = invalidChars.charAt(i);
//		if(string.value.indexOf(badChar,0)!= -1)
		if(string.indexOf(badChar,0)!= -1)
		{
			return false;
		}
	}

	return true;
}

//*****************************************************************
// Name : validateDate
// Action : validates a date
// Arguments :	date as a text string 
//		must be in format dd/mm/yyyy e.g. 27/08/1959
// Returns : true if OK else false
//*****************************************************************
function validateDate(theDate)
{
	// ensure something entered
	if(theDate.value == "")
	{
		return false;
	}
	// reject if too long
	if(theDate.length > DATE_LENGTH)
	{
		return false;
	}

	// put text in string object so it can easily be split
	dateString = new String(theDate.value);

	// make date lowercase. This makes error checking easier later
 	dateString = dateString.toLowerCase();
 

	// attempt to split date into three parts XX/XX/XXXX in an array
	dateParts = dateString.split("/");
	//if resultant array did not contain three elements, this is an error
	if(dateParts.length != 3)
	{
		return false;	
	}

	// check that each part has a value
	if( (dateParts[0] == "") || (dateParts[1] == "") || (dateParts[2] == ""))
	{
		return false;
	}
	
	// check each part to ensure it does not contain invalid characters
	invalidChars = "abcdefghijklmnopqrstuvwxyz `¬£$%^&*()_+-={}[]:@~;'#|<>?!,./\"\\";
	for(i =0; i < 3; i++)
	{
		for(j = 0; j < invalidChars.length ; j++)
		{
			badChar = invalidChars.charAt(j);
			if(dateParts[i].indexOf(badChar,0)!= -1)
			{
				return false;
			}
		}
	}

	// pad each part out as required to make day - XX  month - XX year - XXXX
	if(dateParts[0].length == 1)
	{
		// pad day with 0
		dateParts[0] = "0" +dateParts[0];
	}

	if(dateParts[1].length == 1)
	{
		// pad month with 0
		dateParts[1] = "0" +dateParts[1];
	}

	// will allow XX or XXXX for year, i.e. 01 or 2001
	if(dateParts[2].length == 2)
	{
		// add missing 20 in front of date
		// This will fail in the year 2100, when the author will be 140 years old
		dateParts[2] = "20" + dateParts[2];
	}
	else
	{
		if(dateParts[2].length != 4)
		{
			return false;
		}
	}

	// basic day check
	if ( (dateParts[0] < 1) || (dateParts[0] > 31))
	{
		return false;
	}	

	// month check
	if ( (dateParts[1] < 1) || (dateParts[1] > 12))
	{
		return false;
	}


	if ( (dateParts[2] < 2000) || (dateParts[2] > 2099))
	{
		return false;
	}	

	// check month number OK
	badMonth = false;
	// check days in month
	switch(dateParts[1])
	{
		case "01": // Jan
		case "03": // Mar
		case "05": // May
		case "07": // Jul
		case "08": // Aug
		case "10": // Oct
		case "12": // Dec
				if(datePart[0] > 31)
				{
					badMonth = true;
				}
				break;
		case "04": // Apr
		case "06": // Jun
		case "09": // Sep
		case "11": // Nov
				if(datePart[0] > 30)
				{
					badMonth = true;
				}
				break;

		case "02": // Feb - possible leap year
				if( (dateParts[2] % 4 == 0) && ( (dateParts[2] % 100 != 0)  || 
					(dateParts[2] % 400 == 0)))
				{
					// leap year
					if(dateParts[0] > 29)
					{
						badMonth = true;
					}
				}
				else
				{
					// not leap year
					if(dateParts[0] > 28)
					{
						badMonth = true;
					}
				}
				break;
		default:	badMonth = true;
				break;
	}
	// error in month
	if(badMonth == true)
	{
		return false;
	}

	return true;
}

//*****************************************************************
// Name : validateEmail
// Action : validates an email address
// Arguments :	email as a string, optional, which can be 'Y' or 'N'
//		This is because if optional is 'Y', and empty e-mail
//		allowed.
// Returns : true if OK else false
//*****************************************************************
function validateEmail(email,optional)
{

	optional = optional.toUpperCase();
	// no e-mail enetered
	if(email=="")
	{
		if(optional=="Y")
		{
			return true;
		}
		else
		{
			if(optional=="N")
			{
				return false;
			}
			else
			{
				alert("email field set to invalid mode")
				return false;
			}
		}
	}
	// not allowed in address
	invalidChars = " <>|#%^*!:;";
	// check they don't appear
	for(i=0; i < invalidChars.length; i++)
	{
		badChar = invalidChars.charAt(i);
		if(email.indexOf(badChar,0)!= -1)
		{
			return false;
		}
	}
	// make sure an '@' in address. Start at second position in the string
	atPos = email.indexOf("@",1);
	if(atPos == -1)
	{
		return false;
	}
	// make sure there's a full stop after the '@'
	periodPos = email.indexOf(".",atPos);
	if(periodPos == -1)
	{
		return false;
	}
	// make sure at least two letters after the full stop
	if(periodPos +3 > email.length)
	{
		return false;
	}

	return true;
}
//*****************************************************************
// Name : validatePhoneNumber
// Action : validates a phone number
// Arguments :	phone numbert as a text string 
//		Only numbers and spaces allowed
// Returns : true if OK else false
//*****************************************************************
function validatePhoneNumber(thePhoneNumber)
{
// NOTE : NOT YET WRITTEN
	return true;
}
//*****************************************************************
// Name : validateTime
// Action : validates time
// Arguments :	Time in one format:
//			"hh:mm" in 24 hour format
// Returns : true if OK else false
//*****************************************************************
function validateTime(theTime)
{
// NOTE : NOT YET WRITTEN
   validNums = "0123456789";
   colon = ":";
   theTime = theTime.toLowerCase();
   // check time is exactly 5 digits long
   
   return true;
}
//*****************************************************************
// Name : validateLogonFields
// Action : validates name and password field on logon screen
//		note: only basic check - done rigourously at server
//		puts up alert dialog if not OK
// Arguments :	form with name and password fields
// Returns : true if OK else false
//*****************************************************************

function validateLogonFields(form)
{

	if(stringCheck(form.username,MIN_NAME_LENGTH,MAX_NAME_LENGTH,
		LETTERS_AND_NUMBERS_ONLY) == false)
	{
		alert("Invalid name - letters and numbers only with no spaces - check length");
		form.name.focus();
		return false;
	}
	if(stringCheck(form.password,MIN_NAME_LENGTH,MAX_NAME_LENGTH,
		LETTERS_AND_NUMBERS_ONLY) == false)
	{
		alert("Invalid password  - letters and numbers only with no spaces - check length");
		form.password.focus();
		return false;
	}

	return true;
}

//*****************************************************************
// Name : validateUserName
// Action : validates user name on various screens
//		note: only basic check - done rigourously at server
//		puts up alert dialog if not OK
// Arguments :	form containing the user name fields
// Returns : true if OK else false
//*****************************************************************
function validateUserName(form)
{
	if(stringCheck(form.username,MIN_NAME_LENGTH,MAX_NAME_LENGTH,
		LETTERS_AND_NUMBERS_ONLY) == false)
	{
		alert("Invalid name - letters and numbers only with no spaces - check length");
		form.name.focus();
		return false;
	}
	return true;
}
//////////////////////////////// end of common.js ////////////////////////////////////