﻿function GetFormattedPostcode(postcode)
{
    var firstPart = "";
    var secondPart = "";
    return GetPostcodeParts(postcode, firstPart, secondPart);
}

function GetPostcodeParts(postcode, firstPart, secondPart)
{
    var postcodePartsRegEx = "^([a-zA-Z]{1,2}\\d[\\da-zA-Z]?) *(\\d[a-zA-Z]{2})$";
    var rexp = new RegExp(postcodePartsRegEx, "gim");
    var match = rexp.exec(postcode);
    if (match!=null)
    {
        if (match.length == 3)
        {
            firstPart = match[1];
            secondPart = match[2];
            return firstPart + " " + secondPart;
        }
        else
        {
            throw new Exception(postcode + " is not a real postcode, it produced '" + match.Groups.Count + "' matches");
        }
    }
    else
    {
        throw new Exception(postcode + " is not a real postcode, the Regex match was not a success");
    }
    return firstPart + " " + secondPart;
}

function ValidatePostcode(postcode)
{
//  debugger;
  var alpha1 = "[abcdefghijklmnoprstuwyz]";
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";
  var alpha3 = "[abcdefghjkstuw]";
  var alpha4 = "[abehmnprvwxy]";
  var alpha5 = "[abdefghjlnpqrstuwxyz]";
  
  var Expressions=new Array();
  
  Expressions[0] = "^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$";
  Expressions[1] = "^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$";
  Expressions[2] = "^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$";
  Expressions[3] = "^(GIR)(\\s*)(0AA)$";
  Expressions[4] = "^(bfpo)(\\s*)([0-9]{1,4})$";
  Expressions[5] = "^(bfpo)(\\s*)(c\\/o\\s*[0-9]{1,3})$";
            
  for (var i=0;i<Expressions.length; i++) {
  
    var rexp = new RegExp(Expressions[i], "gim");
    var match = rexp.exec(postcode);
    
    if (match!=null)
    {
      return true
    }

 }
 return false
}
