function insertErrors() {
  var msg = '<p>There were some problems with your input:</p>';
  var errors = $('<div class="errors">'+msg+'<ul></ul></div>');
  $(this).prepend(errors);
}

function error(s) {
  var msg = (this.title? this.title + ': ' : '') + s;
  $(this).parents('form').each(function(){
      var errors = $(this).children('.errors');
      if (!errors.length)
        insertErrors.call(this);
      $(this).find('.errors ul').append($('<li></li>').text(msg));
      errors.show();
    });
}

$(document).ready(function(){
    $('form').submit(function(){
        $(this).find('.errors ul').html('');
        var anyErrors;
        function validate(name,p,s){
          $(this).find(name).each(function(){
              if (p.call(this)) {
                anyErrors = true;
                error.call(this,s);
              }
            });
        }
        validate.call(this,
                      'input.required',
                      function(){ return (this.type == 'text' || this.type == 'password') && this.value == ''; },
                      "Can't be empty!");

        validate.call(this,
                      'input.postcode',
                      function(){
                        if (this.value=='') return false;
                        else return !this.value.toUpperCase().match(/^[A-Z0-9 ]+$/); 
                      },
                      "Must be a valid UK post code!");

        validate.call(this,
                      'input.email',
                      function(){
                        if (this.value=='') return false;
                        else return !this.value.match(/^[^@]+@[^@\.]+\.[^@\.]+/); 
                      },
                      "Must be a valid email!");

        validate.call(this,
                      'input.integer',
                      function(){
                        if (this.value=='') return false;
                        else return !this.value.match(/^[-]{0,1}[0-9]+$/); 
                      },
                      "Must be a valid integer number! E.g. 23, 1, 0, 36214, etc.");

        validate.call(this,
                      'input.overzero',
                      function(){
                        if (this.value=='') return false;
                        else if (!this.value.match(/^[-]{0,1}[0-9]+$/)) return false;
                        else return this.value < 1;
                      },
                      "Must be over zero!");

        validate.call(this,
                      'input.telnumber',
                      function(){
                        if (this.value=='') return false;
                        else return !this.value.toUpperCase().match(/^[0-9 -+]{6,20}$/); 
                      },
                      "Must be a valid telephone number!");

        if (!anyErrors) $(this).find('.errors').hide();
        return !anyErrors;
      });
  });

