//////////
// Resticts the input of a text field according to a data type, or a customly defined 
// character set.
// TODO: Currently working only in IE. Fix it for NN4 and NN6.
//
function RestrictInput(e, nType)
{ 	
	var nKeyCode;             // The code of the key pressed.
	var sAcceptedChars        // The string containing all the accepted characters.
	var asAcceptedChars       // The array of accepted chars.
	var anAcceptedCodes       // The array of accepted unicode codes.
	var nAccepted             // The number of accepted characters.
	var bAccepted             // True if the entered character is accepted.
	var i                     // Auxiliary integer.

	// Initialise.
	bAccepted = false;

	// Get the accepted character set according to the requested type.
	switch (nType)
	{
		case 1:
		// Floating point.
			sAcceptedChars = "0**1**2**3**4**5**6**7**8**9**-**.";
			break;
		case 2:
		// Integer.
			sAcceptedChars = "0**1**2**3**4**5**6**7**8**9**-";
			break;
		case 3:
		// Identifier.
			sAcceptedChars = "_**a**b**c**d**e**f**g**h**i**j**k**l**m**n**o**p**q**r**s**t**u**v**w**x**y**z**A**B**C**D**E**F**G**H**I**J**K**L**M**N**O**P**Q**R**S**T**U**V**W**X**Y**Z**0**1**2**3**4**5**6**7**8**9";
			break;
		case 4:
		// Alphanumeric, underscore, hyphen, dot, and space.
			sAcceptedChars = " **.**_**-**a**b**c**d**e**f**g**h**i**j**k**l**m**n**o**p**q**r**s**t**u**v**w**x**y**z**A**B**C**D**E**F**G**H**I**J**K**L**M**N**O**P**Q**R**S**T**U**V**W**X**Y**Z**0**1**2**3**4**5**6**7**8**9";
			break;
		case 5:
		// String.
			sAcceptedChars = "_** **~**`**!**@**#**$**%**^**&**(**)**-**_**+**=**{**}**[**]**;**:**'**\"**,**<**.**>**/**?**\**|**a**b**c**d**e**f**g**h**i**j**k**l**m**n**o**p**q**r**s**t**u**v**w**x**y**z**A**B**C**D**E**F**G**H**I**J**K**L**M**N**O**P**Q**R**S**T**U**V**W**X**Y**Z**0**1**2**3**4**5**6**7**8**9***";
			break;
		case 6:
		// Nothing (disabled).
			sAcceptedChars = "";
			break;
	}

	// Split the string to an array.
	asAcceptedChars = sAcceptedChars.split("**")

	// Get the number of accepted chars.
	nAccepted = asAcceptedChars.length;

	// Make sure the code array is the right length. Notice that this is 1 element bigger
	// than the accepted chars array because it also contains the line feed code (13).
	anAcceptedCodes = new Array(nAccepted+1)

	// Convert the characters to unicode codes.
	for(i=0; i<nAccepted; i++)
		anAcceptedCodes[i] = asAcceptedChars[i].charCodeAt(0);

	// Add the line feed code.			
	anAcceptedCodes[nAccepted] = 13;

	// Get the code of the key pressed.		
	if (document.layers || (document.getElementById && !document.all))  // NN4 + NN6
		nKeyCode = e.which;		
	else if(document.all) // IE
		nKeyCode = e.keyCode;

	if (nKeyCode == 13)
		SubmitForm();

	// If the character entered is found in the accepted character array set the accepted 
	// flag to true and exit the loop.
	for(i=0; i<nAccepted+1; i++)
		if (nKeyCode == anAcceptedCodes[i])
		{
			bAccepted = true;
			break;
		}

	// If the character entered is not an accepted character do not output the character.	
	if (!bAccepted) 
	{
		if (document.layers || (document.getElementById && !document.all))  // NN4 + NN6
			e.which = null;
		else if(document.all) // IE
			e.keyCode = null;
	}
} // End of RestrictInput()


