// ----------------------------------------------------------------------
// Javascript form validation routines.
// Author: Stephen Poley
//
// Simple routines to quickly pick up obvious typos.
// All validation routines return true if executed by an older browser:
// in this case validation must be left to the server.
//
// Update Aug 2004: have tested that IE 5.0 and IE 5.5 both support DOM model
// sufficiently well, so innerHTML option removed (redundant).
//
// Update Jun 2005: discovered that reason IE wasn't setting focus was
// due to an IE timing bug. Added 0.1 sec delay to fix.
//
// Update Oct 2005: minor tidy-up: unused parameter removed
// 
// Update May 2007 (k.douglass): modified several functions to suit
//
// Update Sept. 2007 (k.douglass): added several functions to suit
//                                 consolidated the two files to cut down on
//                                 the extra http request ;)
// ----------------------------------------------------------------------

var nbsp = 160;    // non-breaking space char
var node_text = 3; // DOM text node-type
var emptyString = /^\s*$/
var glb_vfld;      // retain vfld for timer thread

// -----------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// -----------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '')
};


// -----------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// -----------------------------------------

function setFocusDelayed()
{
  glb_vfld.focus()
}

function setfocus(vfld)
{
  // save vfld in global variable so value retained when routine exits
  glb_vfld = vfld;
  setTimeout( 'setFocusDelayed()', 100 );
}


// -----------------------------------------
//                  msg
// Display warn/error message in HTML element
// commonCheck routine must have previously been called
// -----------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  

  elem.className = msgtype;   // set the CSS class to adjust appearance of message

};

// -----------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// -----------------------------------------

var proceed = 2;

function commonCheck    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);
  if (!elem.firstChild)
    return true;  // not available on this browser
  if (elem.firstChild.nodeType != node_text)
    return true;  // ifld is wrong type of node  

  if (emptyString.test(vfld.value)) {
    if (reqd) {
      msg (ifld, "errmsg", "Required");
      setfocus(vfld);
      return false;
    }
    else {
      msg (ifld, "warn", "");   // OK
      return true;
    }
  }
  return proceed;
}


// -----------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// -----------------------------------------

function validatePresent(vfld,   // element to be validated
                         ifld )  // id of element to receive info/error msg
{	
  var stat = commonCheck (vfld, ifld, true);
  
  if (stat != proceed) return stat;

  msg (ifld, "warn", "");  
  return true;
};




// -----------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// -----------------------------------------

function validateEmail  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  if (!email.test(tfld)) {
    msg (ifld, "errmsg", "Not Valid");
    setfocus(vfld);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld))
    msg (ifld, "warn", ""); // orig: msg (ifld, "errmsg", "Unusual - check if correct");
  else                      // disengaged to avoid maint. prob. as more domain exts are added
    msg (ifld, "warn", "");
  return true;
};


// -----------------------------------------
//            validateTelnr
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// -----------------------------------------

function validateTelnr  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/
  if (!telnr.test(tfld)) {
    msg (ifld, "errmsg", "ERROR: not a valid telephone number. Characters permitted are digits, space ()- and leading +");
    setfocus(vfld);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<6) {
    msg (ifld, "errmsg", "ERROR: " + numdigits + " digits - too short");
    setfocus(vfld);
    return false;
  }

  if (numdigits>14)
    msg (ifld, "errmsg", numdigits + " digits - check if correct");
  else { 
    if (numdigits<10)
      msg (ifld, "errmsg", "Only " + numdigits + " digits - check if correct");
    else
      msg (ifld, "warn", "");
  }
  return true;
};



// -----------------------------------------
// validateUsers
// -----------------------------------------

function validateUsers  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var numonly = /[0-9]/
  if (!numonly.test(tfld)) {
    msg (ifld, "errmsg", "Digits Only");
    setfocus(vfld);
    return false;
  }
  else
    msg (ifld, "warn", "");

  return true;
};


// -------------------------------------------
// match state requirement to USA or Canada
// -------------------------------------------

function checkCountry( vfld )
{

  if (!document.getElementById) {
    return true;  // not available on this browser - leave validation to the server
  }
  
  var star = document.getElementById('statestar');
  var label = document.getElementById('statelabel');
  var st = document.getElementById('state');
  var st_msg = document.getElementById('msg_state');

  if ((vfld.value != 'US') && (vfld.value != 'CA') ) {

    st.setAttribute('disabled', 'disabled');
    star.style.color = "#AAA";
    label.style.color = "#AAA";

    // If the state element has been disabled after an err msg has been displayed,
    // remove the err msg also since it is no longer required
    if (st_msg.className == 'errmsg') {
      msg ('msg_state', "warn", "");
    }

  } else {
    st.removeAttribute('disabled');
    star.style.color = "#9C231C";
    label.style.color = "#000";
  }

  return true;
}



