/**
 * 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}
 *
 */

function validateField(field) {
    
    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
            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) {
        
        if ( $('div.alert', thisForm).length < 1 ) {
            //  Requires 'reqWarn' HTML string (compiled in head of actual HTML document)
            thisForm.prepend(reqWarn);
        }
        
    }
    else if (failed == 0) {
        
        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-01-22 {pf}
 */

function findRequireds() {
    
    $('form').each( function() {
        var thisForm = $(this);
        if ( $(':input.required', thisForm) ) {
            $(thisForm).submit( function() {
                return checkRequireds(thisForm);
            });
        }
    });

}

// Bind form validation when DOM ready [uses jQuery]
$(document).ready( function() {
    if ( $(':input.required').length > 0 ) {
        findRequireds();
    }
});


/**
 *  Find Externals [jQuery]
 *  
 *  Finds all 'rel="external"' anchors on a page and automatically
 *  makes those open in a new window, without harming accessibility.
 *  
 *  Last modified: 2009-02-11 {pf}
 */

function findExternals() {
    $('a[rel="external"]').each( function() {
        if ( $(this).attr('title') && $(this).attr('title').length > 0 ) {
            $(this).attr('title', ( $(this).attr('title') + ' [opens in a new window]' ) );
        }
        else {
            $(this).attr('title', 'Opens in a new window');
        }
        $(this).click( function() {
            window.open($(this).attr('href'));
            return false;
        });
    });
    
}

$(document).ready( function() {
   findExternals(); 
});


/**
 *  Form Input Hinting
 *  
 *  If a form INPUT or TEXTAREA element has a 'title' attribute, this
 *  function displays the title value as a completion hint inside the
 *  element.  It also slightly alters the element styling to indicate
 *  this is a hint and not user-entered data.
 *  
 *  Last modified: 2009-09-08 {pf}
 */
function formHinting() {
    
    $(':text, textarea').each( function() {
        
        if ( $(this).attr('title') && $(this).attr('title').length > 0 ) {
            
            if ( $(this).val().length == 0 || $(this).val() == '' ) {
                $(this).addClass('hint');
                $(this).val( $(this).attr('title') );
            }
            
            $(this).focus( function() {
                if ( $(this).val() == $(this).attr('title') ) {
                    $(this).val('');
                    $(this).removeClass('hint');
                }
            });
            
            $(this).blur( function() {
                if ( $(this).val().length == 0 || $(this).val() == '' ) {
                    $(this).addClass('hint');
                    $(this).val( $(this).attr('title') );
                }
            });
            
        }
        
    });
    
}

$(document).ready( function() {
    formHinting();
});



/**
 * JavaScript Pop-up Window
 *
 * Intelligently finds and attaches pop-up window function to classed links.
 *
 * Last modified: 2009-09-08 {pf}
 */
function jsPopup() {
    if ( $("a[rel=popup], a[rel=external]").length > 0 ) {
        $("a[rel=popup], a[rel=external]").click( function() {
            window.open(this.href);
            return false; // prevents default hyperlink action
        });
    }
}

$(document).ready( function() {
    jsPopup();
});
