﻿var townselector;
var categoryselector;
var yourtownselector;

window.onload = function () {
    townselector = new DropDownBox('atownselector', '', 426, 422, 155, 0, true, true, 'townselectorReturn');
    townselector.setAjaxCallFunction('getLocationAjax', 1);
    townselector.lluDropDownCentrePanel.tabIndex = 9;

    categoryselector = new DropDownBox('acategories', '', 426, 422, 155, 0, true, true, 'categoryselectorReturn');
    categoryselector.setAjaxCallFunction('getCategoryAjax', 1);
    categoryselector.lluDropDownCentrePanel.tabIndex = 15;

    yourtownselector = new DropDownBox('ayourlocations', '', 426, 422, 155, 0, true, true, 'yourtownselectorReturn');
    yourtownselector.setAjaxCallFunction('getYourLocationsAjax', 1);
    yourtownselector.lluDropDownCentrePanel.tabIndex = 15;

};


//----------------------Business Location

function getLocationAjax() {
    var townsearch = townselector.lluDropDownCentrePanel.value;
    strURLgl = "http://" + window.location.host + "/getLocations.ashx?location=" + townsearch;
    $.get(strURLgl, function (data) {

        if (data == "") {
            //document.getElementById("lluDropDownItem1").value = "Sorry, No results found";
            alert("Sorry, No results found");
        }
        else {
            townselector.setScrollList(data);
        }

    });
}

function townselectorReturn(val) {
    document.getElementById("business_location").value = val.split(",")[0];
    document.getElementById("PostCode").focus();
    populateLocSelectorBox(val.split(",")[0]);

    chooseLocation('add', val.split(",")[0], val.split(",")[1]);
    yourtownselector.lluDropDownCentrePanel.value = val.split(",")[1] + "," + val.split(",")[2];
    
    $("#" + val.split(",")[0]).fadeOut("fast");

    //var aa = document.getElementById(val.split(",")[0]);
      
    
}

//----------------------Keyphrases

function getCategoryAjax() {
    var catsearch = categoryselector.lluDropDownCentrePanel.value;
    strURLgl = "http://" + window.location.host + "/getCategories.ashx?catcount=10&keyphrases=" + catsearch;
    $.get(strURLgl, function (data) {
        categoryselector.setScrollList(data);
    });
}

function categoryselectorReturn(val) {
    populateCatSelectorBox(val);
}

function populateCatSelectorBox(item) {
    strURL = "http://" + window.location.host + "/getKeywords.ashx?id=" + item.split(",")[0];
    $.get(strURL, function (data) { document.getElementById("keyphraseList").innerHTML = data; });
    $(".cattag").show();
    $("#KeyphraseContainer").show();
}



//----------------------Work Areas
function getYourLocationsAjax() {
    var townsearch = yourtownselector.lluDropDownCentrePanel.value;
    strURLgl = "http://" + window.location.host + "/getLocations.ashx?location=" + townsearch;
    $.get(strURLgl, function (data) {
        yourtownselector.setScrollList(data);
    });
}
function yourtownselectorReturn(val) {
    populateLocSelectorBox(val)
}

function populateCatSelectorBox(item) {
    strURL = "http://" + window.location.host + "/getKeywords.ashx?id=" + item.split(",")[0];
    $.get(strURL, function (data) { document.getElementById("keyphraseList").innerHTML = data; });
    $(".cattag").show();
    $("#KeyphraseContainer").show();
}


function populateLocSelectorBox(item) {
    strURL = "http://" + window.location.host + "/getLocationSuggestions.ashx?distance=10&placeid=" + item.split(",")[0];
    $.get(strURL, function (data) { document.getElementById("LocationList").innerHTML = data; });
    $(".loctag").show();
    $("#LocationContainer").show();
}
//----------------------


