// ----------------------------------------------------------------------
// Javascript form validation routines.
// Author: Stephen Poley
//
// File 2: checkboxes
// Uses the msg routine from formval.js
// ----------------------------------------------------------------------


// -----------------------------------------
//            commonCheck2
// Common code for checkbox validation routines to
// check for older / less-equipped browsers
// Returns true (validation passed) or
//         proceed (don't know yet)
// -----------------------------------------

var goodSoFar = 2;  

function commonCheck2   (vfld,   // element to be validated
                         ifld)   // id of element to receive info/error msg
{
  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  

  updateErrorText(ifld, "warning", "");  // clear any previous error message
  return goodSoFar;
}


// ----------------------------------------------------------------------
// 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 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 Jun 2006: minor improvements to variable names and layout
// ----------------------------------------------------------------------

var nbsp = 160;		// non-breaking space char
var node_text = 3;	// DOM text node-type
var emptyString = /^\s*$/ ;
var global_valfield;	// retain valfield 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()
{
  global_valfield.focus();
}

function setFocus(valId)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valId;
  setTimeout( 'setFocusDelayed()', 100 );
}


// --------------------------------------------
//                  updateErrorText(msg)
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------

function updateErrorText(errorId, errorClass, errorMessage) 
{
  // 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 HTMLtext;
  if (emptyString.test(errorMessage)) 
    HTMLtext = String.fromCharCode(nbsp);    
  else  
    HTMLtext = errorMessage;

  var elem = document.getElementById(errorId);
  elem.firstChild.nodeValue = HTMLtext;  
  elem.className = errorClass; 
}

// --------------------------------------------
//            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 goodSoFar = 2;  

function checkBasicFieldRequirements(valId,errorId,isRequired)
{
  //skip checks for unsupported old browsers
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var errorElement = document.getElementById(errorId);
  if (!errorElement.firstChild) return true;  // not available on this browser 
  if (errorElement.firstChild.nodeType != node_text) return true;  // errorId is wrong type of node  

  //check field is not empty
  if (emptyString.test(valId.value)) {
    if (isRequired) {
      updateErrorText(errorId, "error", "Required field.");  
      setFocus(valId);
      return false;
    }
    else {
      updateErrorText(errorId, "warning", "");
      return true;  
    }
  }
  
  return goodSoFar;
}

// --------------------------------------------
//            ensureValueEntered(validatePresent)
// Validate if something has been entered
// Returns true if so 
// --------------------------------------------

function ensureValueEntered(valId, errorId) 
{
  var passBasic = checkBasicFieldRequirements(valId, errorId, true);
  if (passBasic != goodSoFar) return passBasic;

  updateErrorText(errorId, "error", "*");  
  return true;
}

// --------------------------------------------
//               checkEmail(validateEmail)
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function checkEmail(valId, errorId, isRequired)
{
  var passBasic = checkBasicFieldRequirements(valId, errorId, isRequired);
  if (passBasic != goodSoFar) return passBasic;

  var valIdTrimmed = trim(valId.value);  // value of field with whitespace trimmed off
  //var validEmail = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;		//original
  var validEmail = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/  ;
  if (!validEmail.test(valIdTrimmed)) {

	//alert('invalid email');
	updateErrorText(errorId, "error", "Invalid e-mail address.");
    setFocus(valId);
    return false;
  }
  else{
	//alert('OK email');
    updateErrorText(errorId, "error", "*");
  	return true;
	}

}


// --------------------------------------------
//            checkTelNum(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 checkTelNum  (valId,errorId,isRequired)
{
  var passBasic = checkBasicFieldRequirements(valId, errorId, isRequired);
  if (passBasic != goodSoFar) return passBasic;

  var valIdTrimmed = trim(valId.value);
  var validTelNum = /^\+?[0-9 ()]+[0-9]$/  ;
  if (!validTelNum.test(valIdTrimmed)) {
    updateErrorText(errorId, "error", "Invalid telephone number.  Digits and brackets only please.");
    setFocus(valId);
    return false;
  }
    else{
	//alert('OK tel num');
    updateErrorText(errorId, "error", "*");
  	return true;
	}

    
  return true;
}


// --------------------------------------------
//            checkPostcode
// Validate postcode UK
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// --------------------------------------------

function checkPostcode(valId,errorId,isRequired)
{

  var passBasic = checkBasicFieldRequirements(valId, errorId, isRequired);
  if (passBasic != goodSoFar) return passBasic;

  var valIdTrimmed = trim((valId.value)); 
  var validUKPostcode = /^[A-Za-z]{1,2}[1-9][0-9]?[A-Za-z]? [0-9][A-Za-z]{2,}|GIR 0AA$/  ;
  if (!validUKPostcode.test(valIdTrimmed)) {
    updateErrorText(errorId, "error", "Invalid UK Postcode.");
    setFocus(valId);
    return false;
  }
  else{
	//alert('OK postcode');
    updateErrorText(errorId, "error", String.fromCharCode(nbsp));
  	return true;
	}

  }



// --------------------------------------------
//             validateAge
// Validate person's age
// Returns true if OK 
// --------------------------------------------

function validateAge    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);
  var ageRE = /^[0-9]{1,3}$/
  if (!ageRE.test(tfld)) {
    updateErrorText(infofield, "error", "ERROR: not a valid age");
    setFocus(valfield);
    return false;
  }

  if (tfld>=200) {
    updateErrorText(infofield, "error", "ERROR: not a valid age");
    setFocus(valfield);
    return false;
  }

  if (tfld>110) updateErrorText(infofield, "warning", "Older than 110: check correct");
  else {
    if (tfld<7) updateErrorText(infofield, "warning", "Bit young for this, aren't you?");
    else        updateErrorText(infofield, "warning", "");
  }
  return true;
}

