// JavaScript Document
// Form validation for Sacramento Bike Hikers
// Date: 9/28/2008 1300hrs
//
// This file REQUIRES core.js for support routines


// SPAMCHECK()
//   check to see if the hidden textarea "realEyes" has had data entered
//   into it. if it was then a spammer's robot has filled it in.
//   spammer is then set to "true" or else spammer is "false"
function spamCheck()
{
  var spammer = false;
  var EyeElement = document.getElementById("realEyes");

  if (EyeElement.value == "")
  {
  	spammer = false; // no data entered
    EyeElement.value = "passed";
  }
    else
  {
    spammer = true; // data entered, must be a spammer
  } // if else
  
  // EyeElement.parentNode.removeChild(EyeElement); // delete the object
  return spammer;
} // humanCheck()


// Write the "to" and "from" fields for the form
// Hide email addresses from spammers
function toFrom()
{
	// Normal address to Ride Coordinator
	document.write('<INPUT TYPE=HIDDEN NAME=to VALUE=\"BHrscoordinator@bikehikers.com\">');
	
	// Test address to junior's email account via the bike hikers email
	// document.write('<INPUT TYPE=HIDDEN NAME=to VALUE=\"bill@bikehikers.com\">');
	
  document.write('<input type=\"hidden\" name="\print_blank_fields\" value=\"1\" />');
  document.write('<INPUT TYPE=HIDDEN NAME=subject VALUE=\"Ride Leader Sign-up\">');
} // toFrom()

// FORM VALIDATION ROUTINES  --------------------------------

var errMsg =
{

  // Checks for when a specified field is required
  required:
  {
    msg: "This field is required",
    test: function(obj,load)
    {
      // Make sure that ther is no text was entered in the field and that
      // we aren't checking on page load (showing 'field required' messages
      // would be annoying on page load)
      //return obj.value.length > 0 || load || obj.value == obj.defaultValue;
      return obj.value.length > 0; // && obj.value != obj.defaultValue;
    }
  },

	integer:
	{
		msg: "This field must be a number.",
		test: function(obj,load)
		{
			return !obj.value || /^\d*[1-9]\d*?/i.test(obj.value);
		}
	},

  dropdown:
  {
    msg: "Please make a selection.",
    test: function(obj,load)
    {
      // Make sure that ther is no text was entered in the field and that
      // we aren't checking on page load (showing 'field required' messages
      // would be annoying on page load)
      //return obj.value.length > 0 || load || obj.value == obj.defaultValue;
      return obj.selectedIndex != 0;
    }
  },

  // Makes sure that the field is a valid email address
  email:
  {
    msg: "Not a valid email address.",
    test: function(obj)
    {
      // Make sure that somthin was entered and that it looks like
      // an email address
      return !obj.value || /^[a-z0-9_+.-]+\@([a-z0-9_+.-]+\.)[a-z0-9]{2,4}$/i.test(obj.value);
    }
  },
  
  // Make sure the file is a phone number and
  // auit-formats the number if it is one
  phone:
  {
    msg: "Not a valid phone number",
    test: function(obj)
    {
      // Check to see if we have something that looks like
      // a valid phone number
      var m = /(\d{3}).*(\d{3}).*(\d{4})/.exec(obj.value);
      // If it is, seemingly, valid - force it into the specific
      // format that we desire: (123) 456-7890
      if ( m )
        obj.value = "(" + m[1] + ") " + m[2] + "-" + m[3];

      return !obj.value || m;
    }
  }
}

// Valid all the elements is a form
function validateForm( form, load )
{
  var valid = true;
  //alert("validateForm: form argument: " + form);
  //alert("validateForm: number of elements in current form: " + form.elements.length);
  // go through all the field element in the form
  // form.elements is an array of all fields in a form
  for (var i = 0; i < form.elements.length; i++)
  {
    //alert("validateForm: element type: " + form.elements[i].nodeName);
    // Hide any error messages, if they're being shown
    hideErrors( form.elements[i] );
    
    // Check to see if the field contains valid contents, or not
    if ( validateField( form.elements[i], load, i ))
    {
      valid = false;
    }
  }

  // Alert the user that all the fields are not okay
  if (!valid)
  {
    alert("Invaled fields found! Please recheck the form. See Red flagged items.");
  }
  
  // Return false if a fields does not have valid contents
  // true if all files are valid
  return valid;
}

  
// Validate a single field's contents
function validateField( elem, load, x )
{
  var errors = [];
  // Go through all the possible validation techniques
  for (var name in errMsg)
  {
    // See if the field has the class specified by the error type
    var re = new RegExp("(^|\\s)" + name + "(\\s|$)");
    // Check to see if the element has the class and that it passes the
    // validation test
    //alert("validateField:  element No:" + x + "  class test: " + re.test(elem.className ) + "  " + name);
    if ( re.test(elem.className ) && !errMsg[name].test( elem, load ))
    {
      // If it fail the validation, add the error message to the list
      errors.push( errMsg[name].msg);
    }
  }
    
  // Show the error messages, if they exist
  if ( errors.length )
    showErrors( elem, errors )
    
  // Return false if the field fails any of the validation routines
  return errors.length > 0
}

// Hide any validation error messages that are currently shown
function hideErrors( elem )
{
  // Find the next element after the curent field
  var next = elem.nextSibling;
  
  // If the next element is a SPAN and has a class of errors
  //alert("hideErrors: " + next.nodeName + " " + next.className)
  if ( next && next.nodeName == "BR" && next.className == "errors" )
  {
    // Remove it (which is our means of 'hiding')
    //alert("hikeErrors: remove span tag...")
    elem.parentNode.removeChild( next );
    next = elem.nextSibling;
    elem.parentNode.removeChild( next );
  }
}

// Show a set of error messages for a specific field within a form
function showErrors( elem, errors )
{
  // Find the next element after the field
  var next = elem.nextSibling;
  
  // If the field isn't one of our special error-holders
  if ( next &&  next.className != "errors")
  {
    // We need to make one instead
    next = document.createElement( "span" );
    next.className = "errors";
    // and then insert into the currect place in the DOM
    elem.parentNode.insertBefore( next, elem.nextSibling);
    // Now that we have a reference to the error holder UL
    // we then loop through all the error messages
    next.innerHTML = errors[0];
    next = document.createElement( "br" );
    next.className = "errors";
    // and then insert into the currect place in the DOM
    elem.parentNode.insertBefore( next, elem.nextSibling);
  }
} 

// This must run only after page_load
var formWatchStart =
{
  init: function()
  {
     // Find the first form on the page
     //alert("formWatchStart.init:  ");
     var form = document.getElementsByTagName( "form" )[0];
     Core.addEventListener( form, 'submit', formWatchStart.submitListener);
  },  
  submitListener: function(event)
  {
    if (!validateForm( this, true ))// validate the data
    {
      Core.preventDefault(event);
    }
    else if (spamCheck())
    {
      Core.preventDefault(event);
    }
  } //submitListener.function
} // formWatchStart

Core.start(formWatchStart);

