function isblank(checkStr)
{
	for (var i=0; i < checkStr.length; i++)
	{
		var c = checkStr.charAt(i);
		if((c != ' ') && (c != '\n') && (c != '\r') && (c != '\t'))
			return false;
	}
	
	return true;
}

function CheckRecordCount(RecordsAllowed, RecordCount, ErrorMessage)
{
	if ((RecordCount >= RecordsAllowed) && (RecordsAllowed != 0))
	{
		alert (ErrorMessage);
		return (false);
	}
	else
		return (true);
}

function VerifyField (objField)
{
	var strValue="";
	var tmpResult="";
	var WordArray = "";
	
	if (objField.MaxLength)
	{
		if (objField.value.length > objField.MaxLength)
		{			
			objField.value = objField.value.slice(0,objField.MaxLength);
		}
	}
	
	if (objField.MaxWords)
	{
		if (objField.value.length > 0)
		{			
			WordArray = objField.value.split (' ')
			if (WordArray.length > objField.MaxWords)
				objField.value = objField.value.slice(0,objField.value.length-1);
		}
	}
	
	if (objField.DataType != null)
	{
		if (objField.DataType.toUpperCase()=="NUMBER")
		{
			if (objField.value.length > 9)
				objField.value = objField.value.slice(0,9);
			
			if (objField.value != "-")
			{
				if (!isNumeric(objField.value))
				{
					for (var i=0; i<objField.value.length; i++)
					{
						if (isNumeric(objField.value.substr(i,1)))
						{						
							tmpResult = tmpResult + objField.value.substr(i,1);
						}				
					}
					
					objField.value = tmpResult;
				}
			}
		}
	}
	
	if (objField.MaxValue)
	{
		if (objField.value > objField.MaxValue)
		{			
			objField.value = objField.MaxValue;
		}
	}
}


