function checkPostCode (toCheck) {

// This routine checks the value of the form element specified by the parameter
// for a valid postcode. The space between the inward part and the outward part
// is optional, although is inserted if not there as it is part of the postcode.

// The definition of a valid postcode has been taken from:
// http://www.royalmail.com/docContent/other/Downloadable_Files/PAF_Digest_Issue_5_0.pdf

// If the element is a valid postcode, the function returns it correctly 
// formatted. Otherwise it returns the original input.

  // This 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 (/^([a-z]{1,2}[0-9]{1,2})(\s*)([0-9]{1}[abdefghjlnpqrstuwxyz]{2})$/i);

  // Expression for postcodes: ANA NAA, and AANA  NAA
  pcexp.push (/^([a-z]{1,2}[0-9]{1}[a-z]{1})(\s*)([0-9]{1}[abdefghjlnpqrstuwxyz]{2})$/i);
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/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 both 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();
      
      // 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;
}

