// Original created by: Chris Campbell
// www.particletree.com
// Adapted by: Arjan Nusselder / FBIDesign
// www.fbidesign.nl

// Set these variables
var cFormID     = 'FORM2'; // id of the form element
var cTextArea   = true; // set to True to validate textareas (otherwise only input fields are validated)
var cFbRequired = "*"; // feedback for empty required fields
var cFbFailed   = "[&nbsp;!&nbsp;]"; // feedback for incorrect fields
var cLang       = "nl"

//window.onload = attachFormHandlers;

// Attach the validation function to all the form elements
function attachFormHandlers()
{
  var regex = /^validate/;

  // Attachment of validation functions
// get the form
  var form = document.getElementById(cFormID) 
// make sure were on a newer browser
  if (document.getElementsByTagName)          
  {
    // prep input fields
// store all input fields
    var objInput = document.getElementsByTagName('input');       
    for (var iCounter=0; iCounter<objInput.length; iCounter++) {
// find some less cpu intensive way to do this, ie. a startsWith() function
      if (regex.test(objInput[iCounter].className)) { 
// attach the onchange to each input field
        objInput[iCounter].onblur = function(){return attach(this);} 
// try to precheck everything
        attach(objInput[iCounter]);                                  
      }
    }

    if (cTextArea) {
      // prep textarea fields
// store all textarea fields
      var objInput = document.getElementsByTagName('textarea');    
      for (var iCounter=0; iCounter<objInput.length; iCounter++) {
// attach the onchange to each input field
        objInput[iCounter].onblur = function(){return attach(this);} 
// try to precheck everything
        attach(objInput[iCounter]);                                  
      }
    }
  }

// attach validate() to the form
  form.onsubmit = function(){return validate();} 
}

// 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
  var sRegEx;
  gContinue = true; 

// get all the rules from the input box classname
  sRules = objInput.className.split(' '); 
  sValidate    = sRules[0]; // validate means we will validate the field
  sRequired    = sRules[1]; // required means field is required
// typecheck are additional validation rules (ie. email, phone, date)
  sTypeCheck   = sRules[2]; 
  sFeedbackLoc = sRules[3]; // feedbackLoc is the td id where feedback is sent to.
// validateRequired() checks if it is required and then sends back feedback
  sFeedback = validateRequired(sRequired, sVal, sTypeCheck); 

