$(document).ready(function(){
    // functions to display error messages.
    var sendError = function(elem, error){
        var container = $(elem.parent());
        $(container).find('span').remove();
        $('<span></span>').addClass('error-message').text(error).appendTo(container);
    };
    // functions to remove error messages.
    var clearError = function(elem){
        var container = $(elem.parent());
        $(container).find('span').remove();
    }
    $('form :input').blur(function(){
        // check if a field is required
        // if a required field is blank set and error.
        if ($(this).hasClass('required')) {
            if (this.value == '') {
                var message = 'This field can not be left blank';
                sendError($(this), message)
            }
            // if required field is not empty
            // clear any errors set for this field.
            else {
                clearError($(this));
            }
        }
        // check to see if email is valid
        if ($(this).hasClass('validate-email')) {
            if (this.value != '' && !/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value)) {
                var message = 'This is not a valid email';
                sendError($(this), message);
            }
            // if the field is not empty but the email is valid
            // clear any errors set for this field.
            else 
                if (this.value != '') {
                    clearError($(this));
                }
        }
        if ($(this).hasClass('validate-match')) {
            var match = $('#password').get(0).value;
            if (this.value != match) {
                var message = 'Your password did not match';
                sendError($(this), message);
            }
            // if the field is not empty but value matches the password field
            // clear any errors set for this field.
            else 
                if (this.value != '') {
                    clearError($(this));
                }
        }
    });
});
