// Original created by: Chris Campbell
// www.particletree.com
// Adapted by: Arjan Nusselder / FBIDesign
// www.fbidesign.nl

// Set these variables
const cFormID = 'contactform'; // id of the form element
const cTextArea = true; // set to True to validate textareas (otherwise only input fields are validated)
const cFbRequired = "*"; // feedback for empty required fields
const cFbFailed = "[&nbsp;!&nbsp;]"; // feedback for incorrect fields

window.onload = attachFormHandlers;

// Attach the validation function to all the form elements
function attachFormHandlers()
{
  // Attachment of validation functions
  var form = document.getElementById(cFormID) // get the form
  if (document.getElementsByTagName)          // make sure were on a newer browser
  {
    // prep input fields
    var objInput = document.getElementsByTagName('input');       // store all input fields
    for (var iCounter=0; iCounter<objInput.length; iCounter++) {
      objInput[iCounter].onblur = function(){return attach(this);} // attach the onchange to each input field
      attach(objInput[iCounter]);                                  // try to precheck everything  
    }

    if (cTextArea) {
      // prep textarea fields
      var objInput = document.getElementsByTagName('textarea');    // store all textarea fields
      for (var iCounter=0; iCounter<objInput.length; iCounter++) {
        objInput[iCounter].onblur = function(){return attach(this);} // attach the onchange to each input field
        attach(objInput[iCounter]);                                  // try to precheck everything
      }
    }
  }

  form.onsubmit = function(){return validate();} // attach validate() to the form
}

// Validate the current form element
var gContinue = true;
function attach(objInput)
{
  sVal = objInput.value; //get value inside of input field
  var sFeedBack; //feedback is the feedback message sent back to the user
  gContinue = true; 

  sRules = objInput.className.split(' '); // get all the rules from the input box classname
  sValidate    = sRules[0]; // validate means we will validate the field
  sRequired    = sRules[1]; // required means field is required
  sTypeCheck   = sRules[2]; // typecheck are additional validation rules (ie. email, phone, date)
  sFeedbackLoc = sRules[3]; // feedbackLoc is the td id where feedback is sent to.
  sFeedback = validateRequired(sRequired, sVal, sTypeCheck); // validateRequired() checks if it is required and then sends back feedback

  if (gContinue)  // If it is required and blank gContinue is false and we don't validate anymore.
      // This is done because if it is blank it will also fail other tests.
      // We don't want to spam the user with INVALID EMAIL!! if the field is still blank.
  {
    // check the different validation cases (ie: email, phone, etc.)
    switch (sTypeCheck)
      {
    // Actually used:
      case "name":
        sRegEx = /^([a-zA-Z \.\xc0-\xff-]{1,56})$/;
        sHelp = "Alleen letters, spaties en punten zijn toegestaan.";
        sFeedback = validateRegEx(sVal,sRegEx,sHelp,sFeedbackLoc);
        break;
      case "email":
        sRegEx = /^[a-zA-Z\xc0-\xff0-9._-]+@([a-zA-Z\xc0-\xff0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
        sHelp = "Ongeldig e-mail adres.";
        sFeedback = validateRegEx(sVal,sRegEx,sHelp,sFeedbackLoc);
        break;
      case "postcode":
        sRegEx = /^[1-9]{1}[0-9]{3} ?[a-zA-Z]{2}$/;
        sHelp = "Ongeldige postcode.";
        sFeedback = validateRegEx(sVal,sRegEx,sHelp,sFeedbackLoc);
        break;
      case "telefoon":
        sRegEx = /^[0-9\+\-\(\) ]{9,20}$/;
        sHelp = "Alleen cijfers, +, (, ), en spaties toegestaan.";
        sFeedback = validateRegEx(sVal,sRegEx,sHelp,sFeedbackLoc);
        break;
      case "alnum":
        sRegEx = /^([a-zA-z\xc0-\xff0-9 \.\-\/]{2,56})$/;
        sHelp = "Alleen cijfers of letters zijn toegestaan.";
        sFeedback = validateRegEx(sVal,sRegEx,sHelp,sFeedbackLoc);
        break;
      case "datum":
        sRegEx = /^([a-zA-z0-9\/\\ \.\-]{2,56})$/;
        sHelp = "Ongeldig datum-weergave.";
        sFeedback = validateRegEx(sVal,sRegEx,sHelp,sFeedbackLoc);
        break;
      case "largetext":
        sRegEx = /^([\s\w\d\.,\-\/?!]{2,512})$/;
        sHelp = "Alleen cijfers of letters zijn toegestaan (max. 512 karakters).";
        sFeedback = validateRegEx(sVal,sRegEx,sHelp,sFeedbackLoc);
        break;
    }
  }
  // after validation is complete return the feedback 
  document.getElementById(sFeedbackLoc).innerHTML = sFeedback;  
}

// Validate the input text and return feedback
function validateRequired(sRequired, sVal, sTypecheck)
{
  if (sRequired == "required")  // check if required if not, continue validation script
  {
       if (sVal == "")          // if it is required and blank then it is an error and continues to be required
    {
      gContinue = false;
      return cFbRequired;
     }
      else if (sTypecheck == "none")  // if its not blank and has no other validation requirements the field passes
    {
      return "";
    }
  }
  // If it is not required, sFeedback should still be something, like ""
  else if (sVal == "") // ie. it is not required
  {
    gContinue = false;
  }
  return "";
}


// Generic Validation Function
function validateRegEx(sVal, sRegEx, sHelp, sFeedbackLoc)
{
  var regex=sRegEx;
 
  if (regex.test(sVal))  // succes
  {
    return "";
  }
  else      // failure
  {
    sReturn = "<em onmouseover=\"showHelp('" + sFeedbackLoc + "-help')\" onmouseout=\"hideHelp('" + sFeedbackLoc + "-help')\">" + cFbFailed + "</em>";
    sReturn += "<p id=\"" + sFeedbackLoc + "-help\" class=\"info\">" + sHelp + "</p>";
    return sReturn;
  }
}


var gErrors = 0; //number of errors is set to none to begin with
function validate()
{
  var tables; //variable which will become an array holding all elements with the td tagname

  // store all <td> elements in the tables array
  tables = document.getElementsByTagName('td')

  //loop through all the <td> elements 
  for (i=0; i<tables.length; i++)
    {
    // if the class name of that td element is rules check to see if there are error warnings
    if (tables[i].className == "rules")
      {
        //if there is a thank you or its blank then it passes
        if (tables[i].innerHTML == 'Thank You' || tables[i].innerHTML == '' )
        {
        tables[i].style.color = '#050551';//the color is changed to blank or stays black
        }
        else
        {
        gErrors = gErrors + 1; //the error count increases by 1
        tables[i].style.color = '#ff0000';//error messages are changed to red
        }
      }
    }
    
    if (gErrors > 0){
      //if there are any errors give a message
      alert ("Niet alles is correct ingevuld. Fouten staan gemarkeerd met een rode asteriks.");
      gErrors = 0;// reset errors to 0
      return false;
    }
    
    else 
    {
      return true;//set this to true in practice to allow the form to submit
    }
  

}

		function showHelp(helpID)
		{
			document.getElementById(helpID).style.visibility="visible";
			document.getElementById(helpID).style.width="400px";
		}
		function hideHelp(helpID)
		{
			document.getElementById(helpID).style.visibility="hidden";
		}