// If it is required and blank gContinue is false and we don't validate anymore.
  if (gContinue)  
      // 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})$/;
        if (cLang == "nl") {
          sHelp = "Alleen letters, spaties en punten zijn toegestaan.";
        }
        else if (cLang == "en") {
          sHelp = "Only letters, spaces and periods are allowed.";
        }
        break;
      case "email":
        sRegEx = /^[a-zA-Z\xc0-\xff0-9._-]+@([a-zA-Z\xc0-\xff0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
        if (cLang == "nl") {
          sHelp = "Ongeldig e-mail adres.";
        }
        else if (cLang == "en") {
          sHelp = "Invalid email address.";
        }
        break;
      case "postcode":
        sRegEx = /^([a-zA-z\xc0-\xff0-9 \.\-\/]{2,56})$/;
        if (cLang == "nl") {
          sHelp = "Ongeldige postcode.";
        }
        else if (cLang == "en") {
          sHelp = "Invalid postal code, only letters, numbers and spaces are allowed.";
        }
        break;
      case "telefoon":
        sRegEx = /^[0-9\+\-\(\) ]{9,20}$/;
        if (cLang == "nl") {
          sHelp = "Alleen cijfers, +, (, ) en spaties toegestaan.";
        }
        else if (cLang == "en") {
          sHelp = "Only numbers, +, (, ) and spaces allowed.";
        }
        break;
      case "alnum":
        sRegEx = /^([a-zA-z\xc0-\xff0-9 \.\-\/]{2,56})$/;
        if (cLang == "nl") {
          sHelp = "Alleen cijfers of letters zijn toegestaan.";
        }
        else if (cLang == "en") {
          sHelp = "Only numbers and letters allowed.";
        }
        break;
      case "datum":
        sRegEx = /^([a-zA-z0-9\/\\ \.\-]{2,56})$/;
        if (cLang == "nl") {
          sHelp = "Ongeldig datum-weergave.";
        }
        else if (cLang == "en") {
          sHelp = "Invalid date.";
	}
        break;
      case "largetext":
        sRegEx = /^([\s\w\d\.,\-\/?]{2,512})$/;
        if (cLang == "nl") {
          sHelp = "Alleen cijfers of letters zijn toegestaan (max. 512 karakters).";
        }
        else if (cLang == "en") {
          sHelp = "Only letters and numbers allowed (max. 512 characters).";
        }
        break;
      case "functie":
        sRegEx = /^([a-zA-Z0-9\(\)\',&:\/ \.\xc0-\xff-]{1,56})$/;
        if (cLang == "nl") {
          sHelp = "Alleen letters, spaties en punten zijn toegestaan.";
        }
        else if (cLang == "en") {
          sHelp = "Only letters, spaces en periods allowed.";
        }
        break;
      case "none":
        sRegEx = /./;
	sHelp = "huh";
// should be caught by validateRequired, if not, sFeedback = will generate an error 
        break; 
      default:
        sRegEx = /^$/;
        if (cLang == "nl") {
          sHelp  = "Unknown regexp!!"
        }
        else if (cLang == "en") {
          sHelp  = "Unknown regexp!!"
        }
      // create default, or disregard sFeedback below if no case is selected
    }
    sFeedback = validateRegEx(sVal,sRegEx,sHelp,sFeedbackLoc);
  }
  // after validation is complete return the feedback 
  document.getElementById(sFeedbackLoc).innerHTML = sFeedback;  
}

// Validate the input text and return feedback
function validateRequired(sRequired, sVal, sTypecheck)
{
// check if required if not, continue validation script
  if (sRequired == "required")  
  {
//=> sRequired == "required" && sVal == ""
// if it is required and blank then it is an error and continues to be required
    if (sVal == "")          
    {
      gContinue = false;
      return cFbRequired;
    }
//=> sRequired == "required" && sVal != "" && sTypecheck == "none"
// if its not blank and has no other validation requirements the field passes
    else if (sTypecheck == "none")  
    {
      gContinue = false;
      return "";
    }
  }
  // If it is not required, sFeedback should still be something, like ""
//=> sRequired != "required" && sVal == ""
  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()
{
//variable which will become an array holding all elements with the td tagname
  var tables; 

  // 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 == '' )
        {
//the color is changed to blank or stays black
        tables[i].style.color = '#050551';
        }
        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
      if (cLang == "nl") {
        alert ("Niet alles is correct ingevuld. Fouten staan gemarkeerd met een rode asteriks.");
      }
      else if (cLang == "en") {
        alert ("Not all textfields are filled out correctly. Errors are marked with a red asteriks.");
      }
      gErrors = 0;// reset errors to 0
      return false;
    }
    
    else 
    {
      return true;//set this to true in practice to allow the form to submit
    }
  

}

// show pop-up info
function showHelp(helpID)
{
  document.getElementById(helpID).style.visibility="visible";
  document.getElementById(helpID).style.width="400px";
}

function hideHelp(helpID)
{
  document.getElementById(helpID).style.visibility="hidden";
}

// fill the 'how did you find us'field based on the dropbox
function fillHow(){
  var hoeFill=document.getElementById("hoe");
  var hoeText = hoeFill.options[hoeFill.selectedIndex].text;
  if (hoeText=="Anders, namelijk") hoeText="";
  document.getElementById("hoe_anders").value = hoeText;
  attach(document.getElementById('hoe_anders'));
}

var activeID = "none";
function meerminder(vID) {
  if (activeID != "none") {
    document.getElementById(activeID).style.display="none"
  }
  activeID = vID;
  document.getElementById(activeID).style.display="block"
}