//////////
// Validates a number. It works for both floating point and integer numbers.
// INPUTS - num: the number; bRequired: true if this is a required field; 
// nMin, nMax: the minimum/maximum values allowed; sFieldName: the name of 
// the field in which this number was entered (used for the error message); 
// nType: the data type of the number (1 for float, 2 for integer).
//
function ValidateNumber(num, bRequired, nMin, nMax, sFieldName, nType)
{ 			
	// Convert the number to string (notice that it may be a string already).
	num = new String(num)

	// Required field check.
	if ((bRequired) && (num.length == 0))
	{
		alert("The " + sFieldName + " is a required field.\nPlease enter this value and try again.");
		return false;
	}
	else if (num.length > 0)
	{
		// Data type check.
		if (nType == 1)
		// Float
		{
			// Check that it is a number.
			if (!isFinite(num))
			{
				alert("The " + sFieldName + " should be a decimal number.\nPlease re-enter this value and try again.");
				return false;
			}
		}
		else if (nType == 2)
		// Int
		{
			// Check that it is an integer number.
			if (!isFinite(num) || (isFinite(num) && (num.indexOf(".") > -1)))
			{
				alert("The " + sFieldName + " should be a number (integer).\nPlease re-enter this value and try again.");
				return false;
			}
		}	


		// Limit check.
		if (num < nMin)
		// Min
		{
			alert("The " + sFieldName + " is less than the minimum allowed (" + nMin + ").\nPlease re-enter this value and try again.");
			return false;
		}
		else if (num > nMax)
		// Max
		{
			alert("The " + sFieldName + " is greater than the maximum allowed (" + nMax + ").\nPlease re-enter this value and try again.");
			return false;
		}
	}


	// Number validated; return true.
	return true;	

} // End of ValidateNumber()


//////////
// Validates a string. It works with various types of strings.
// INPUTS - str: the string; nMin, nMax: the minimum/maximum numbers of chars;
// sFieldName: the name of the field in which this string was entered (used 
// for the error message); sIllegalChars: a string containing all the characters
// that are not allowed, delimited by "**" (used in custom string - type 3 - only);
// nType: the type of the number (1 for identifier; 2 for identifier, underscore, 
// hyphen, dot, and space; 3 for custom string).
//
function ValidateString(str, nMin, nMax, sFieldName, sIllegalChars, nType)
{ 	
	var objRegExp;            // A regular expression.
	var sRegExp;              // A string describing a reg. exp.
	var asIllegalChars;       // Array containing all the characters that are not 
				  // allowed (used in custom string - type 3).
	var i;                    // Auxiliary integer.


	// Type check.
	if (nType == 1)
	// Identifier [A-Za-z0-9_]
	{
		// Define the regular expression.
		objRegExp = new RegExp("^[a-zA-Z0-9_]*$");

		// If this version of js supports reg. expr. test it.	
		if (window.RegExp) 
			if (!objRegExp.test(str))
			{
				alert("The " + sFieldName + " field contains at least one illegal character (allowed characters: 0-9, a-z, A-Z, and _).\nPlease remove the unwanted character(s) and try again.");
				return false;
			}
	}
	else if (nType == 2)
	// Identifier, underscore, hyphen, dot, and space [A-Za-z0-9 ._-]
	{
		// Define the regular expression.
		objRegExp = new RegExp("^[a-zA-Z0-9 ._-]*$");

		// If this version of js supports reg. expr. test it.	
		if (window.RegExp) 
			if (!objRegExp.test(str))
			{
				alert("The " + sFieldName + " field contains at least one illegal character (allowed characters: 0-9, a-z, A-Z, _, -, ., and [space]).\nPlease remove the unwanted character(s) and try again.");
				return false;
			}
	}
	else if (nType == 3)
	// Custom 
	{
		// Make sure there is at least one illegal character in the relevant string.
		if  (sIllegalChars != "") 
		{
			// Get the array of illegal chars.
			asIllegalChars = sIllegalChars.split("**");

			// Start constructing the regular expression.
			sRegExp = "^[^";

			// Add all the illegal chars.
			for(i=0; i<asIllegalChars.length; i++)
				sRegExp	= sRegExp + asIllegalChars[i];

			// Finish off the reg. exp.
			sRegExp	= sRegExp + "]*$";

			// Define the regular expression object.
			objRegExp = new RegExp(sRegExp);

			// If this version of js supports reg. expr. test it.	
			if (window.RegExp) 
				if (!objRegExp.test(str))
				{
					// Start constructing the error message.
					str = "The " + sFieldName + " field contains at least one illegal character (illegal characters: ";

					// Add  the 1st illegal char.
					if (asIllegalChars[0] != " ") 
						str = str + asIllegalChars[0];
					else
						str = str + "[space]";

					// Add all the subsequent illegal chars.
					for(i=1; i<asIllegalChars.length; i++)
					if (asIllegalChars[i] != " ") 
						str = str + ", " + asIllegalChars[i];
					else
						str = str + ", " + "[space]";

					// Finish off.
					str = str + ").\nPlease remove the unwanted character(s) and try again."

					// Display the message and return false.
					alert(str);
					return false;
				}
		}
	}


	// Length check.
	if (str.length < nMin)
	// Min
	{
		alert("The " + sFieldName + " should be at least " + nMin + " character(s) long.\nPlease correct this error and try again.");
		return false;
	}
	else if (str.length > nMax)
	// Max
	{
		alert("The " + sFieldName + " should not be more than " + nMax + " characters long.\nPlease correct this error and try again.");
		return false;
	}


	// String validated; return true.
	return true;	

} // End of ValidateString()