// -------------------------------------------
// validateSelects1 - for country
// -------------------------------------------

function validateSelects1 (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{

  if (!document.getElementById)
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);
  
  if(elem == null) return true;
  
  if (!elem.firstChild)
    return true;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text)
    return true;  // ifld is wrong type of node

  if (vfld.value == '--') {
    if (reqd) {
      msg (ifld, "errmsg", "Required");
      setfocus(vfld);
      return false;
    }
    else {

      msg (ifld, "warn", "");   // OK  - left intact in case we want to msg on other cond.
      return true;  
    }
  }

  return true;
}


// -------------------------------------------
// validateSelects2 - for state
// -------------------------------------------

function validateSelects2 (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{

  if (!document.getElementById) {
    return true;  // not available on this browser - leave validation to the server
  }

  var elem = document.getElementById(ifld);
  if (!elem.firstChild)
    return true;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text)
    return true;  // ifld is wrong type of node

  var st = document.getElementById('state');

  //if (!st.hasAttribute('disabled')) {
    if (vfld.value == '--') {
      if (reqd) {
        msg (ifld, "errmsg", "Required");
        setfocus(vfld);
        return false;
      }
      else {
        msg (ifld, "warn", "");   // OK  - left intact in case we want to msg on other cond.
        return true;
      }
    }
  //}

  return true;
}


// -------------------------------------------
// Parent Method called on submit
// -------------------------------------------


var errMsgFlag = false;

  function RFI_validate() {

    var elem;
    var errs=0;
    // execute all element validations in reverse order, so focus gets
    // set to the first one in error.
    
	if (!validateSelects1(document.forms.RFIform["00N000000072UE1"],  'msg_jobRol', true)) errs += 1;
	if (!validateSelects1(document.forms.RFIform["00N00000007sArQ"],  'msg_role', true)) errs += 1;
	
	
    if (!validateSelects1(document.forms.RFIform["00N00000004waIu"],  'msg_referral', true)) errs += 1;

    if (!validateUsers(document.forms.RFIform["00N00000004x1fY"],  'msg_potential', true)) errs += 1;
    // if (!validatePresent(document.forms.RFIform["00N00000004x1fY"],  'msg_potential')) errs += 1;

    if (!validateSelects1(document.forms.RFIform["00N000000072UE6"],  'msg_solution', true)) errs += 1;

    if (!validatePresent(document.forms.RFIform.city,  'msg_city')) errs += 1;
	
	if ((document.getElementById('country').value == 'US') || (document.getElementById('country').value == 'CA') ) {
    	if (!validateSelects2(document.forms.RFIform.state, 'msg_state', true)) errs += 1;
	}
	
    if (!validateSelects1(document.forms.RFIform.country, 'msg_country', true)) errs += 1;
    if (!validateEmail  (document.forms.RFIform.email, 'msg_email', true)) errs += 1;
    if (!validatePresent(document.forms.RFIform.phone,  'msg_phone')) errs += 1;
    if (!validatePresent(document.forms.RFIform.company,  'msg_company')) errs += 1;
	
    if (!validateSelects1(document.forms.RFIform.title,  'msg_title', true)) errs += 1;
	
    if (!validatePresent(document.forms.RFIform.last_name,  'msg_last')) errs += 1;
    if (!validatePresent(document.forms.RFIform.first_name,  'msg_first')) errs += 1;

	



    // replaced this with the inline error msg at the top of the form (kd)
    //if (errs>1)  alert('There are fields which need correction before sending');
    //if (errs==1) alert('There is a field which needs correction before sending');

    if((!errMsgFlag) && (errs > 0)) {
      
      errMsgFlag = true;

      // Message that appears at the top of the form
      var userMsg = '';
      if (errs>1)  userMsg = 'Please correct the fields indicated below.';
      if (errs==1) userMsg = 'Please correct the field indicated below.';
    
      // create a text node
      var msgNode = document.createTextNode(userMsg);
    
      // grab the existing container div and add the class name
      var userMsgBox = document.getElementById("validationMsg");
      userMsgBox.className = "errorBox";
    
      // append the text node to the div
      userMsgBox.appendChild(msgNode);
    
      // change the container's inline display to block
      userMsgBox.style.display = 'block';

    } else {  // If the form validates

       // If the user has selected a state before selecting a country other than US or Canada, ensure the 
       // value sent for state is "--" for proper distribution of the lead
       var sfld = document.forms.RFIform.country.value;

       if ((sfld != 'US') && (sfld != 'CA') ) {
          document.getElementById('state').options[document.getElementById('state').selectedIndex].value = "--";
       }

    }

    return (errs==0);
  };






