// FORM VALIDATION FUNCTIONS

function setbg(gotFocus, elID, color)
{
	var e = document.getElementById(elID)
	e.style.background=color
//	if (gotFocus) e.select();
}

function IsEmpty(aTextField) {
   if ((aTextField.value.length==0) || (aTextField.value==null)) {
      return true;
   }
   else { return false; }
}

function validate_string (strng, strType) {
	var error = "";
	if (strng == "") {
		error = "+ You did not enter a "+strType+".\n";
	}
	return error;
}

function validate_textbox (txtbox, strType) {
    var hasTxt = (txtbox.length>0);
	if (!hasTxt) return ("+ You must enter " + strType + ".\n");
	return "";
}

function validate_firstname (strng) {
	var error = "";
	if (strng == "") {
		error = "+ You did not enter a first name.\n";
	}
	return error;
}

function validate_lastname (strng) {
	var error = "";
	if (strng == "") {
		error = "+ You did not enter a last name.\n";
	}
	return error;
}

function validate_number (nmbr, interestedIn) {
	var error="";
	var nmbrPat=/^[0-9]+$/;
	if (!(nmbrPat.test(nmbr))) {
		error="+ Please enter a correct quantity for \'" + interestedIn + "\'.\n";
	}
	return error;
}

function validate_phonenumber (nmbr) {
	var error="";
	var nmbrPat=/^[\d\. -]*$/;
	if (!(nmbrPat.test(nmbr))) {
		error="+ Please enter a valid phone number.\n";
	}
	return error;
}

function validate_email (emailStr) {
	var error = "";
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
	var emailPat=/^(.+)@(.+)$/;
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]";
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")";
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
/* The following string represents an atom (basically a series of
   non-special characters.) */
	var atom=validChars + '+';
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")";
// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
		return (error = "+ Email address incorrect (check @ and .'s).\n");
	}

	var user=matchArray[1];
	var domain=matchArray[2];

// See if "user" is valid 
	if (user.match(userPat)==null) {
    // user is not valid
	    return (error = "+ Part of your email address before the '@' is not valid.\n");
	}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
    // this is an IP address
		for (var i=1;i<=4;i++) {
	    	if (IPArray[i]>255) {
	        	return (error="+ Destination IP address is invalid.\n");
	    	}
    	}
    	return error;
	}

// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		return(error="+ Part of your email address after the '@' is not valid.\n");
	}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
	var atomPat=new RegExp(atom,"g");
	var domArr=domain.match(atomPat);
	var len=domArr.length;
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>6) {
   // the address must end in a two letter or other TLD including museum
	   return(error="+ The email address must end in a top level domain (e.g. .com), or two letter country.\n");
	}

// Make sure there's a host name preceding the domain.
	if (len<2) {
	   return(error="+ Your email address is missing a hostname.\n");
	}

// If we've got this far, everything's valid!
	return error;
}

/* validatePostcode 
Validates a UK Postcode using Regex 
AN NAA, AAN NAA, AANN NAA, ANA NAA, AANA NAA 
@param str strPostCode PostCode 
*/ 
function validate_postcode(strPostCode) {
	var test = checkPostCode(strPostCode);
	var sCode = strPostCode;
	if (sCode == "") sCode="[BLANK]";
	if (test == false) {
		return ("+ "+sCode+ " is not a valid postcode.\n");
	}
	return ("");
} 


function checkPostCode (toCheck) {

  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkstuw]";                                // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
  
  // Array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
  
  // Overseas Territories
  pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var valid = false;
  
  // Check the string against the types of post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      
      // Load new postcode back into the form element
      valid = true;
      
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode
  if (valid) {return postCode;} else return false;
}

/* validate_Address
Determines whether the FindOut Form Fields contains info
@frm is the name to interate and check
this is not the final version - a quick fix!
*/
function validate_Address(frm) {
	var hasAddr = (frm.address.value.length>0);
	if (!hasAddr) return ("+ We need your Postal Address to send you information.\n");
	return "";
}

/* validate_FindOut
Determines whether the FindOut Form Fields contains info
@frm is the name to interate and check
this is not the final version - a quick fix!
*/ 
function validate_FindOut(frm) {
	if (!(frm.where[0].checked || frm.where[1].checked || frm.where[2].checked || frm.where[3].checked || frm.where[4].checked || frm.where[5].checked || (frm.where[6].checked && (frm.wheredetails.value!="")))) return ("+ Please tell us where you found out about us.\n");
	if (frm.where[4].checked && (frm.wheredetails.value=="")) return ("+ Please tell us at which show you found out about us.\n");
	if (frm.where[5].checked && (frm.wheredetails.value=="")) return ("+ Please tell us which search engine you used to find our website.\n");
	return "";
}