function LocationRequested(sender, args) {
    var combo = $find("Locations");
    if (args.get_text().length > 2) {
        strURLgl = "http://" + window.location.host + "/getLocations.ashx?location=" + args.get_text();
        $.get(strURLgl, function (data) {
            var towns = data.split('|');
            combo.ClearItems;
            for (var i = 0; i < towns.length - 1; i++) {
                var idsplit = towns[i].split(";");
                var comboItem = new Telerik.Web.UI.RadComboBoxItem();
                comboItem.set_text(idsplit[1]);
                comboItem.set_value(idsplit[0]);
                combo.trackChanges();
                combo.get_items().add(comboItem);
                combo.commitChanges();
            }
            $(".rcbList").css("position", "relative");
        });
    }

   }


   function OnClientItemsRequestedcat(sender, args) {
       var strURL = "";
       var combo = $find("Categories");
       if (args.get_text().length > 2) {
           strURL = "http://" + window.location.host + "/getCategories.ashx?catcount=2&keyphrases=" + args.get_text();
           $.get(strURL, function (data) {
               var cats = data.split('|');
               combo.ClearItems;
               for (var i = 0; i < cats.length - 1; i++) {
                   var idsplit = cats[i].split(";");
                   var comboItem = new Telerik.Web.UI.RadComboBoxItem();
                   comboItem.set_text(idsplit[1]);
                   comboItem.set_value(idsplit[0]);
                   combo.trackChanges();
                   combo.get_items().add(comboItem);
                   combo.commitChanges();
               }
               $(".rcbList").css("position", "relative");
           });
       
       }

       
   }




   function OnClientItemsRequestedLocations(sender, args) {
       var strURL = "";
       var combo = $find("Locations");
       if (args.get_text().length > 2) {
           strURL = "http://" + window.location.host + "/getLocations.ashx?location=" + args.get_text();
           $.get(strURL, function (data) {
               var cats = data.split('|');
               combo.ClearItems;
               for (var i = 0; i < cats.length - 1; i++) {
                   var idsplit = cats[i].split(";");
                   var comboItem = new Telerik.Web.UI.RadComboBoxItem();
                   comboItem.set_text(idsplit[1]);
                   comboItem.set_value(idsplit[0]);
                   combo.trackChanges();
                   combo.get_items().add(comboItem);
                   combo.commitChanges();
               }
               $(".rcbList").css("position", "relative");
           });

       }


   }

   



   function chooseLocation(action, itemid, item) {


       $("#SelectedLocationContainer").fadeIn("fast");

       var Locations = document.getElementById("hfLocations").value;
       var Locationids = document.getElementById("Locationids").value;
       var Locationshtml = document.getElementById("Locationshtml").value;







       if (action == 'add') {
           if (Locationids.indexOf(itemid) > -1) {
               $("#" + itemid).fadeOut("fast");
               return;
           }

           document.getElementById("hfLocations").value = '';
           document.getElementById("Locationids").value = '';

           Locationids = Locationids.split(",");
           

           if (Locations.length == 0) {
               Locations = "|" + item + "^" + itemid + "|";
               Locations = Locations.split(",");
           }
           else {
               Locations = Locations.split(",");
               Locations.push("|" + item + "^" + itemid + "|");
               Locations = cleanArray(Locations);
           }
           Locationids.push("|" + itemid + "|");



           $("#" + itemid).fadeOut("fast");
       }


       if (action == 'del') {

           document.getElementById("hfLocations").value = '';
           document.getElementById("Locationids").value = '';

           Locations = Locations.replace("|" + item + "^" + itemid + "|", "");
           Locationids = Locationids.replace("|" + itemid + "|", "");

           Locations = Locations.replace(",,", ",");
           Locationids = Locationids.replace(",,", ",");


           Locations = Locations.split(",");
           Locations = cleanArray(Locations);

           Locationids = Locationids.split(",");
           Locationids = cleanArray(Locationids);
       }

       $(".loccount").html(Locations.length + " locations.");

       var htmlstring = "";
       document.getElementById("hfLocations").value = Locations;
       document.getElementById("Locationids").value = Locationids;

       Locations = cleanArray(Locations);




       for (i = 0; i < Locations.length; i++) {

           Location = Locations[i].substring(0, Locations[i].indexOf('^')).replace("|", "");
           Locationids = Locations[i].substring(Locations[i].indexOf('^') + 1, Locations[i].length - 1).replace("|", "");
           htmlstring += "<div id=\"sel" + Locationids + "\" class='LocationListItemSelected' onclick=\"chooseLocation('del','" + Locationids + "','" + Location + "');\">" + Location + "</div>";
       }

       document.getElementById("SelectedLocationList").innerHTML = "";
       document.getElementById("SelectedLocationList").innerHTML = htmlstring;







   }


   


   function chooseKeyword(action,itemid,item) {
       //alert(element);
       
       

       $("#SelectedKeyphraseContainer").fadeIn("fast");

       var keywords = document.getElementById("keywords").value;
       var keywordids = document.getElementById("keywordids").value;
       var keywordshtml  = document.getElementById("keywordshtml").value;

       





       if (action == 'add') {

           
           keywordids = keywordids.split(",");

           if (keywordids.length >= 10) {
               alert("You have already selected 10 keyphrases. You can add more later once registration is complete.");
               return;
           }

           document.getElementById("keywords").value = '';
           document.getElementById("keywordids").value = '';

           if (keywords.length == 0) {
               keywords = "|" + item + "^" + itemid + "|";
               keywords = keywords.split(",");
           }
           else {
               keywords = keywords.split(",");
               keywords.push("|" + item + "^" + itemid + "|");
           }
           keywordids.push("|" + itemid + "|");

           

           $("#" + itemid).fadeOut("fast");
       }






       if (action == 'del') {
           document.getElementById("keywords").value = '';
           document.getElementById("keywordids").value = '';

           keywords = keywords.replace("|" + item + "^" + itemid + "|", "");
           keywordids = keywordids.replace("|" + itemid + "|", "");

           keywords = keywords.replace(",,", ",");
           keywordids = keywordids.replace(",,", ",");
           
           keywords = keywords.split(",");
           keywordids = keywordids.split(",");
       }


       //keywords = cleanArray(keywords);
       keywordids = cleanArray(keywordids);
       
       $(".catcount").html(keywordids.length + " key categories.");
       var htmlstring = "";
       document.getElementById("keywords").value = keywords;
       document.getElementById("keywordids").value = keywordids;

       keywords = cleanArray(keywords);




       for (i = 0; i < keywords.length; i++) {

           //var aa = keywords[i].split("^")[0];
           keyword = keywords[i].substring(0, keywords[i].indexOf('^')).replace("|","");

           keywordids = keywords[i].substring(keywords[i].indexOf('^') + 1, keywords[i].length - 1).replace("|", "");
           //nouns[i] = nouns[i].substring(0, nouns[i].indexOf('|'));

           htmlstring += "<div id=\"" + keywordids + "\" class='keywordListItemSelected' onclick=\"chooseKeyword('del','" + keywordids + "','" + keyword + "');\">" + keyword + "</div>";
       }
       document.getElementById("SelectedkeyphraseList").innerHTML = htmlstring;
   }

   $(document).ready(function () {



       $('.closebutton').click(function () {
           document.getElementById("SessionID").value = "";

       });

       $('#contactInfoContinue').click(function () {
           $('#contactexists').hide();
       });





       $('#sf1title,#sf2title,#sf3title,#sf4title').hide();

       $('#sf1completed').hide();
       // add * to required field labels
       $('label.required').append('&nbsp;<strong>*</strong>&nbsp;');

       // accordion functions
       var accordion = $("#socialsignup").accordion({ autoHeight: false, animated: 'slide' });

       var current = 0;

       $.validator.addMethod("pageRequired", function (value, element) {
           var $element = $(element)
           function match(index) {

               return current == index && $(element).parents("#sf" + (index + 1)).length;
           }
           if (match(0) || match(1) || match(2)) {

               return !this.optional(element);

           }
           return "dependency-mismatch";
       }, $.validator.messages.required)

       var v = $("#socialsignupform").validate({
           errorClass: "warning",
           onkeyup: false,
           onblur: false,
           submitHandler: function () {
               
           }
       });



       // back buttons do not need to run validation
       $(".backto0").click(function () {
           accordion.accordion("activate", 0);
           current = 0;
       });
       $("#sf3 .prevbutton").click(function () {
           accordion.accordion("activate", 1);
           current = 1;
       });

       $("#sf4 .prevbutton").click(function () {
           accordion.accordion("activate", 2);
           current = 2;
       });
       // these buttons all run the validation, overridden by specific targets above


       $(".open4").click(function () {
           if (validateData(4) == false) {
               return;
           }

           if (v.form()) {
               accordion.accordion("activate", 4);
               current = 4;
               $.post("submitform.ashx?page=4", $("#socialsignupform").serialize(), function (data) { });
               $('#sf1').css('background-image', 'url(/resources/images/yourbusiness.png)')
               $('#sf2').css('background-image', 'url(/resources/images/yourdetails.png)')
               $('#sf3').css('background-image', 'url(/resources/images/yourcategories.png)')
               $('#sf4').css('background-image', 'url(/resources/images/yourlocations.png)')
               $('#sf5').css('background-image', 'url(/resources/images/yourfinished_active.png)')

               $('#sf3title').hide();
               $('#sf2title').hide();
               $('#sf1title').hide();

               $.get('submitform.ashx?page=4', $("#socialsignupform").serialize(), function (data) { });
               document.getElementById("SessionID").value = "";
           }
       });



       $(".open3").click(function () {

           if (validateData(3) == false) {
               return;
           }

           if (v.form()) {
               accordion.accordion("activate", 3);
               current = 3;

               //$.get('submitform.ashx?page=3', $("#socialsignupform").serialize(), function (data) { alert("PAGE 3a"); });
               $.post("submitform.ashx?page=3", $("#socialsignupform").serialize(), function (data) { });

               $('#sf1').css('background-image', 'url(/resources/images/yourbusiness.png)')
               $('#sf2').css('background-image', 'url(/resources/images/yourdetails.png)')
               $('#sf3').css('background-image', 'url(/resources/images/yourcategories.png)')
               $('#sf4').css('background-image', 'url(/resources/images/yourlocations_active.png)')
               $('#sf5').css('background-image', 'url(/resources/images/yourfinished.png)')

               $('#sf3title').show();

               $('#sf4title').hide();



           }
       });


       $(".open2").click(function () {

           if (validateData(2) == false) {
               return;
           }

           if (v.form()) {
               accordion.accordion("activate", 2);
               current = 2;
               $.post("submitform.ashx?page=2", $("#socialsignupform").serialize(), function (data) { });

               $('#sf1').css('background-image', 'url(/resources/images/yourbusiness.png)')
               $('#sf2').css('background-image', 'url(/resources/images/yourdetails.png)')
               $('#sf3').css('background-image', 'url(/resources/images/yourcategories_active.png)')
               $('#sf4').css('background-image', 'url(/resources/images/yourlocations.png)')
               $('#sf5').css('background-image', 'url(/resources/images/yourfinished.png)')

               $('#sf2').css('background-image', 'url(/resources/images/yourdetails.png)')

               $('#sf2title').show();
               $('#sf1prev').show();

               $('#sf3title').hide();
               $('#sf4title').hide();

               //$.get('submitform.ashx?page=2', $("#socialsignupform").serialize(), function (data) { });
           }
       });


       $(".open1").click(function () {
           $('#sf1completed').hide();
           if (validateData(1) == false) {
               return;
           }

           if (v.form()) {

               accordion.accordion("activate", 1);
               current = 1;

               $.post("submitform.ashx?page=1", $("#socialsignupform").serialize(), function (data) { });

               $('#sf1').css('background-image', 'url(/resources/images/yourbusiness.png)')
               $('#sf2').css('background-image', 'url(/resources/images/yourdetails_active.png)')
               $('#sf3').css('background-image', 'url(/resources/images/yourcategories.png)')
               $('#sf4').css('background-image', 'url(/resources/images/yourlocations.png)')
               $('#sf5').css('background-image', 'url(/resources/images/yourfinished.png)')
               $('#sf1title').show();
               $('#sf1completed').show();
               $('#sf2title').hide();
               $('#sf3title').hide();
               $('#sf4title').hide();

               //$.get('submitform.ashx?page=1', $("#socialsignupform").serialize(), function (data) { });
           }
       });
       $(".open0").click(function () {
           if (v.form()) {
               accordion.accordion("activate", 0);
               $('#sf1').css('background-image', 'url(/resources/images/yourbusiness_active.png)')
               $('#sf2').css('background-image', 'url(/resources/images/yourdetails.png)')
               $('#sf3').css('background-image', 'url(/resources/images/yourcategories.png)')
               $('#sf4').css('background-image', 'url(/resources/images/yourlocations.png)')
               $('#sf5').css('background-image', 'url(/resources/images/yourfinished.png)')

               $('#sf1completed').hide();

               $('#sf1title').hide();
               $('#sf2title').hide();
               $('#sf3title').hide();
               $('#sf4title').hide();
               current = 0;
           }
       });

       $(".addbutton").click(function () {



           if (document.getElementById("Accreditations").value != '') {
               $('#acclist').css('display', 'block');
               var accred = document.getElementById("Accreditations").value;
               var accredID = accred.replace(/ /gi, "_");
               document.getElementById("accreditations_list").value += "," + accredID;

               $('#acclist').append("<div id=\"" + accredID + "\" class=\"acclist\" onclick=\"delacc('" + accredID + "');\" >" + accred + "</div>");

               document.getElementById("Accreditations").value = '';
           };
       });


   });


   function delacc(accred) {

       var hiddenfield = document.getElementById("accreditations_list").value;
       //var accred = accred.replace("_", " ");
       hiddenfield = cleanArray(hiddenfield.replace(accred, "").split(","));

       document.getElementById("accreditations_list").value = hiddenfield;


       $("#" + accred).replaceWith('');
   }


   function validateData(section) {
       var error = "";
       document.getElementById('errorMessage').innerHTML = "";

       switch (section) {

           case 1:
               var compName = document.getElementById('CompanyName').value;
               compName = compName.replace(/ /g, "");

               if (compName.length==0) {
                   error += "<p class=\"errorItem\">Company Name.</p>";
               }

               break;


           case 2:
               if (document.getElementById('Forename').value == "") { error += "<p class=\"errorItem\">Forename.</p>"; }
               if (document.getElementById('Surname').value == "") { error += "<p class=\"errorItem\">Surname.</p>"; }
               if (document.getElementById('Address1').value == "") { error += "<p class=\"errorItem\">Address Line 1</p>"; }

               var aa = document.getElementById('business_location').value;
               if (document.getElementById('business_location').value == "") { error += "<p class=\"errorItem\">Please Select A Town</p>"; }



               var postc = document.getElementById("PostCode").value;
               var pcChk = checkPCode(postc)
               var postcode = document.getElementById("PostCode").value
               var strURL = "http://" + window.location.host + "/getCheckPostcode.ashx?postcode=" + postcode;

               $.ajax(
            { url: strURL, async: false, success: function (data) {
                if (data.indexOf("false") > -1) {
                    error += "<p class=\"errorItem\">Not A Valid Postcode, Please Check.</p>";
                }
            }
            });
               if (pcChk != '' && pcChk != true) { error += "<p class=\"errorItem\">Postcode</p><p class=\"errorItem\">" + pcChk + "</p>"; }




               if (error != "") {

                   document.getElementById('errorMessage').innerHTML = "<h3 class=\"errorHeader\">ERROR.</h3><p class=\"errorHeader\">You have not completed the following required fields:</p>" + error;
                   return false;
               }


               if ((document.getElementById("Mobile").value.length == 0) && (document.getElementById("Email").value.length == 0)) {
                   error += "<p class=\"errorItem\">You need to enter a valid mobile number or e-mail address so we can send you your username and password.</p>";
               }



               if ((document.getElementById("Mobile").value.length == 0) && (document.getElementById("Email").value.length != 0)) {

                   var email = document.getElementById("Email").value
                   var strURL = "http://" + window.location.host + "/getCheckEmail.ashx?email=" + email;
                   $.ajax({ url: strURL, async: false, success: function (data) {
                       if (data.indexOf("FAIL") > -1) {
                           error += "<p class=\"errorItem\">Email Did Not Validate.</p>";
                       }
                   }
                   });


                   var strURL = "http://" + window.location.host + "/getCheckContactExists.ashx?mobile=&email=" + email;
                   $.ajax({ url: strURL, async: false, success: function (data) {
                       if (data.indexOf("ReturnFalse") > -1) {
                       } else {
                           $('#contactexists').show();
                           $('#contactexistsText').text(data);

                           $.post("submitform.ashx?page=contactExists", $("#socialsignupform").serialize(), function (data) { });
                           return false;
                       }
                   }
                   });





               }



               if ((document.getElementById("Mobile").value.length != 0) && (document.getElementById("Email").value.length == 0)) {
                   var mobile = document.getElementById("Mobile").value

                   if (document.getElementById("Mobile").value.length != 11 | document.getElementById("Mobile").value.charAt(0) != "0" | document.getElementById("Mobile").value.charAt(1) != "7") {
                       error += "<p class=\"errorItem\">Your mobile number must be 11 digits and start with '07'</p>";
                   }

                   var strURL = "http://" + window.location.host + "/getCheckContactExists.ashx?email=&mobile=" + mobile;
                   $.ajax({ url: strURL, async: false, success: function (data) {
                       if (data.indexOf("ReturnFalse") > -1) {
                       } else {
                           $("#contactexists").fadeIn(1000);
                           $('#contactexistsText').text(data);
                           $.post("submitform.ashx?page=contactExists", $("#socialsignupform").serialize(), function (data) { });
                           return false;
                       }
                   }
                   });
               }



               if ((document.getElementById("Mobile").value.length != 0) && (document.getElementById("Email").value.length != 0)) {
                   var mobile = document.getElementById("Mobile").value;

                   if (document.getElementById("Mobile").value.length != 11 | document.getElementById("Mobile").value.charAt(0) != "0" | document.getElementById("Mobile").value.charAt(1) != "7") {
                       error += "<p class=\"errorItem\">Your mobile number must be 11 digits and start with '07'</p>";
                   }

                   var email = document.getElementById("Email").value
                   var strURL = "http://" + window.location.host + "/getCheckEmail.ashx?email=" + email;
                   $.ajax({ url: strURL, async: false, success: function (data) {
                       if (data.indexOf("FAIL") > -1) {
                           error += "<p class=\"errorItem\">Email Did Not Validate.</p>";
                       }
                   }
                   });

                   var strURL = "http://" + window.location.host + "/getCheckContactExists.ashx?email=" + email + "&mobile=" + mobile;
                   $.ajax({ url: strURL, async: false, success: function (data) {
                       if (data.indexOf("ReturnFalse") > -1) {
                       } else {
                           $('#contactexists').show();
                           $('#contactexistsText').text(data);
                           $.post("submitform.ashx?page=contactExists", $("#socialsignupform").serialize(), function (data) { });
                           return false;
                       }
                   }
                   });

               }

               var referrer = document.getElementById("Referrer").value;
               if (referrer.length > 0) {
                   var strURL = "http://" + window.location.host + "/getCheckReferrer.ashx?referrer=" + referrer;

                   $.ajax({ url: strURL, async: false, success: function (data) {
                       if (data.indexOf("false") > -1) {
                           error += "<p class=\"errorItem\">Incorrect Referrer Code.</p>";
                       }
                       if (data.indexOf("true") > -1) {
                       }
                   }

                   });
               }
               break;






           case 3:

               var keywordsamount = cleanArray(document.getElementById("keywords").value.split(","));

               if (keywordsamount.length < 3 || keywordsamount.length > 10) {
                   error += "<p class=\"errorItem\">Please select between 3 - 10 keyphrases, You currenly have " + keywordsamount.length + " selected</p>";
               }

               break;



           case 4:

               var Locations = cleanArray(document.getElementById("hfLocations").value.split(","));

               if (Locations.length ==0 || Locations.length > 10) {
                   error += "<p class=\"errorItem\">Please select upto  10 locations, You currenly have " + Locations.length + " selected</p>";
               }
               break;


           case 'contactExists':
               $.post("submitform.ashx?page=contactExists", $("#socialsignupform").serialize(), function (data) { });
               
               break;

       }

       if (error != "") {

           document.getElementById('errorMessage').innerHTML = "<h3 class=\"errorHeader\">ERROR.</h3><p class=\"errorHeader\">You have not completed the following required fields:</p>" + error;
           return false;
       }

   }