function Verify (form, PassErrors)
{
	var EmptyFields = "";
	var LongFields = "";
	var Message;
	var Errors = PassErrors;
	var tmpArray, tmpString;
	var fieldID = '';
	for (var i = 0; i < form.length; i++)
	{
		var element = form.elements[i];
	
	    fieldID = element.getAttribute('FieldID');
	    
	    if (fieldID == null || fieldID == '')
	        fieldID = element.id;
	     
		if (element.required)
		{
			if ((element.value == null) || (element.value == "") || (isblank(element.value)))
			{
				if (element.id.length > 60)
					EmptyFields += "\n	" + fieldID.slice (0,60) + "...";
				else
					EmptyFields += "\n	" + fieldID;
			}			
		}
		
		if (element.MaxLength)
		{
			if (element.value.length > element.MaxLength)
			{
				LongFields += "\n	" + fieldID + " (Current Size = " + element.value.length + ", Max =" + element.MaxLength + ")";
			}
		}
		
		//if((element.type == "text") || (element.type == "textarea"))
		//{
			var tmpResult;
			
			if (element.DataType != null)
			{
				switch (element.DataType.toUpperCase())
				{		
					case 'NUMBER':
								
								if (isNumeric (element.value) || element.value.length == 0)
								{
									element.value=element.value.replace(/,/g,"");
								}
								else
								{
									Errors += "- The field \"" + fieldID + "\" must contain a valid number\n\n";
								}
														
								break;
								
					case 'TELEPHONE':	var tmpResult = VerifyTelephone(element.value)
								if(tmpResult)
								{
									if((tmpResult == "empty"))
										element.value = "";
									else
										element.value = tmpResult;
								}
								else
								{
									Errors += "- The field \"" + fieldID + "\" must contain a valid telephone number\n\n";
								}
								break;
								
					case 'DATE':tmpResult = chkdate(element.value);
								if(tmpResult)
								{
									if((tmpResult == "empty"))
										element.value = "";
									else
										element.value = tmpResult;
								}
								else
								{
									Errors += "- The field \"" + fieldID + "\" must contain a valid date.\n\n";
								}
								break;
								
					case 'TIME':tmpResult = chkTime(element.value);
								if(tmpResult)
								{
									if((tmpResult != "empty"))
										element.value = tmpResult;
									else
										element.value = "";
								}
								else
								{
									Errors += "- The field \"" + fieldID + "\" must contain a valid time.\n\n";
								}
								break;
								
					case 'BOOLEAN':if ((element.value!="yes") && (element.value!= "no") && (element.value!="1") && (element.value!="0") && (element.value!="-1") && (element.value != "true") && (element.value!="false") && (!isblank (element.value)))
								{
									Errors += "- The field \"" + fieldID + "\" must be yes or no.\n\n";
								}
								break;
					
					case 'HYPERLINK':	if (element.value.indexOf (" ") != -1)
								{
									Errors += "- The field \"" + fieldID + "\" must not contain any spaces.\n\n";
								}
								break;
								
					case 'EMAIL':	if (!isblank (element.value) && !isValidEmail(element.value))
								{
									Errors += "- The field \"" + fieldID + "\" does not contain a valid email address.\n\n";
								}
								break;
								
					case 'FILE':	if (!isblank (element.value))
									{
										//Get the file extension of the chosen file
										tmpArray = element.value.split(".");
										var strExtension = tmpArray[tmpArray.length-1].toLowerCase();
										
										tmpArray = element.value.split("\\");
										var strFileName = tmpArray[tmpArray.length-1];
										
										//Check the extensions
										if (element.Extensions != "" && element.Extensions != null)
										{											
											//Get the allowed extensions
											tmpArray = element.Extensions.split (",");
											
											tmpString = "";
											
											for (var x = 0; x < tmpArray.length; x++)
											{
												if (tmpArray[x].toLowerCase() == strExtension)
												{
													tmpString = ""
													x = tmpArray.length
													break;
												}
												
												if ((x > 0) && (x < (tmpArray.length - 1)))
												{
													tmpString += ", "
												}
												else if (x == tmpArray.length - 1 && tmpArray.length - 1 > 0)
												{
													tmpString += " or "
												}
													
												switch (tmpArray[x])
												{
													//Add some more values in here as new file types are checked for
													//Remember to add them into ASP file types at top
													case 'jpg':	tmpString += "JPEG Image"
																break;	
																
													case 'gif':	tmpString += "GIF Image"
																break;	
																
													case 'png':	tmpString += "PNG Image"
																break;	
																
													case 'txt':	tmpString += "Text File (.txt)"
																break;	
																
													case 'tif':	tmpString += "TIF Image"
																break;						
																
													case 'bmp':	tmpString += "Bitmap Image"
																break;
																
													case 'rtf':	tmpString += "Rich Text Document"
																break;	
																
													case 'mpg':	tmpString += "MPEG Movie"
																break;
																
													case 'avi':	tmpString += "AVI Movie"
																break;
																
													case 'zip':	tmpString += "ZIP File"
																break;
																
													case 'rar':	tmpString += "RAR File"
																break;
																
													case 'ace':	tmpString += "Win Ace File"
																break;
																
													case 'pdf':	tmpString += "PDF Document"
																break;			
																
													case 'doc':	tmpString += "Word Document (.doc)"
																break;		

													case 'xls':	tmpString += "Excel File (.xls)"
																break;		

													case 'csv':	tmpString += "CSV File (.csv)"
																break;		
																
													default:	tmpString += tmpArray[x] + " File (." + tmpArray[x] + ")"
																break;	
												}
											}
											
											if (tmpString != "")	
											{
												Errors += "- The field \"" + fieldID + "\" does not contain a valid file type.\n"
												Errors += "    Please select a " + tmpString + "\n\n";
											}
										}
																	
										//164 is the actual limit but I have allowed a bit
										if (strFileName.length > 120)
											Errors += "- The file name in field \"" + element.id + "\" is too long.\n\n"
										
										//Check the extension length (10 characters is the max for storing in the table)
										if (strExtension.length > 10)
											Errors += "- The file extension in field \"" + fieldID + "\" is too long.\n\n"
									}
										
								break;
				}
			}
		//}
	}
	
	if(!EmptyFields && !Errors && !LongFields)
	{
		return true;
	}
	
	else
	{	
		Message = "___________________________________________________________________\n\n";
		Message += "The form was not submitted because of the following error(s).\n";
		Message += "Please correct these error(s) and re-submit the form.\n";
		Message += "___________________________________________________________________\n";
			
		if (EmptyFields)
		{
			Message += "\n- The following required field(s) are empty:" + EmptyFields + "\n";
		}
	
		if (LongFields)
		{
			Message += "\n- The following field(s) contain too much text:" + LongFields + "\n";
		}
	
		if (Errors)
		{
			Message += "\n";
			Message += Errors;			
		}
		alert(Message);	
		return false;
	}
}

