var time=0;

function formValidate(FN,MN,LN,BDATE,DDATE)
{		
	var fName = FN.value;
	var mName = MN.value;
	var lName = LN.value;

   // Strip out characters that are not allowed in a name
   fName = fName.replace(/(\'|\"|\!|\@|\#|\$|\%|\^|\&|\(|\)|\+|\=|\[|\]|\{|\}|\<|\>|\~|\`|\|)/g, " ");
   mName = mName.replace(/(\'|\"|\!|\@|\#|\$|\%|\^|\&|\(|\)|\+|\=|\[|\]|\{|\}|\<|\>|\~|\`|\|)/g, " ");
   lname = lName.replace(/(\'|\"|\!|\@|\#|\$|\%|\^|\&|\(|\)|\+|\=|\[|\]|\{|\}|\<|\>|\~|\`|\|)/g, " ");
   
	if(BDATE)
	{
 		var birthDate = BDATE.value;
	}else {
		var birthDate = '';
	}
	if(DDATE)
	{
		var deathDate = DDATE.value;
	}else {
		var deathDate = '';
	}
	if (fName == "First Name")
	{
		fName = ' ';
	}
	if(mName == "Middle Name")
	{
		mName = ' ';
	}		
	if (lName == "Last Name") 
	{
		alert('Can\'t search without a last name! Please enter names and search again.');
		return false;
	}

    // Specifics tests for this form
    // Need first name if there is a middle name
    if (! isblank(mName) && isblank(fName))  {
				//errors += "You cannot have a middle name without a first name.\n";
				alert('You cannot have a middle name without a first name.');
				return false;
    }
    // Check for wildcards in name
    if (iswildcard(fName) || iswildcard(mName) || iswildcard(lName))  {
				//errors += "You cannot use wildcards in the search fields.\n";
				alert('You cannot use wildcards in the name search fields.');		
				return false;
    }
    // Check for wildcards in name
	if(isblank(lName))
	{
			alert('Can\'t search without a last name! Please enter names and search again.');
			return false;
	}
	//if(isblank(fName))
	//{
	//		alert('Can\'t search without a first and last name! Please enter names and search again.');
	//		return false;
	//}		
	if(!dateValidate(birthDate,deathDate))
	{
			return false;
	}

	var date = new Date();

   if (date.getTime()-time > 10000)
   {
      time=date.getTime();

      if ((!FN.value) && (BDATE.value || DDATE.value))
      {
         alert('Results for surname-only search will include matches covering all dates and all locations.');
      }
   
	   return true;
   }
   else
   {
      return false;
   }
}


function formValidateTree(FN,MN,LN,BDATE,DDATE)
{     
   var fName = FN.value;
   var mName = MN.value;
   var lName = LN.value;

   // Strip out characters that are not allowed in a name
   fName = fName.replace(/(\'|\"|\!|\@|\#|\$|\%|\^|\&|\(|\)|\+|\=|\[|\]|\{|\}|\<|\>|\~|\`|\|)/g, " ");
   mName = mName.replace(/(\'|\"|\!|\@|\#|\$|\%|\^|\&|\(|\)|\+|\=|\[|\]|\{|\}|\<|\>|\~|\`|\|)/g, " ");
   lname = lName.replace(/(\'|\"|\!|\@|\#|\$|\%|\^|\&|\(|\)|\+|\=|\[|\]|\{|\}|\<|\>|\~|\`|\|)/g, " ");
   
   if(BDATE)
   {
      var birthDate = BDATE.value;
   }else {
      var birthDate = '';
   }
   if(DDATE)
   {
      var deathDate = DDATE.value;
   }else {
      var deathDate = '';
   }
   if (fName == "First Name")
   {
      alert('You must enter a first and last name.');
      return false;
   }
   if(mName == "Middle Name")
   {
      mName = ' ';
   }     
   if (lName == "Last Name") 
   {
      alert('You must enter a first and last name.');
      return false;
   }

    // Specifics tests for this form
    // Need first name if there is a middle name
    if (! isblank(mName) && isblank(fName))  {
            //errors += "You cannot have a middle name without a first name.\n";
            alert('You cannot have a middle name without a first name.');
            return false;
    }
    // Check for wildcards in name
    if (iswildcard(fName) || iswildcard(mName) || iswildcard(lName))  {
            //errors += "You cannot use wildcards in the search fields.\n";
            alert('You cannot use wildcards in the name search fields.');     
            return false;
    }
    // Check for wildcards in name
   if(isblank(lName))
   {
         alert('You must enter a first and last name.');
         return false;
   }
   if(isblank(fName))
   {
         alert('You must enter a first and last name.');
         return false;
   }     
   if(!dateValidate(birthDate,deathDate))
   {
         return false;
   }

   return true;
}



function dateValidate(bDate,dDate)
{
	var birthDate = trim(bDate);
	var deathDate = trim(dDate);
	var entries = new Array(birthDate, deathDate);
	var result;
	var bgoodDate = true;
	var count = 0;
	var i = 0;

	var patterns = new Array(/^(\d{1,2})\/(\d{1,2})\/(\d{3,4})$/, 
							 /^(\d{1,2})\/(\d{3,4})$/,
							 /^(\d{1,2})\.(\d{1,2})\.(\d{3,4})$/, 
							 /^(\d{1,2})\.(\d{3,4})$/,
							 /^([A-Za-z]+)\.? *(\d{1,2})\,? *(\d{3,4})$/, 
							 /^(\d{1,2}) *([A-Za-z]+)\.?\,? *(\d{3,4})$/,
							 /^([A-Za-z]+)\.?\,? *(\d{3,4})$/, 
							 /^(\d{3,4})$/);
	for (count = 0; count < entries.length; count++)
	{
		bgoodDate = true;
		if(isblank(entries[count]))
			continue;
		for (i = 0; i < patterns.length; i++)
		{

			result = entries[count].match(patterns[i]);
			if (result != null)
			{
				if( i == 0)					//var m/d/yyyy
				{
					month = result[1];
					day 	= result[2];
					year  = result[3];
					if(!checkMonthNum(month))
					{
						bgoodDate = false;
					}
					if(!checkDay(day))
					{
						bgoodDate = false;
					}
					break;
				}
				else if (i == 1)		//var m/yyyy
				{
					month = result[1];
					year	= result[2];
					if(!checkMonthNum(month))
					{
						bgoodDate = false;
					}
					break;
				}
				else if (i == 2)		//var d.m.yyyy
				{
					month = result[2];
					day 	= result[1];
					year  = result[3];
					if(!checkMonthNum(month))
					{
						bgoodDate = false;
					}
					if(!checkDay(day))
					{
						bgoodDate = false;
					}
					break;			
				}	
				else if (i == 3)		//var m.yyyy
				{
					month = result[1];
					year  = result[2];
					if(!checkMonthNum(month))
					{
						bgoodDate = false;
					}
					break;					
				}	
				else if (i == 4)		//var Monthdyyyy
				{
					month = result[1];
					day 	= result[2];
					year  = result[3];
					if(!checkMonthStr(month))
					{
						bgoodDate = false;
					}
					if(!checkDay(day))
					{
						bgoodDate = false;
					}
					break;
				}	
				else if (i == 5)		//var dMonthyyyy
				{
					month = result[2];
					day 	= result[1];
					year  = result[3];
					if(!checkMonthStr(month))
					{
						bgoodDate = false;
					}
					if(!checkDay(day))
					{
						bgoodDate = false;
					}
					break;					
				}					
				else if (i == 6)		//var Monthyyyy
				{
					month = result[1];
					year  = result[2];
					if(!checkMonthStr(month))
					{	
						bgoodDate = false;
					}
					break;					
				}	
				else  if(i == 7)
				{
					year  = result[1];
					bgoodDate = true;
					break;
				}
			}
		}
		if(!result || bgoodDate == false)
		{
			bgoodDate = false;
			alert("Can't read date " +entries[count]+ " - please check spelling and make sure to use 4 digits for year.");		
			return bgoodDate;
		}

	}
	return bgoodDate;
}	



function checkMonthStr(monthStr)
{
	var months = new Array("Jan.", "January", "Jan", "january", "jan", "jan.", "February", "February,", "Feb", "Feb.", 
						   "february", "february,", "feb", "feb.", "March", "March,", "Mar", "Mar.", "march", "march,", "mar", "mar.",
						   "April", "April,", "Apr", "Apr.", "april", "april,", "apr", "apr.", "May", "May,", "may", "may,", 
						   "June", "June,", "Jun", "Jun.", "june", "june,", "jun", "jun.", "July", "July,", "Jul", "Jul.", "july", "july,", "jul", "jul.",
						   "August", "August,", "Aug", "Aug.", "august", "august,", "aug", "aug.", "September", "September,", "Sept", "Sept.", 
   						   "september", "september,", "sept", "sept.", "October", "October,", "Oct", "Oct.", "october", "october,", "oct", "oct.",
						   "November", "November,", "Nov", "Nov.", "november", "november,", "nov", "nov.", "December", "December,", "Dec", "Dec.", 
						   "december", "december,", "dec", "dec.");
	for (count = 0; count < months.length; count++)
	{
		if(monthStr == months[count])
		{	
			bMonth = true;
			break;
		}
		else 
			bMonth = false;
	}
	return bMonth;

}	
function checkMonthNum(monthNum)
{	
	iMonth = parseInt(monthNum, 10);
	if(iMonth > 0 && iMonth <= 12)
	{
		return true;
	} else { 
		return false;
	}
}

function checkDay(day)
{
	iDay = parseInt(day, 10);
	if(iDay > 0 && iDay <= 31)
	{
		return true;
	} else { 
		return false;
	}
}

// A utility function that returns true if a string contains only 
// whitespace characters.
function isblank(s)
{
	if (s == null) return true;
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t') && (c != '\:') && (c != '\;') && (c != '\.') && (c != '\/') && (c != '\\') && (c != '\-') && (c != '\_')) return false;
    }
    return true;
}
function iswildcard(s)
{
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (c == '*') return true;
		if (c == '?')  {
			// Jumping through hoops to support queries of A??? but
			// reject queries of A? or A??
			if (s.length >= (i+2))  {
				if ((s.charAt(i+1) == '?') && (s.charAt(i+2) == '?'))  {
					i = i + 2;
				}else {
					return true;
				}
			}else 
				return true;
			}
    }
    return false;
}

// Trims the spaces on the left hand side of the string
function ltrim(thisstring)
{
        while(thisstring.charAt(0)==" ")
        {
                thisstring=thisstring.substring(1,thisstring.length)
        }
        return thisstring
}

// Trims the spaces on the right hand side of the string
function rtrim(thisstring)
{
        while(thisstring.charAt(thisstring.length-1)==" ")
        {
                
thisstring=thisstring.substring(0,(thisstring.length-1))
        }
        return thisstring
}

// Trims spaces from both sides of the string
function trim(thisstring)
{
        thisstring=ltrim(thisstring)
        thisstring=rtrim(thisstring)
        return thisstring
}

function fixDate(){  //takes one or more date fields as arguments
   for (var n=0; n<arguments.length; n++) 
   {
      var dateInput = arguments[n];
      var d="", m="", y="", mNum;
      
      //***Delete trailing and leading spaces (this is longer than necessary because of netscape regexp bug with "^")
      dateInput.value = dateInput.value.replace(/^\s+/,"");
      dateInput.value = dateInput.value.replace(/(\s+)$/,"");
      
      // Also, must delete any leading 0s
      dateInput.value = dateInput.value.replace(/^0+/,"");
      
      if (dateInput.value == "") 
      {
         return true;
      }

      //***Split into fields
      var dateFields = dateInput.value.split(/\b\W+\b/);

      //***Make sure it has a valid number of fields
      var numFields = dateFields.length;
      if (numFields > 3) 
      {
         badDateAlert(dateInput);
         return false;
      }

      //***Get year
      y = dateFields[numFields - 1];
      if (y.search(/^[1|2]\d{3}$/) != 0)
      {
         badYearAlert(dateInput); 
         return false;
      }
      if (numFields == 1) 
      {
         dateInput.value = y; 
         return true;
      }

      //***Get month (and day, if any)
      var Months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
      var Days = [31,29,31,30,31,30,31,31,30,31,30,31];
      if (((y%4) || (!(y%100))) && (y%400)){Days[1] = 28};
      
      //***See if you can find a text month in the string-----
      m = dateInput.value.replace(/.*\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec).*/i,"$1");
      if (m != dateInput.value) 
      {
         mNum = "janfebmaraprmayjunjulaugsepoctnovdec".indexOf(m.toLowerCase()) / 3;
         m = Months[mNum];
         if (numFields == 3) 
         {
            //***Get day (if any);
            d = dateInput.value.replace(/.*\b(\d{1,2})\b.*/,"$1");
            
            if (d == dateInput.value)
            {
               badDateAlert(dateInput); 
               return false;
            }
            
            if (d < 1 || d > Days[mNum]) 
            {
               invalidDateAlert(dateInput);
               return false;
            }
            d = " " + d + ",";
         }
      }
      
      //***If no text month, then the month must be a number in the first field
      else 
      {
         mNum = parseInt(dateFields[0],10) - 1;
         if (mNum <0 || mNum > 11 || isNaN(mNum)) 
         {
            badDateAlert(dateInput); 
            return false;
         }
         m = Months[mNum];
         if (numFields == 3) 
         {
            //***Get day (if any)
            d = parseInt(dateFields[1],10)
            if (d < 1 || d > Days[mNum])
            {
               invalidDateAlert(dateInput);
               return false;
            }
            d = " " + d + ",";
         }
      }
      dateInput.value = m  + d + " " + y;
   }
   return true;
      
   //***error strings
   function badYearAlert(theField)
   {
   alert("Cannot understand date \"" + theField.value + "\". Make sure you have entered 4 digits for the year.")
   }
   function badDateAlert(theField)
   {
   alert("Cannot understand date \"" + theField.value + "\". Please check spelling and try again.")
   }
   function invalidDateAlert(theField)
   {
   alert("\"" + theField.value + "\" is not a valid date. Please change it.")
   }
}


// Trims spaces from both sides of the string
function formClear(ptrForm)
{
   ptrForm.FN.value = "";
   ptrForm.MN.value = "";
   ptrForm.LN.value = "";
   ptrForm.BDATE.value = "";
   ptrForm.BLOCATION.value = "";
   ptrForm.DDATE.value = "";
   ptrForm.DLOCATION.value = "";
}


