/*
 * PostcodeChecker
 * 23/11/2007
 * 
 * PostcodeChecker.check(postcodeString)
 * Pass in the UK postcode to check.
 */
var PostcodeChecker = {}
PostcodeChecker.check = function(postcode) {
	// Allowed values for each character in 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
	
	/* 3 kinds of postcode structure */
	var pcexp = [];
	pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
	pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
	pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
	var isValid = false;
	
	/* Loop through each postcode type and try to match with postcode entered */
	for ( var i=0; i<pcexp.length; i++) {
	    if (pcexp[i].test(postcode)) {
	      pcexp[i].exec(postcode);
	      postcode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
	      postcode = postcode.replace (/C\/O\s*/,"c/o ");
	      isValid = true;
	      break;
	    }
  		}

	return isValid;
}