// File Name:   Validate.js
// Description: Contains functions that validate HTML forms.
// History:
// Version      Date                    Author                  Reason for Change
// V1.00        24 June 2000            Alistair Hughes         Created
//

// Name:  	isRadioButtonSelected
// Purpose:     Determines whether a radio button has been selected.
// Parameters:  radioButton - The radio button field.
// Returns:     True  - If a radio button has been selected.
//		False - If no radio button has been selected.
function isRadioButtonSelected(radioButton)
{
    var selection = null;	// The selected radio button field.
    var iCounter;		// Counter to iterate through the radio buttons.

    for(iCounter=0; iCounter < radioButton.length; iCounter++)
    {
    	if(radioButton[iCounter].checked)
        {
        	return true;
        }
    }
    return false;
}

// Name:	isFieldEmpty
// Purpose:     Determines whether a field is empty or not.
// Parameters:  emptyField - The field to check.
// Returns:     True  - If the field is empty.
//              False - If the field is not empty.
function isFieldEmpty(emptyField)
{
	if ((emptyField.type == "text") || (emptyField.type == "textarea") || (emptyField.type == "file") || (emptyField.type == "hidden") || (emptyField.type == "password"))
      	{
      		if (emptyField.value == "")
         	{
         		return true;
         	}
        }
   	else
      	{
      		if (!isRadioButtonSelectd(emptyField))
         	{
         		return false;
         	}
      	}
   	return false;
}
// Name:     	IsValidEmail
// Purpose:     Validates the email address.  Checks to see if the email address contains
//		a "@", ".", is more than 6 characters in length and does not contain spaces.
// Parameters:  emailField - The field to check.
// Returns:     True  - If we have a valid email address.
//              False - If we have an invalid email address.
function isValidEmail(emailField)
{
	if (isFieldEmpty(emailField))
      	{
      		return false;
      	}
    	if (emailField.value.indexOf("@")==-1
        	|| emailField.value.indexOf(".")==-1
        	|| emailField.value.indexOf(" ")!=-1
        	|| emailField.value.length<6)
       	{
       		return false;
       	}
    	else
       	{
       		return true;
       	}
}
// Name:   	IsValidDate
// Purpose:     Checks to see if the entered date is valid.  The date should be entered
//		in the form of DD/MM/YYYY
// Parameters:  dateField - The field to check.
// Returns:     True  - If we have a valid date.
//              False - If we have an invalid date.
function isValidDate(dateField)
{
       	var dtEnteredDate;		// The entered date.
        var arrEnteredDate;		// The entered date split into an array.
        var lEnteredDateMilliseconds;	// The entered date in milliseconds.
        var dtChkEnteredDate;		// The entered date after being converted from milliseconds.
        var dtChkEnteredDate1;          // The entered date after checking for numeric values.
        var dbAmericanDate;
        var lYear;

   	if (isFieldEmpty(dateField))
      	{
     		return false;
      	}

        // Make a copy of the entered field.
       	dtEnteredDate=dateField.value;
        // Split the entered date into its individual parts using the "/" character as the delimeter.
    	arrEnteredDate = dtEnteredDate.split("/")
        // Take the entered date and return the number of milliscecods since midnight 1 Jan 1970.
        // Only works with MM/DD/YYYY format so convert.
        dbAmericanDate = arrEnteredDate[1] + "/" +
                         arrEnteredDate[0] + "/" +
                         arrEnteredDate[2];
    	lEnteredDateMilliseconds = new Date(Date.parse(dbAmericanDate))
        // Do some date manipluation for Netscape.
        if (lEnteredDateMilliseconds.getYear() < 1000)
        {
        	lYear = lEnteredDateMilliseconds.getYear() + 1900;
        }
        else
        {
                lYear = lEnteredDateMilliseconds.getYear();
        }

        // Turn the number of milliseconds back into a date.
    	dtChkEnteredDate = (lEnteredDateMilliseconds.getDate()) +
                         "/" + (lEnteredDateMilliseconds.getMonth() + 1)+
                         "/" + lYear;
    	dtChkEnteredDate1 = (Math.abs(arrEnteredDate[0])) + "/" +
                            (Math.abs(arrEnteredDate[1])) + "/" +
                            (Math.abs(arrEnteredDate[2]));
        // Check to see if the date is valid.
    	if(dtChkEnteredDate1 != dtChkEnteredDate || dtChkEnteredDate == "NaN/NaN/NaN")
       	{
       		return false;
       	}
   	else
       	{
       		return true;
       	}
}
// Name:   	CompareDates
// Purpose:     Compares two dates.
// Parameters:  dtFirstDate  - The first date to compare.
//		dtSecondDate - The second date to compare.
// Returns:	0 - If the First Date and Secord date are equal.
//		1 - If the First Date is greater than the Second date.
//		2 - If the Second Date is greater that the First date.
function CompareDates(dtFirstDate, dtSecondDate)
{
 	var l_dtFirstDate;
        var l_arrFirstDate;
        var l_lFirstDateMil;
        var l_dtSecondDate;
        var l_arrSecondDate;
        var l_lSecondDateMil;
        var l_lRetValue;

        // Process the first string into a date.
        l_dtFirstDate=dtFirstDate.value;
        // Split the entered date into its individual parts using the "/" character as the delimeter.
        l_arrFirstDate = l_dtFirstDate.split("/")
        // Take the entered date and return the number of milliscecods since midnight 1 Jan 1970.
        // Only works with MM/DD/YYYY format so convert.
        l_dtFirstDate = l_arrFirstDate[1] + "/" +
                        l_arrFirstDate[0] + "/" +
                        l_arrFirstDate[2];
        l_lFirstDateMil = new Date(Date.parse(l_dtFirstDate))

        // Process the second string into a date.
        l_dtSecondDate=dtSecondDate.value;
        // Split the entered date into its individual parts using the "/" character as the delimeter.
        l_arrSecondDate = l_dtSecondDate.split("/")
        // Take the entered date and return the number of milliscecods since midnight 1 Jan 1970.
        // Only works with MM/DD/YYYY format so convert.
        l_dtSecondDate = l_arrSecondDate[1] + "/" +
                         l_arrSecondDate[0] + "/" +
                         l_arrSecondDate[2];
        l_lSecondDateMil = new Date(Date.parse(l_dtSecondDate))

	// Do the comparisons.
        if(l_lFirstDateMil < l_lSecondDateMil)
        {
                l_lRetValue = 2;
        }
        if(l_lFirstDateMil > l_lSecondDateMil)
        {
         	l_lRetValue = 1;
        }
        if(l_lFirstDateMil == l_lSecondDateMil)
        {
                l_lRetValue = 0;
        }
        return l_lRetValue;
}
// Name:	isNumeric
// Purpose:     Determines whether a string is numeric.
// Parameters:	strString - The string to check.
// Returns:     True  - If the string is numeric.
//		False - If the string is not numeric.
function isNumeric(strString)
{
  var checkOK = "0123456789";
  var checkStr = strString.value;
  var allValid = true;
  var decPoints = 0;
  var allNum = "";
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
    allNum += ch;
  }
  return(allValid)
}
// Name:        CheckString
// Purpose:     Determines whether the contents of the string match the supplied allowable contents.
// Parameters:  strString 	- The string to check.
//		checkOK 	- The contents that are allowed in the string.
// Returns:     True  - If the string is OK.
//              False - If the string is not OK.
function CheckString(strString, checkOK)
{
  var checkStr = strString.value;
  var allValid = true;
  var decPoints = 0;
  var allNum = "";
  for (i = 0;  i < checkStr.length;  i++)
  {
    ch = checkStr.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
      if (ch == checkOK.charAt(j))
        break;
    if (j == checkOK.length)
    {
      allValid = false;
      break;
    }
    allNum += ch;
  }
  return(allValid)
}


