/*==============================================================================

Application:   Utility Function
Author:        John Gardner

Version:       V1.0
Date:          4th August 2007
Description:   Used to check the validity of a UK Tax Code

Version:			 V1.1
Date:					 13th March 2008
Description:	 K code error corrected (thanks to Adam Deacon)

Version:			 V1.2
Date:					 22nd August 2008
Description:	 M1 and W1 suffixes allowed (thanks to Dan Williams)
  
Parameters:    toCheck - tax code to be checked. 

This function checks the validty of the supplied number. 

If the number is found to be in a valid format, the function returns the tax 
code in upper case and with any embedded spaces removed. Otherwise a value of 
false. A space is inserted between the true tax code and any M1 or W1 suffix.

See http://www.hmrc.gov.uk/ebu/qual_stand_valid_spec.pdf

for a formal specification, and 

http://www.hmrc.gov.uk/paye/intro-understandingtaxcodes.htm

for an account of M1 and W1 codes.
  
Example call:
  
  if (checkTaxCode (myTaxCode) {
    alert ("Tax code has a valid format")
  } 
  else {alert ("Tax code has invalid format")};
                    
------------------------------------------------------------------------------*/

function checkTaxCode (toCheck) {

  // Convert given tax code to uppercase
  toCheck = toCheck.toUpperCase ();  
  
  // Remove spaces from the tax code to help validation
  while (toCheck.indexOf(" ")!= -1)  {
    toCheck = toCheck.slice (0,toCheck.indexOf(" ")) + toCheck.slice (toCheck.indexOf(" ")+1)
  }
  
  // Set up the regular expression for valid tax codes
	var exp = /(^[1-9]{1}[0-9]{0,5}[TLPVY]([MW]1){0,1}$)|(^K[1-9]{1}[0-9]{0,5}([MW]1){0,1}$)|(^((BR)|(OT)|(D0)|(NT)|(FT))([MW]1){0,1}$)/;
  
  // Check the code
  if (toCheck.match(exp)) {
  
     // Enforce a space before any M1 or W1     
     exp = /^(.+)([MW]1)$/;
     if (toCheck.match (exp)) {
        var namelist = new Array ();
        namelist [0] = toCheck.slice (0,-2);
        namelist [1] = toCheck.slice (-2);
        toCheck = namelist[0] + ' ' + namelist[1];
     }
        
    // Valid - return the tax code in uppercase with spaces removed
    return toCheck;
  }
  else 
  
    // Invalid - return false
    return false;
}
