/**
 * Validate Field [jQuery]
 *
 * Intelligently checks a form field to make sure either a selection has
 * been made or a value entered (as appropriate to the field type).
 *
 * Last modified: 2009-01-22 {pf}
 *
 */

//  Warning to appear on form error
var reqWarnTitle = 'Sorry, there was a problem&hellip;';
var reqWarnBody = '<p>One or more required fields were not completed or have been completed incorrectly. Please check the fields highlighted below and try again, thank you.</p>';
var reqWarn = '<div class="message warning"><h3>' + reqWarnTitle + '</h3>' + reqWarnBody + '</div>';

function validateField(field) {
    
    //console.log( field.attr('id') + ' value is ' + field.val() );
    
    switch ( field.attr('type') ) {
        
        case 'select':
        case 'select-one':
            if ( !field.val() ) {
                return false;
            }
            break;
        
        case 'checkbox':
        case 'radio':
            if ( field.hasClass('requiredGroup') ) {
                var groupChecked = false;
                var fieldset = $(field).parents('fieldset')[0];
                $('input.requiredGroup', fieldset).each ( function() {
                    if ( $(this).attr('checked') ) {
                        groupChecked = true;
                    }
                });
                return groupChecked;
            }
            else if ( !field.attr('checked') ) {
                return false;
            }
            break;
        
        case 'password':
            // not currently testing or comparing passwords in JS, so treated as...
        default: // text
            if ( field.hasClass('validateEmail') ) {
                var emailPattern = new RegExp(/^([a-zA-Z0-9_\-\.\']+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/);
                if ( field.val().match(emailPattern) === null ) {
                    return false;
                }
            }
            else if ( !field.val() ) {
                return false;
            }
        
    }
    
    return true;
    
}


/**
 * Check Requireds [jQuery]
 *
 * Alerts the user to any 'required' inputs, in the target form, which
 * have not been completed.
 *
 * Last modified: 2009-01-22 {pf}
 */
function checkRequireds(thisForm) {
    
    var validated = false;
    
    //  Failure counter
    var failed = 0;
    
    //  NOTE: ':input' is jQuery shorthand for *all* form field types
    $(':input.required', thisForm).each( function () {
        
        var fieldValid = validateField($(this));
        
        if ( !fieldValid ) {
            
            failed++;
            
            //  Highlight error and set row class for hint reveal
            if ( $(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio' ) {
                $(this).parent().addClass('error');
            }
            else if ( !$(this).parent().hasClass('error') ) {
                $(this).wrap('<div class="error"></div>');
            }
            
        }
        else {
            
            //  Remove error highlight (if present)
            $(this).parent().removeClass('error');
            
        }
        
    });
    
    if (failed > 0) {

            $('div.warning', thisForm).slideDown(250);
        
    }
    else if (failed == 0) {
        
        if (hasCallback) {
            $('div.warning:visible', thisForm).slideUp(250);
            $('div.confirmation', thisForm).slideDown(250);
            $('fieldset', thisForm).slideUp(250);
        }
        
        validated = true;
        
    }
    
    return validated;
    
}

/**
 * Find Requireds [jQuery]
 *
 * Automatically scans the page for forms, then adds an 'onsubmit'
 * function to any forms which contain input elements classed as
 * 'required'.
 *
 * Last modified: 2009-08-14 {pf}
 */

function findRequireds() {
    
    $('.formWrapper').each( function() {
        var thisForm = $(this);
        if ( $(':input.required', thisForm) ) {
            $(':submit, :image', thisForm).click( function() {
                return checkRequireds(thisForm);
            });
        }
    });

}

// Bind form validation when DOM ready [uses jQuery]
$(document).ready( function() {
    if ( $(':input.required').length > 0 ) {
        findRequireds();
    }
});

