// ----------------------------------------------------------------------
// Pixelcocoa - Craigy P - Javascript form validation
//
// CP - last update: 31/01/2007 - tidying up and commenting
//
// 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.
//
// ----------------------------------------------------------------------

var DECISION_vERROR = 0; // constant -- do not modify: means jscript wont work so leave validation to server
var DECISION_INVALID = 1; // constant -- do not modify: failed js validation
var DECISION_CONTINUE = 2; // constant -- do not modify: passed initial checks, do more

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 - used when setting focus

// --------------------------------------------
//                  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.
// Set focus routines are used when user entered
// data doesnt pass validation to make the
// incorrectly filled field the active one
// --------------------------------------------

function setFocusDelayed()
{
  global_valfield.focus();
}

function setfocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  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
{
  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 - added to style.css
}

// --------------------------------------------
//            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    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  if (!document.getElementById) 
    return DECISION_vERROR;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(infofield);
  if (!elem.firstChild) DECISION_vERROR;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text) DECISION_vERROR;  // infofield is wrong type of node  

  if (emptyString.test(valfield.value)) {
    if (required) {
      msg (infofield, "error", "ERROR: required");  
      setfocus(valfield);
      return DECISION_INVALID;
    }
    else {
      msg (infofield, "warn", "");   // OK
      return DECISION_vERROR;  
    }
  }
  return DECISION_CONTINUE;
}

// --------------------------------------------
//               validatePassword
// Validates the password and the confrm password
// Checks for max and min length and allows almost any char
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validatePassword  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var decision = commonCheck (valfield, infofield, required);
  if (decision == DECISION_vERROR) return true;
  if (decision == DECISION_INVALID) return false;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var checkOK = "0123456789.,[]{}=+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ()_:;'\\*^%$@<>?'"; 
  
  if (tfld.length > 20) {
  	msg (infofield, "error", "ERROR: Password cant be longer than 20 chars");
  	setfocus(valfield);
  	return false;
  }
  
  if (tfld.length < 6) {
  	msg (infofield, "error", "ERROR: password must be atleast 6 characters");
    setfocus(valfield);
    return false;
  }
  
  for (i = 0;  i < tfld.length;  i++)
  		{
    		ch = tfld.charAt(i);
			for (j = 0;  j < checkOK.length;  j++) {
	      		if (ch == checkOK.charAt(j)) {
					break; }
				if (j == checkOK.length-1){
					msg (infofield, "error", "ERROR: contains invalid characters");
    				setfocus(valfield);
    				return false;
    				break;
				}
			}
		}
  msg (infofield, "warn", "");
  return true;
}

// --------------------------------------------
//               validateUsername
// Validates the username
// Checks for max and min length and allows letter and numbers
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateUsername  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var decision = commonCheck (valfield, infofield, required);
  if (decision == DECISION_vERROR) return true;
  if (decision == DECISION_INVALID) return false;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var checkOK = "0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz "; 
  
  if (tfld.length > 15) {
  	msg (infofield, "error", "ERROR: Username cant be longer than 15 chars");
  	setfocus(valfield);
  	return false;
  }
  
  if (tfld.length < 5) {
  	msg (infofield, "error", "ERROR: Username must be atleast 5 characters");
    setfocus(valfield);
    return false;
  }
  
  for (i = 0;  i < tfld.length;  i++)
  		{
    		ch = tfld.charAt(i);
			for (j = 0;  j < checkOK.length;  j++) {
				if (ch == checkOK.charAt(j)) {
					break; }
				if (j == checkOK.length-1){
					msg (infofield, "error", "ERROR: contains invalid characters");
    				setfocus(valfield);
    				return false;
    				break;
				}
			}
		}
  msg (infofield, "warn", "");
  return true;
}

// --------------------------------------------
//               validateName
// Validates the first and second name
// No Checks for max or min length and only allows letters
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateName  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var decision = commonCheck (valfield, infofield, required);
  if (decision == DECISION_vERROR) return true;
  if (decision == DECISION_INVALID) return false;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz "; 
  
  if (tfld.length > 20) msg (infofield, "warn", "Name is canny long like - check it or die");
  	    
  for (i = 0;  i < tfld.length;  i++)
  		{
    		ch = tfld.charAt(i);
			for (j = 0;  j < checkOK.length;  j++) {
	      		if (ch == checkOK.charAt(j)) {
					break; }
				if (j == checkOK.length-1){
					msg (infofield, "error", "ERROR: contains invalid characters");
    				setfocus(valfield);
    				return false;
    				break;
				}
			}
		}
  msg (infofield, "warn", "");
  return true;
}

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

function validatePresent(valfield,   // element to be validated
                         infofield ) // id of element to receive info/error msg
{
  var decision = commonCheck (valfield, infofield, true);
  if (decision == DECISION_vERROR) return true;
  if (decision == DECISION_INVALID) return false;

  msg (infofield, "warn", "");  
  return true;
}

// ----------------------------------------------------
//               validateEmail
// Validates e-mail address and confirm email address
// Checks for correct format aswell as unusual address formats
// Returns true if so (and also if could not be executed because of old browser)
// ----------------------------------------------------

