/////////////////////////////////////////////////////////
// Validate_Form
//    Validates the entire form by checking to see if 
//    user has already submitted this form, checking
//    that required questions were answered, and that
//    the email address being submitted is valid.
/////////////////////////////////////////////////////////
 function Validate_Form(f)
 {
	// Now iterate through all the required questions and make sure 
	// that there is a value for each one
	if (! validateRequiredQuestions(f) )
	{
		return false;
	}

	// Make sure the email address is a valid one
	// (Check only if it is in the 'text' field, not the 'hidden'
	if (f.email.type == 'text')
	{
		if (! emailCheck(f.email.value))
		{
			f.email.focus();
			window.scrollBy(0,-20);
			return false;
		}
	}

	return true;
}

/////////////////////////////////////////////////////////
// validateRequiredQuestions
//    Makes sure that all required fields in a form are
//    filled out before submitting the form.
/////////////////////////////////////////////////////////
function validateRequiredQuestions(f)
{
	//  using _REQ appended to field name to specify required field.
	//  Also, check email field for validity.

	// Pattern in the 'name' attribute that determines if 
	// it is a required field.
	var requiredPat               = /_REQ$/;
	var requiredQuestions         = "";
	var requiredQuestionPositions = "";

	// 1. Go through form and pickout the field names that 
	//   require an answer. 
	for (var i=0, j=document.forms[f].elements.length; i<j; i++) 
	{
		e = document.forms[f].elements[i];
		matchRequired=e.name.match(requiredPat); // match required regex

		// Don't add to array if it's not a required field.
		if (matchRequired != null)
		{
			// Keep track of the question names to see if we
			// have already looked at that question, and keep 
			// track of the index position of this element on
			// the form.
			if (requiredQuestions.indexOf( e.name ) == -1 )
			{
				requiredQuestions += "::" + e.name ;
				requiredQuestionPositions += "::" + i ;
			}
		}
	}

	// 2. Loop through fields, and by type, make test to see 
	//    if a value has been set. (The technique to validate 
	//    each type might differ.)
	var Positions = requiredQuestionPositions.split("::");
	var valid = true; // initalize to true in case no elements
					  // need to be validated.

	// Start at i = 1, so we can avoid the first "::"
	for (i = 1; i < Positions.length ; i++)
	{
		// clear 'valid' flag
		valid = false;
		
		// get the form element
		e = eval("document.forms["+f+"].elements[" + Positions[i] + "]");

		// check to see if something was selected for this question
		// a. radio/checkbox
		if (e.type == 'radio' || e.type == 'checkbox')
		{
			valid = ( isCheckboxRadioValid( eval("document.forms["+f+"]." + e.name) ) );
		}
		// b. select
		else if (e.type == 'select-one' || e.type == 'select-multiple' || e.type == 'select')
		{
			valid = (e.options[e.selectedIndex].value != "");
		}
		// c. text
		else //if (e.type == 'hidden' || e.type == 'password' || e.type == 'text' || e.type == 'textarea')
		{
			valid = (e.value != "");
		}
		
		if (e.name.indexOf('email_REQ') > -1)
		{
			valid = emailCheck(e.value);
		}

		// 3. If no value was found for the question, we should return
		// a message asking the user to input a value, and focus on
		// the question that needs to be answered.
		// alert( i + " : " + e.name + " : " + e.value + " : " + e.type + " : " + matchNums[0] + " : " + valid);
		if (! valid)
		{
			// Form the error text that we will be displaying to user.
			// NOTE: Reading the 'alt' attribute is not supported by NS4. 
			questionText = e.alt;
			msg = "Please make sure all required questions are answered and press \"Submit\" to continue.";
			if (questionText) 
				msg = "The field \""+ questionText + "\" is required in order to submit this form. " + msg;
			
			// Display message, focus on field (if field support it) 
			// and return
			alert( msg );
			e.focus();
			window.scrollBy(0,-40);
			return valid;
		}
	}

	// all required fields aren't empty. 
	// 'valid' should always be true here.
	return valid;
}

/////////////////////////////////////////////////////////
// isCheckboxRadioValid
//    does the checkbox/radio element have a value?
/////////////////////////////////////////////////////////
function isCheckboxRadioValid(e)
{
  //  e is of the form "document.forms[0].questionDDD"
  for (i=0; i < e.length; i++) 
  {
    if (e[i].checked == true) 
    {        
      return true;
    } 
  }
  return false;
}

