/*****************************************
* TERRADON Form Field Validation Script  *
* Copyright 2000 TERRADON Corporation    *
*   Original: June 15, 2000 by JAS, JAT  *
*   Modified: June 19, 2000 by JAS       *
******************************************/

//=================================================================================================================================
String.prototype.Trim = function()
{
    // Use a regular expression to replace leading and trailing spaces with the empty string
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

String.prototype.LTrim = function()
{
    // Use a regular expression to replace leading spaces with the empty string
    return this.replace(/(^\s*)/g, "");
}

String.prototype.RTrim = function()
{
    // Use a regular expression to replace trailing spaces with the empty string
    return this.replace(/(\s*$)/g, "");
}

//=================================================================================================================================
function Verify()
{

  Errors = "";
  InValid = 0;
  
  NumFields = Form.length;

  for (var i = 0; i < NumFields; i++)
  {
    if (Form[i].VALIDATE)
      {
        if (Form[i].PARAMETER)
          PARAMETER = ", " + Form[i].PARAMETER;
        else
          PARAMETER = "";

        eval('Validate' + Form[i].VALIDATE + "('" + Form[i].name + "'" + PARAMETER + ")");
      }
  }

  if (InValid != 0)
    {
      if (InValid == 1)
        alert('The Form Validation has returned the following error in the field data:\n____________________________________\n' + Errors + '____________________________________\n\nPlease check this field and try again.');
      else
        alert('The Form Validation has returned the following errors in the field data:\n____________________________________\n' + Errors + '____________________________________\n\nPlease check these fields and try again.');

      return false;
    }

  else
    return true;
}

//=================================================================================================================================
function ValidateFail(field)
{
  InValid++;

  if (Form[field].MESSAGE)
    Errors = Errors + '\n' + InValid + '. ' + Form[field].MESSAGE + "\n";
  else
    Errors = Errors + '\n' + InValid + '. ' + Form[field].name.substr(1 ,Form[field].name.length)  + ' is a required field or has been improperly completed.' + "\n";

}

//=================================================================================================================================
function ValidateText(field)
{

  if (Form[field].value.length == 0) 
    ValidateFail(field);
}

//=================================================================================================================================
function ValidateSelect(field)
{
  if (Form[field].options.selectedIndex < 0)
    ValidateFail(field);
}

//=================================================================================================================================
function ValidateSingle(field)
{
  if (!Form[field].checked)
    ValidateFail(field);
}

//=================================================================================================================================
function ValidateDay(field)
{
  if (
       (parseInt(Form[field].value) > 31) || 
       (parseInt(Form[field].value) != Form[field].value)
     )
    ValidateFail(field);
}
	
//=================================================================================================================================
function ValidateYear(field, Year)
{
  if (
       (parseInt(Form[field].value) < Year)  || 
       (parseInt(Form[field].value) > 9999)  || 
       (parseInt(Form[field].value) != Form[field].value)
     )
    ValidateFail(field);
}

//=================================================================================================================================
function ValidateHour(field)
{
  if (
       (parseInt(Form[field].value) < 1)  || 
       (parseInt(Form[field].value) > 12)  || 
       (parseInt(Form[field].value) != Form[field].value)
     )
    ValidateFail(field);
}

//=================================================================================================================================
function ValidateMinuteSecond(field)
{
  if (
       (parseInt(Form[field].value) < 0)  || 
       (parseInt(Form[field].value) > 59)  || 
       (parseInt(Form[field].value) != Form[field].value)
     )
    ValidateFail(field);
}

//=================================================================================================================================
function ValidateUSPhone(field, required, HasArea)
{
  if ((required == "Yes") && (Form[field].value.length == 0))
    ValidateFail(field);

	else if (Form[field].value.length != 0)
	{
	  if (HasArea == 'Yes')
	    AcceptNumbers=10;
	  else
	    AcceptNumbers=7;
	
	  //Check numbers
	  End = Form[field].value.length;
	  Numbers=0;
		ValidPhone = true;
	
	  for (var i = 0; i < End; i++)
	    {
	      if (parseInt(Form[field].value.charAt(i)) == Form[field].value.charAt(i))
	        Numbers++;
	
	      else if (
	                (Form[field].value.charAt(i) != '.') &&
	                (Form[field].value.charAt(i) != ' ') &&
	                (Form[field].value.charAt(i) != '(') &&
	                (Form[field].value.charAt(i) != ')') &&
	                (Form[field].value.charAt(i) != '-')
	              )
	             ValidPhone = false;
	    }
	
	  if ((Numbers != AcceptNumbers) || (!ValidPhone))
	    ValidateFail(field);
	}
}

//=================================================================================================================================
function ValidateInteger(field, required)
{												
	if (!required)
		required = "Yes";
		
  if ((required == "Yes") && (Form[field].value.length == 0))
    ValidateFail(field);
	else if ((Form[field].value.length != 0) && (parseInt(Form[field].value) != Form[field].value))
    ValidateFail(field);
}

//=================================================================================================================================
function ValidateNumber(field)
{
  if (isNaN(Form[field].value))
    ValidateFail(field);
}

//=================================================================================================================================
function ValidateRange(field, Min, Max)
{
  if (isNaN(Form[field].value))
    ValidateFail(field);
  else
    {
      if ((Form[field].value < Min) || (Form[field].value > Max))
        ValidateFail(field);
    }
}

//=================================================================================================================================
function ValidateUSZip(field, Type)
{
  if (Type == "Long") 
    AcceptNumbers=9;

  else if (Type == "Short") 
    AcceptNumbers=5;

  else
    {
      if (Form[field].value.indexOf('-') >= 0) 
        AcceptNumbers=9;
      else
        AcceptNumbers=5;
    }

  //Check numbers
  End = Form[field].value.length;
  Numbers=0; 
	validzip = true;

  for (var i = 0; i < End; i++)
    {
      if (parseInt(Form[field].value.charAt(i)) == Form[field].value.charAt(i))
        Numbers++;

      else if (Form[field].value.charAt(i) != '-')
				validzip = false;
    }

  if ((Numbers != AcceptNumbers) || (!validzip))
    ValidateFail(field);

}

//=================================================================================================================================
function ValidateIncludes(field, String)
{
  var includePattern = new RegExp(String);
  
  if (!includePattern.test(Form[field].value)) 
    ValidateFail(field);
}

//=================================================================================================================================
function ValidateExcludes(field, String)
{
  var excludePattern = new RegExp(String);
  
  if (excludePattern.test(Form[field].value)) 
    ValidateFail(field);
}

//=================================================================================================================================
function ValidateURL(field, required)
{
  var addressPattern = new RegExp("ftp://|http://|javascript:|file://|gopher://|https://|mailto:|rlogin://|shttp://|snews://|telnet://|tn3270://|wais://");

  if ((required == "Yes") && (Form[field].value.length == 0))
    ValidateFail(field);

  else if ((Form[field].value.length != 0) && (!addressPattern.test(Form[field].value)))
    ValidateFail(field);
}

//=================================================================================================================================
function ValidateEmail(field, required)
{
  var addressPattern = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;

  if (Form[field].value.length == 0)
  {
	  if (required == "Yes") 
		  ValidateFail(field);
	}

  else
		{
	    if (!addressPattern.test(Form[field].value))
        ValidateFail(field);
		}
}

//=================================================================================================================================
function ValidateImage(field, required)
{  
  if ((required == "Yes") && (Form[field].value.length == 0))
    ValidateFail(field);

  else if (Form[field].value.length != 0)
    {
      if (
           (Form[field].value.toLowerCase().indexOf('.jpg') < 0) &&
           (Form[field].value.toLowerCase().indexOf('.gif') < 0)
         )
      ValidateFail(field);
    }
}

//=================================================================================================================================
function ValidatePDF(field, required)
{  
  if ((required == "Yes") && (Form[field].value.length == 0))
    ValidateFail(field);

  else if (Form[field].value.length != 0)
    {
      if (Form[field].value.toLowerCase().indexOf('.pdf') < 0)
	      ValidateFail(field);
    }
}

//=================================================================================================================================
function ValidateLength(field, Min, Max)
{  
  if (
       (Form[field].value.length < Min) ||
       (Form[field].value.length > Max)
     )
    ValidateFail(field);
}

//=================================================================================================================================
function ValidateComboFields(field1, field2)
{  
  if (
       (Form[field1].value.length == 0) &&
       (Form[field2].value.length == 0)
     )
    ValidateFail(field1);
}

//=================================================================================================================================
function ValidateSequence(field1, field2)
{  
  if (
       (Form[field2].value.length == 0) &&
       (Form[field1].value.length != 0)
     )
    ValidateFail(field1);
}
//=================================================================================================================================
function ValidateMatch(field1, field2)
{  
  if (Form[field2].value != Form[field1].value)
    ValidateFail(field1);
}

//=================================================================================================================================
function ValidateCondition(field, Expression)
{
  if (eval(Expression))
    ValidateFail(field);
}

//=================================================================================================================================
function ValidateCurrency(field)
{
	// This routine will remove the "$" and "," from the field to verify the field is numeric.
	var tmpCur;

	tmpCur = Form[field].value;
	tmpCur = tmpCur.Trim();
	tmpCur = tmpCur.replace(/\$|,|-/g, "");

  if (isNaN(tmpCur))
	{
    ValidateFail(field);
	}
	else
	{																
		//If the field is blank, do not format the fields in dollar format, leave blank.
	  if (Form[field].value.length > 0) 
			Form[field].value = formatCurrency(tmpCur);
	}
}

//=================================================================================================================================
function ValidateOpenDate(field, required)
{
	var strDate;
	var err = 0;
	var errmsg = "";
	
	strDate = Form[field].value;	//	Copy form value into work area variables.
	strDate = strDate.Trim();			//	Remove all spaces from front and back of string.
	
	//alertmsg("strDate = " + strDate);
	
	if ((strDate.length == 0) && (required == "Yes"))
	{
		ValidateFail(field);
	}
	else if (strDate.length != 0)
	{
		var strDatestyle = "US"; //United States date style
		//var strDatestyle = "EU";  //European date style
		var strDateArray;
		var strDay;
		var strMonth;
		var strYear;
		var intDay;
		var intMonth;
		var intYear;
		var booFound = false;
		var datefield;
		var strSeparatorArray = new Array("-"," ","/",".");
		var intElementNr;
		var strMonthArray = new Array(12);
		var strMonthAbbrArray = new Array(12);
	
		strMonthArray[0] = "January";
		strMonthArray[1] = "February";
		strMonthArray[2] = "March";
		strMonthArray[3] = "April";
		strMonthArray[4] = "May";
		strMonthArray[5] = "June";
		strMonthArray[6] = "July";
		strMonthArray[7] = "August";
		strMonthArray[8] = "September";
		strMonthArray[9] = "October";
		strMonthArray[10] = "November";
		strMonthArray[11] = "December";

		strMonthAbbrArray[0] = "Jan";
		strMonthAbbrArray[1] = "Feb";
		strMonthAbbrArray[2] = "Mar";
		strMonthAbbrArray[3] = "Apr";
		strMonthAbbrArray[4] = "May";
		strMonthAbbrArray[5] = "Jun";
		strMonthAbbrArray[6] = "Jul";
		strMonthAbbrArray[7] = "Aug";
		strMonthAbbrArray[8] = "Sep";
		strMonthAbbrArray[9] = "Oct";
		strMonthAbbrArray[10] = "Nov";
		strMonthAbbrArray[11] = "Dec";

		// Set Delimiters to a period
		strDate = strDate.replace(/-|\/|\\|,|\s/g, ".");

		// Remove duplicate deliminators
		strDate = strDate.replace(/\.+/g, ".");

		// Break date into individual elements
		for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) 
		{
			if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) 
			{
				strDateArray = strDate.split(strSeparatorArray[intElementNr]);
				if (strDateArray.length == 3) 
				{
					strDay = strDateArray[0];
					strMonth = strDateArray[1];
					strYear = strDateArray[2];
				}
				//else if (strDateArray.length == 2) 
				//{
				//	strDay = "01";
				//	strMonth = strDateArray[0];
				//	strYear = strDateArray[1];
				//}
				else 
        {
					err=1;
					errmsg = "Invalid date format, specify month, day, and year.";
          break;
				}
				booFound = true;
			}
		}

		//Check for a date with no breaks. Checking for format: mmddyyyy or mmddyy
		if (booFound == false) 
		{
			if ((strDate.length == 6) || (strDate.length == 8))
			{
				strDay = strDate.substr(0, 2);
				strMonth = strDate.substr(2, 2);
				strYear = strDate.substr(4);
		  }
			else
			{
				err=12;
				errmsg = "Invalid date format.";
			}
		}
		
		// US style format
		if (strDatestyle == "US") 
		{
			strTemp = strDay;
			strDay = strMonth;
			strMonth = strTemp;
		}

		//alertmsg ("Error Code = " + err + "\nMonth = " + strMonth + "\nDay = " + strDay + "\nYear = " + strYear);

		if (err == 0)
		{
			// Convert date from 2 digit to 4 digit year
			if (strYear.length == 2) 
			{
				if (parseInt(strYear) > 29)
					strYear = '19' + strYear
				else
					strYear = '20' + strYear;
			}
			else if (strYear.length != 4)
			{
				err=13;
				errmsg = "Invalid year format.";
			}
	
			intYear = parseInt(strYear, 10);
			if ((isNaN(intYear) || (parseInt(strYear) != strYear)) && (err == 0)) 
			{
				err = 5;
				errmsg = "Year contains invalid characters.";
			}
			
			intDay = parseInt(strDay, 10);

			//alertmsg("intDay = " + intDay); 
			//alertmsg("strDay = " + strDay); 
			//tstrday = "";
			//tstrday = parseInt(strDay);
			//alertmsg("tstrday = " + tstrday); 
			//tstrday = '0' + parseInt(strDay);
			//alertmsg("tstrday = " + tstrday); 
			//tstrday = tstrday.substring(tstrday.length, tstrday.length-2);
			//alertmsg("tstrday = " + tstrday); 
			
			//if ((isNaN(intDay) || (parseInt(strDay) != strDay))  && (err == 0))
			//if ((isNaN(intDay) || ( tstrday != strDay))  && (err == 0))
			if (isNaN(intDay) && (err == 0))
			{
				err = 4;
				errmsg = "Day contains invalid characters.";
			}

			//alertmsg ("Error Code = " + err + "\nIntDay = " + intDay);
			
			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;
					}
					else if (strMonth.toUpperCase() == strMonthAbbrArray[i].toUpperCase()) 
					{
						intMonth = i+1;
						strMonth = strMonthAbbrArray[i];
						i = 12;
					}
				}
				
				if (isNaN(intMonth)) 
				{
					err = 2;
					errmsg = "Date contains an invalid month.";
				}
			}
			else
			{
				if ((parseInt(strMonth) != strMonth)) 
				{
					err=3;
					errmsg = "Month contains invalid characters.";
				}
			}
			
			if (err == 0)
			{
				if (intMonth>12 || intMonth<1) 
				{
					err = 6;
					errmsg = "Month is not a valid number.";
				}
		
				if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intDay > 31 || intDay < 1)) 
				{
					err = 7;
					errmsg = "Day is not a valid number.";
				}					
				
				if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intDay > 30 || intDay < 1)) 
				{
					err = 8;
					errmsg = "Day is not a valid number.";
				}
				
				if (intMonth == 2) 
				{
					if (intDay < 1) 
					{
						err = 9;
						errmsg = "Day is not a valid number.";
					}
		
					if (LeapYear(intYear) == true) 
					{
						if (intDay > 29) 
						{
							err = 10;
							errmsg = "Day is not a valid number.";
						}
					}
					else 
					{
						if (intDay > 28) 
						{
							err = 11;
							errmsg = "Day is not a valid number.";
						}
					}
				}
			}
		}
		
		//If the field is valid, write a standard format (mm/dd/yyyy) into the field
		if (err == 0)
			Form[field].value = intMonth + "/" + intDay + "/" + intYear;
  }

	// Raise validation flag if error.	
  if (err != 0)
	{
		//alertmsg ("Error #" + err + ": " + errmsg);
    ValidateFail(field);
	}
}
	
function LeapYear(intYear) 
{
	if (intYear % 100 == 0) 
	{
		if (intYear % 400 == 0) 
		{ 
			return true; 
		}
	}
	else 
	{
		if ((intYear % 4) == 0) 
		{ 
			return true; 
		}
	}
	return false;
}

//=================================================================================================================================

function formatCurrency(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	cents = Math.floor((num*100+0.5)%100);
	num = Math.floor((num*100+0.5)/100).toString();
	if(cents < 10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
	return ('$' + num + '.' + cents);
}

//=================================================================================================================================

function alertmsg(msg)
{
	alert(msg);
}
