/*

 Generic form validator
 ----------------------
 
 Steps to install:

 1. Make sure jquery is available.
 2. Include this file in the <head> of the page.
 3. It will automatically hook up to any form on the page.
 4. To make a field validated, e.g.

     <input type="text" name="email"/>

    add classes to it's `class` attribute, e.g.:

    <input type="text" name="email" class="required" />

    This will make sure it's not empty. You can add more than one:

    <input type="text" name="email" class="email required" />

    This will make sure an email address is entered.

    When the form is submitted, it will add an error message
    div to the form, e.g.:

    <form action="">
       <div class="errors">
         <p>There were some problems with your input:</p>
         <ul>
           <li>Must be a valid email!</li>
         </ul>
       </div>
       <input type="text" name="email" class="email required" />
    </form>

5. Add titles to your inputs so that errors can be more meaningful, e.g.:

    <form action="">
       <div class="errors">
         <p>There were some problems with your input:</p>
         <ul>
           <li>Email: Must be a valid email!</li>
         </ul>
       </div>
       <input type="text" name="email" title="Email" class="email required" />
    </form>

6. Style the `errors` div so that it looks like an error message.
7. Make sure that your form inputs have the right classes, e.g. an
    integer e.g. 1, 52, 2451 (not 2.5) should have class `integer' on
    it.
   
    Supported classes:

    required
    postcode
    email
    integer
    overzero
    telnumber

    More will be added as required.

 */

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();
    });
}

$.fn.validate = function(){
    var anyErrors;
    var errclass = "erroneous";                
    var focused;

    // Clear errors
    $(this).find('.errors ul').html('');
    function clear() {
        $(this).parent().removeClass(errclass);
        $(this).next('span').remove();
    }
    $(this).find('input').each(clear);
    $(this).find('textarea').each(clear);
    $(this).find('select').each(clear);

    function validate(name,p,s){
        // Here is where errors are inserted
        $(this).find(name).each(function(){
            // Don't bother validating an already invalid input
            if ($(this).parent().hasClass(errclass)) return true;
            if (p.call(this)) {
                anyErrors = true;
                $(this).parent().addClass(errclass);

                // Focus the input
                if (!focused) {
                    $(this).focus();
                    focused = true;
                }

                // Display a message at the top?
                  // error.call(this,s);

                // Add a message next to the input?
                   var errspan = $('<span class="error"></span>').text(s);
                   $(this).parent().append(errspan);
                //
            }
        });
    }
    validate.call(this,
                  'input.required',
                  function(){ return (this.type == 'text' || this.type == 'password') && this.value.replace(/[ ]+/,'') == ''; },
                  "Can't be empty!");

    validate.call(this,
                  'textarea.required',
                  function(){ return this.value.replace(/[ ]+/,'') == ''; },
                  "Can't be empty!");

    validate.call(this,
                  'select.required',
                  function(){ return this.value.replace(/[ ]+/,'') == ''; },
                  "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;
}

function copyover() {
    if (!this.checked) return;
    $('#billingaddress1').val($('#address1').val());
    $('#billingaddress2').val($('#address2').val());
    $('#billingcity').val($('#city').val());
    $('#billingcounty').val($('#county').val());
    $('#billingpostcode').val($('#postcode').val());
}

$(document).ready(function(){
    var i;
    $('form').submit(function(){
        var f = $(this);
        if (!i) i = setInterval(function(){ f.validate(); },1000);
        return f.validate();
    });
    $('input.copyover').click(copyover);
    $('input.copyover').change(copyover);
});