function validateEmail  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var decision = commonCheck (valfield, infofield, required);
  if (decision == DECISION_vERROR) return true;
  if (decision == DECISION_INVALID) return false;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
  if (!email.test(tfld)) {
    msg (infofield, "error", "ERROR: not a valid e-mail address");
    setfocus(valfield);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;
  if (!email2.test(tfld)) 
    msg (infofield, "warn", "Unusual e-mail address - check if correct");
  else
    msg (infofield, "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  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var decision = commonCheck (valfield, infofield, required);
  if (decision == DECISION_vERROR) return true;
  if (decision == DECISION_INVALID) return false;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/  ;
  if (!telnr.test(tfld)) {
    msg (infofield, "error", "ERROR: not a valid telephone number. Characters permitted are digits, space ()- and leading +");
    setfocus(valfield);
    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 (infofield, "error", "ERROR: " + numdigits + " digits - too short");
    setfocus(valfield);
    return false;
  }

  if (numdigits>14)
    msg (infofield, "warn", numdigits + " digits - check if correct");
  else { 
    if (numdigits<10)
      msg (infofield, "warn", "Only " + numdigits + " digits - check if correct");
    else
      msg (infofield, "warn", "");
  }
  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 decision = commonCheck (valfield, infofield, required);
  if (decision == DECISION_vERROR) return true;
  if (decision == DECISION_INVALID) return false;

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

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

  if (tfld>110) msg (infofield, "warn", "Older than 110: check correct");
  else {
    if (tfld<7) msg (infofield, "warn", "Fuck off child, you dont have 100 quid");
    else        msg (infofield, "warn", "");
  }
  return true;
}

// --------------------------------------------
//               validateCity
// At the minute validates the city if typed in
// In future should validate this from a UK city list which is populated from a file
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateCity  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var decision = commonCheck (valfield, infofield, required);
  if (decision == DECISION_vERROR) return true;
  if (decision == DECISION_INVALID) return false;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
  for (i = 0;  i < tfld.length;  i++)
  		{
    		ch = tfld.charAt(i);
			for (j = 0;  j < checkOK.length;  j++) {
	      		if (ch == checkOK.charAt(j)) {
					break; }
				if (j == checkOK.length-1){
					msg (infofield, "error", "ERROR: contains invalid characters");
    				setfocus(valfield);
    				return false;
    				break;
				}
			}
		}
  msg (infofield, "warn", "");
  return true;
}

// --------------------------------------------
//               validateAddress
// Validates the address lines
// These are not a required field and pobably dont need to be in future
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateAddress  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var decision = commonCheck (valfield, infofield, required);
  if (decision == DECISION_vERROR) return true;
  if (decision == DECISION_INVALID) return false;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var checkOK = "0123456789.+-_#,/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ()_";
  for (i = 0;  i < tfld.length;  i++)
  		{
    		ch = tfld.charAt(i);
			for (j = 0;  j < checkOK.length;  j++) {
	      		if (ch == checkOK.charAt(j)) {
					break; }
				if (j == checkOK.length-1){
					msg (infofield, "error", "ERROR: contains invalid characters");
    				setfocus(valfield);
    				return false;
    				break;
				}
			}
		}
  msg (infofield, "warn", "");
  return true;
}

// --------------------------------------------
//               validateCode
// Validates the postcode if entered
// basic checks and currently not required, needs enhancing based on postcode formats
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateCode  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var decision = commonCheck (valfield, infofield, required);
  if (decision == DECISION_vERROR) return true;
  if (decision == DECISION_INVALID) return false;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var checkOK = "0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
  
  if (tfld.length > 8) msg (infofield, "warn", "Postcode is unusually long, check if correct");
  if (tfld.length < 4) {
  	msg (infofield, "error", "ERROR: not a valid postcode");
    setfocus(valfield);
    return false;
  }
  
  for (i = 0;  i < tfld.length;  i++)
  		{
    		ch = tfld.charAt(i);
			for (j = 0;  j < checkOK.length;  j++) {
	      		if (ch == checkOK.charAt(j)) {
					break; }
				if (j == checkOK.length-1){
					msg (infofield, "error", "ERROR: contains invalid characters");
    				setfocus(valfield);
    				return false;
    				break;
				}
			}
		}
  msg (infofield, "warn", "");
  return true;
}

// ---------------------------------------------------------------------- 
//					valPass
// check that password and email match respective confirmation fields
//
// -----------------------------------------------------------------------
function valPass  (password,
				   confirmPass,
				   infofield)
{
    if (password.value != confirmPass.value)
    {
    		msg (infofield, "error", "ERROR: passwords dont match");
    		setfocus(confirmPass); 
    		return false;
	}
	else msg (infofield, "warn", "");
	return true
}
	
function valEmail  (email,
                     confirmEmail,
                     infofield) 
{    
    if (email.value != confirmEmail.value)
    {
    		msg (infofield, "error", "ERROR: email addresses dont match");
    		setfocus(confirmEmail); 
    		return false;
	}
	else msg (infofield, "warn", "");
	return true
	}