// Name: hasAltAttribute
// Purpose: To parse the text to make sure that all images have alt attributes
// Parameters:  strString 	- The text to be parsed
//		strErrorMessage	- The error message to display if alt text is missing
// Returns: True or False depending on whether alt text was missing
function imagesWithoutAltAttribute(strString, strErrorMessage)
{

	var imgRe = new RegExp("IMG", "i");
	var altRe = new RegExp("alt=", "i");
	var srcRe = new RegExp("src=", "i");
	var thisString;
	var stringArray;
	var imageStringArray;
	var result;
	var filename;
						
	thisString = strString.value;
	stringArray = thisString.split('<');
	
	// Reuse string to store images in error
	thisString = "";
						
	for (var i=0; i<stringArray.length; i++)
	{
		if (stringArray[i] != null)
		{
			imageStringArray = stringArray[i].match(imgRe);
			
			if (imageStringArray != null)
			{
   				// This is an img tag, is there an alt attribute?
				result = stringArray[i].match(altRe);
				if (result == null)
				{
					// no alt tag found
					// Extract the file name from the img tag
					
					// Split the tag by quotes
					filename = stringArray[i].split('"');
					var j;
					for (j=0; j<filename.length; j++)
					{
						// search for src attribute
						result = filename[j].match(srcRe);
						if (result != null)
						{
							// src attribute found so file name is next string in array
							thisString = thisString  + "\n" + filename[j+1];
							break;
						}
					}
				}
			}
		}
	}
	if (thisString != "")
	{
		alert(strErrorMessage + thisString);
		return(true);
	}
	else
	{
		return(false);
	}
}

function ReplaceCharacters(strStringToReplace)
{
	var strResult;
	objRegEx = new RegExp("’", "g");
	strResult = strStringToReplace.replace(objRegEx, "'");
	
	objRegEx = new RegExp("–", "g");
	strResult = strResult .replace(objRegEx, "-");

	objRegEx = new RegExp("“", "g");
	strResult = strResult .replace(objRegEx, '"');

	objRegEx = new RegExp("”", "g");
	strResult = strResult .replace(objRegEx, '"');

	return(strResult);
}

// Name:        isValidIPAddress
// Purpose:     Determines whether the contents of the element passed is a valid ip address format.
// Parameters:  el    - The string to check.
// Returns:     True  - If the ip address is OK.
//              False - If the ip address is not OK.
function isValidIPAddress(el)
{
	var subnetString, subnet;
	var ipAddress = el.value;
	var subnets = ipAddress.split('.');
	if ( subnets.length == 4 )
	{
		for( var i=0; i<subnets.length; i++ )
		{
			subnetString = subnets[i];
			subnet = parseInt(subnetString, 10);
			if ( isNaN(subnet) || (subnetString != subnet) || (subnet > 255) )
			{
				return false;
			}
		}
		return true;
	}
	return false;
}