function isNumeric (checkStr)
{		
	var checkOK = "0123456789,.";
	var allValid = true;
	var decPoints = 0;
	var allNum = "";
	var found = false;
	
	//Loop through the check string checking each character
	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		
		//Check this char to see if it is valid (CheckOK)
		found = false;
		
		//Check for the maximum number before sql server returns 1E+16
		if (checkStr.length > 15)
		{
			found = false;
			break;
		}
				
		for (j = 0;  j < checkOK.length;  j++)
		{
			if (ch == checkOK.charAt(j))
			{					
				found = true;
				break;
			}
		}
		
		//Special case when the -ve sign is at the start of the string
		if ((ch == "-") && (i == 0) && (checkStr.length > 1))
		{
			found = true;
		}
		
		//Didn't find the char
		if (found==false)
		{
			allValid = false;
			break;
		}
		
		if (ch == ".")
		{			
			if(checkStr.length > 1 && decPoints == 0)
			{
				allNum += ".";
				decPoints++;
			}
			else
			{
				allValid = false;
				break;
			}
		}	
	}
	if (allValid == true)
	{
		return true;
	}
	
	else
		return false;
}

//Telephone validation function
function VerifyTelephone(checkStr)
{
	var CheckString = checkStr;
		
	CheckString = CheckString.replace(/[(]/g,"");
	CheckString = CheckString.replace(/[)]/g,"");
	CheckString = CheckString.replace(/[ ]/g,"");
	CheckString = CheckString.replace(/[-]/g,"");
	CheckString = CheckString.replace(/[.]/g,"");
	CheckString = CheckString.replace(/[,]/g,"");
	CheckString = CheckString.replace(/[\/]/g,"");
	CheckString = CheckString.replace(/[\\]/g,"");
	
	if (isblank(CheckString.replace(/[+]/g,"")))
		return "empty";
	
	if (!isNumeric(CheckString.replace(/[+]/g,"")))
		return false;
		
	return CheckString;
}

//Email vaildation function
function isValidEmail(strEmail){
	//var pattern = /^([a-zA-Z0-9]|[a-zA-Z0-9][\w\+'.-]*)@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/i;	
	//Check if there is @ and . and no spaces		
	if((strEmail.indexOf("@") == -1) || (strEmail.indexOf(".") == -1) || (strEmail.indexOf(" ") != -1))
		return false; 				 			  			  
	else
		return true;
}