/////////////////////////////////////////////////////////
// emailCheck
//    Check the validity of an email address.
/////////////////////////////////////////////////////////
function emailCheck (emailStr) 
{
   // convert the email to lowercase
   emailStr = emailStr.toLowerCase();

   // This script and many more are available free online at -->
   // The JavaScript Source!! http://javascript.internet.com -->

	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);

	if (matchArray==null) {
		alert("Email address seems incorrect (check @ and .'s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];

	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("Ths username contains invalid characters.");
			return false;
		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("The domain name contains invalid characters.");
			return false;
	   }
	}
	if (user.match(userPat)==null) {
		alert("The username doesn't seem to be valid.");
		return false;
	}
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
			alert("Destination IP address is invalid!");
			return false;
			}
		}
		return true;
	}

	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			alert("The domain name does not seem to be valid.");
			return false;
		}
	}

	if (checkTLD && domArr[domArr.length-1].length!=2 && 
	domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("The email address must end in a well-known domain or two letter " + "country.");
		return false;
	}

	if (len<2) {
		alert("This email address is missing a hostname!");
		return false;
	}

	return true;
}

/////////////////////////////////////////////////////////
// isValidObject
//    Test that an object in the form exists.
/////////////////////////////////////////////////////////
function isValidObject(objToTest) {
	if (null == objToTest) {
		return false;
	}
	if ("undefined" == typeof(objToTest) ) {
		return false;
	}
	return true;
}

/////////////////////////////////////////////////////////
// isValidUrl
//    Test that an object in the form exists.
/////////////////////////////////////////////////////////
function isValidUrl(s) {
   	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
   	return regexp.test(s);
}


/////////////////////////////////////////////////////////
// basename
//    Extract basename (actual filename) from URL or 
//    filepath.
/////////////////////////////////////////////////////////
function basename(path, suffix) {
	var b = path.replace(/^.*[\/\\]/g, '');
	if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
		b = b.substr(0, b.length-suffix.length);
	}
	return b;
}

/////////////////////////////////////////////////////////
// checkForFileInFileUpload
//    Ensure that a file to be uploaded is of a certain 
//    file type by checking it's extension.
/////////////////////////////////////////////////////////
function checkForFileInFileUpload(field, fileextension)
{
  var filepath = field.value;
  var filelength = parseInt(filepath.length) - 3;
  var fileext = filepath.substring(filelength,filelength + 3);

  if (filepath == "")
  {
      alert("Please upload a file of type '" + fileextension + "'");
      field.focus();
	  return false;
  }

  // first test to see if string ends in fileextension
  if ( fileext.toUpperCase() != fileextension.toUpperCase() )
  {
	  // not the right file type
	  alert("We only allow '"+fileextension+"' type.");
	  field.focus();
      return false;
  } 

  // check to see that starts with a letter. There's weird bug
  // in php FastCGI that doesn't properly upload filenames starting
  // with a number.
  var regexp = /^[a-zA-Z]/i;
  if(! regexp.test(basename(filepath)))
  {
     field.focus();
     alert("Filename needs to start with a letter");
     return false;
  }

  // passed all tests
  return true;

}

/////////////////////////////////////////////////////////
// checkForFileInFileUpload2
//    Ensure that a file to be uploaded is within an  
//    array of file type by checking it's extension.
/////////////////////////////////////////////////////////
function checkForFileInFileUpload2(field)
{
  var filepath = field.value;

  // allowed file extensions
  var allowedFilePattern=/\.(avi|bmp|csv|doc|dwg|dwf|dxf|gif|gz|html|jpe|jpeg|jpg|mov|mp3|mpg|pdf|png|ppt|ps|qt|rtf|txt|wav|wmv|wma|xls|xml|zip)$/;
  var matchArray=filepath.toLowerCase().match(allowedFilePattern);

  if (filepath == "")
  {
      alert("Please select a file for upload.");
      field.focus();
	  return false;
  }

  if (matchArray==null) {
      alert("File type is not supported. Unable to load this file. Please see supported file types.");
	  field.focus();
      return false;
  }
  var filext=matchArray[1];
  //alert (filext);

  // check to see that starts with a letter. There's weird bug
  // in php FastCGI that doesn't properly upload filenames starting
  // with a number.
  var regexp = /^[a-zA-Z]/i;
  if(! regexp.test(basename(filepath)))
  {
     field.focus();
     alert("Filename needs to start with a letter");
     return false;
  }

  // passed all tests
  return true;

}


///////////////// Date format validation ///////////////
var dtCh= "-";
var minYear=2000;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this;
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strYear=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strDay=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		alert("The date format  should be : yyyy-mm-dd");
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month");
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day");
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date ");
		return false;
	}
return true;
}