function cleanArray(actual) {
    var newArray = new Array();
    for (var i = 0; i < actual.length; i++) {
        if (actual[i]) {
            newArray.push(actual[i]);
        }
    }
    return newArray;
}


function checkPCode(element) {


    test = document.getElementById("PostCode").value;
    size = test.length
    test = test.toUpperCase();
    var errormsg = "";
    while (test.slice(0, 1) == " ") {
        test = test.substr(1, size - 1); size = test.length
    }
    while (test.slice(size - 1, size) == " ") //Strip trailing spaces
    {
        test = test.substr(0, size - 1); size = test.length
    }
    document.getElementById("PostCode").value = test; //write back to form field
    if (size < 6 || size > 8) { //Code length rule
        errormsg = test + " is not a valid postcode - wrong length";
    }


    if (!(isNaN(test.charAt(0)))) { //leftmost character must be alpha character rule
        errormsg = test + " is not a valid postcode - cannot start with a number";
    }
    if (isNaN(test.charAt(size - 3))) { //first character of inward code must be numeric rule
        errormsg = test + " is not a valid postcode - alpha character in wrong position";
    }
    if (!(isNaN(test.charAt(size - 2)))) { //second character of inward code must be alpha rule
        errormsg = test + " is not a valid postcode - number in wrong position";
    }
    if (!(isNaN(test.charAt(size - 1)))) { //third character of inward code must be alpha rule
        errormsg = test + " is not a valid postcode - number in wrong position";
    }
    if (!(test.charAt(size - 4) == " ")) {//space in position length-3 rule
        errormsg = test + " is not a valid postcode - no space or space in wrong position";
    }

    count1 = test.indexOf(" "); count2 = test.lastIndexOf(" ");

    if (count1 != count2) {
        errormsg = test + " is not a valid postcode - only one space allowed";
        return false;
    }

    if (errormsg != "") {

        return errormsg;
    }
    else {


        return true;
    }
}



