// Tools 
Array.prototype.exists = function(s){for (var i=0; i<this.length; i++) if (this[i] == s) return true;
return false;}
// To make an alert with an (simple) object and see key values pairs 
Object.prototype.toString=function(){var i,c='';for (i in this) c+=i+' => '+this[i]+'\n';return c}
// to remove space or tab or line feed at the beginnig or at the end of strings
String.prototype.trim=function(){var c=this.replace(/(^\s+|\s+$)/g,'');return c}


function validateForm(){
/*set up form variable */
var x=document.forms["myForm"]["postcode"].value;
x=x.trim().replace(/\s+/g,' ');// Only one space or tab...
// A shorter code (see the split at the end)
var pc="TW1,TW2,TW3,TW7,TW8,TW9,TW10,TW11,TW12,E1,E10,E11,E12,E13,E14,E15,E16,E17,E18,E2,E3,E4,E5,E6,E7,E8,E9,EC1,EC2,EC3,EC4,N1,N10,N11,N12,N13,N14,N15,N16,N17,N18,N19,N2,N20,N21,N22,N3,N4,N5,N6,N7,N8,N9,NW1,NW10,NW11,NW2,NW3,NW4,NW5,NW6,NW7,NW8,NW9,SE1,SE10,SE11,SE12,SE13,SE14,SE15,SE16,SE17,SE18,SE19,SE2,SE20,SE21,SE22,SE23,SE24,SE25,SE26,SE27,SE28,SE3,SE4,SE5,SE6,SE7,SE8,SE9,SW1,SW10,SW11,SW12,SW13,SW14,SW15,SW16,SW17,SW18,SW19,SW2,SW20,SW3,SW4,SW5,SW6,SW7,SW8,SW9,W1,W10,W11,W12,W13,W14,W2,W3,W4,W5,W6,W7,W8,W9,WC1,WC2".split(/\,/g);
                                     
function TestPostCode(p){var okCode=false,outwardCode=formatedCode='undefined',inwardCode='';
var inwardRegEx = /\s?([0-9][A-Z]{2})$/i; 
p=p.replace(inwardRegEx,function(a,b) {inwardCode=b.toUpperCase();return ''});
p=p.trim();
var outwardRegEx = /^[A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1}$/i;
if (outwardRegEx.test(p)) {okCode=true;outwardCode=p.toUpperCase();}
this.valid=okCode;
this.outward=outwardCode;
this.inward=inwardCode;
if (okCode) this.formatedCode=(outwardCode+' '+inwardCode).trim(); 
return this;} 
var userPostCode=new TestPostCode(x);
// alert(userPostCode);


if (!userPostCode.valid) {alert("This is not a valid postcode");return false;}
else {var msg="\n(The post code is "+userPostCode.formatedCode+")";
if (pc.exists(userPostCode.outward)) {
alert("Yes, we deliver Christmas trees to your area."+msg);return true;}
else {alert ("Sorry, we do not deliver Christmas trees to your area this year."+msg);return false;} 
}
}