function chkdate(strPassDate)
{
	//var strDatestyle = "US"; //United States date style
	var strDatestyle = "EU";  //European date style
	
	var strDate = strPassDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var blnFound = false;
	var strSeparatorArray = new Array("-"," ","/",".");
	var err = 0;
	
	//Sets up the 12 months of the year
	var strMonthArray = new Array(12);
	strMonthArray[0] = "Jan";
	strMonthArray[1] = "Feb";
	strMonthArray[2] = "Mar";
	strMonthArray[3] = "Apr";
	strMonthArray[4] = "May";
	strMonthArray[5] = "Jun";
	strMonthArray[6] = "Jul";
	strMonthArray[7] = "Aug";
	strMonthArray[8] = "Sep";
	strMonthArray[9] = "Oct";
	strMonthArray[10] = "Nov";
	strMonthArray[11] = "Dec";
	
	if (strDate.length < 1)
	{
		return "empty";
	}
	
	for (var intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++)
	{
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1)
		{
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) 
			{
				return false;
			}
		
			else 
			{
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
			}
			
			blnFound = true;
		 }
	}
	
	if (blnFound == false)
	{
		if (strDate.length>5) 
		{
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
		}
		
		else
			return false;
	}
	
	if (strYear.length < 2)
	{
		return false;
	}
	
	if (strYear.length == 2)
	{
		//This will cause problems in the future and should be sorted out
		if (strYear > 30)
			strYear = '19' + strYear;
		else
			strYear = '20' + strYear;
	}
	
	if (isNaN(strYear) || strYear.length > 4)
	{
		return false;
	}
	
	//Make sure the date doesn't exceed the bounds of a SmallDateTime (sql Server)
	if (parseInt(strYear) < 1900 || parseInt(strYear) > 2078)
	{
		return false;
	}
	
	
	if (strDatestyle == "US") 
	{
		strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
	}
	
	intday = parseInt(strDay, 10);	
	if (isNaN(intday))
	{
		err = 2;
		return false;
	}
	
	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth)) 
	{
		for (i = 0;i<12;i++) 
		{
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) 
			{
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
			}
		}
		
		if (isNaN(intMonth)) 
		{
			err = 3;
			return false;
		}
	}
	
	intYear = parseInt(strYear, 10);
	if (isNaN(intYear))
	{
		err = 4;
		return false;
	}
	
	if (intMonth>12 || intMonth<1)
	{
		err = 5;
		return false;
	}
	
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) 
	{
		err = 6;
		return false;
	}
	
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) 
	{
		err = 7;
		return false;
	}
	
	if (intMonth == 2) 
	{
		if (intday < 1) 
		{
			err = 8;
			return false;
		}
		
		if (LeapYear(intYear) == true) 
		{
			if (intday > 29) 
			{
				err = 9;
				return false;
			}
		}
		
		else 
		{
			if (intday > 28) 
			{
				err = 10;
				return false;
			}
		}
	}
	
	if (strDatestyle == "US")
	{
		strDate = intMonth + "/" + intday + "/" + strYear;
	}
	
	else 
	{
		strDate = "";
		
		if (intday < 10)
		{
			strDate = "0";
		}
			
		strDate += intday + "/";
		
		if (intMonth < 10)
		{
			strDate += "0";
		}
			
		strDate += intMonth + "/" + strYear;
	}
	
	return strDate;
}

function chkTime(timeStr) 
{
	// Checks if time is in HH:MM:SS AM/PM format.
	// The seconds and AM/PM are optional.

	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

	var matchArray = timeStr.match(timePat);
	
	if (timeStr.length < 1)
	{
		return "empty";
	}
	
	if (matchArray == null) 
	{
		//alert("Time is not in a valid format.");
		return false;
	}
	
	hour = matchArray[1];
	minute = matchArray[2];
	second = matchArray[4];
	ampm = matchArray[6];

	if (second=="") { second = null; }
	if (ampm=="") { ampm = null; }

	if (hour < 0  || hour > 23) 
	{
		//alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
		//alert("Hour must be between 1 and 23.");
		return false;
	}
	//if (hour <= 12 && ampm == null) 
	//{
	//	if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) 
	//	{
	//		alert("You must specify AM or PM.");
	//		return false;
	//	}
	//}
	
	//if  (hour > 12 && ampm != null) 
	//{
	//	alert("You can't specify AM or PM for military time.");
	//	return false;
	//}
	
	if (minute<0 || minute > 59) 
	{
		//alert ("Minute must be between 0 and 59.");
		return false;
	}
	
	if (second != null && (second < 0 || second > 59)) 
	{
		//alert ("Second must be between 0 and 59.");
		return false;
	}
	return timeStr;
}

function LeapYear(intYear) 
{
	if (intYear % 100 == 0) 
	{
		if (intYear % 400 == 0) { return true; }
	}
	
	else 
	{
		if ((intYear % 4) == 0) { return true; }
	}
	
	return false;
}


	
function CheckPasswordStrength(strPassword, strOldPassword, MinimumLength, MinimumStrength) {
    var reg = new RegExp("^[a-zA-Z0-9]*$", "i");
    var Strength = 0;


    if (/[0-9]/.test(strPassword))
        Strength += 1;

    if (/[a-z]/.test(strPassword))
        Strength += 1;

    if (/[A-Z]/.test(strPassword))
        Strength += 1;

    if (strPassword.length < MinimumLength) {
        Strength = 0;
    }

    if (!reg.test(strPassword)) {
        Strength = -1;
    }
    return Strength;
}