function let_num(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);
    keychar = keychar.toLowerCase();

    if ((key == null) || (key == 0) || (key == 8) ||
    (key == 9) || (key == 13) || (key == 27))
        return true;

    else if ((("abcdefghijklmnopqrstuvwxyz0123456789 ").indexOf(keychar) > -1))
        return true;
    else
        alert("Please use only Letters or Numbers in this field.");
    return false;
}



function allowSpecial(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);
    keychar = keychar.toLowerCase();


    if ((key == null) || (key == 0) || (key == 8) ||
    (key == 9) || (key == 13) || (key == 27))
        return true;

    else if ((("abcdefghijklmnopqrstuvwxyz0123456789 .@-_+").indexOf(keychar) > -1))
        return true;
    else
        alert("Please use only Letters, Numbers, Fullstops or @ in this field.");
    return false;
}

function allowNumbers(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);
    keychar = keychar.toLowerCase();

    if ((key == null) || (key == 0) || (key == 8) ||
    (key == 9) || (key == 13) || (key == 27))
        return true;

    else if ((("0123456789 ").indexOf(keychar) > -1))
        return true;
    else
        alert("Please use only Numbers in this field.");
    return false;
}

function allowLetters(e) {
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);
    keychar = keychar.toLowerCase();

    if ((key == null) || (key == 0) || (key == 8) ||
    (key == 9) || (key == 13) || (key == 27))
        return true;

    else if ((("abcdefghijklmnopqrstuvwxyz ").indexOf(keychar) > -1))
        return true;
    else
        alert("Please use only Letters in this field.");
    return false;
}



