/**
 * 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) {
    
    //  Warning text to appear on form error [can contain HTML]
    var reqWarn = '<div class="alert userWarning"></div>';
    //  NB: No on-screen text in this implementation; empty element still required for validation check
    
    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);
        }
        
        //$(window).scrollTo($('div.requiredWarning:first', thisForm));
        
    }
    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();
    }
});


/**
 *  Open in New Window
 *  Simple handler function to open designated link(s) in a new window,
 *  with optional onclick function override.
 *  last modified: 2009-02-26 {pf}
 */
function openInNewWindow() {
    
    var anchor = arguments[0];
    
    //  Set/update 'title' for assistive hover tip
    if ( $(anchor).attr('title') && $(anchor).attr('title').length > 0 ) {
        $(anchor).attr('title', ( $(anchor).attr('title') + ' [opens in a new window]' ) );
    }
    else {
        $(anchor).attr('title', 'Opens in a new window');
    }
    
    //  Add external onclick method (if passed in)
    if (arguments.length > 1) {
        var linkName = arguments[1];
        var func = null;
        if (linkName == "facebook") {
            func = "fbs_click";
        }
        else {
            func = "localPopup";
        }
        $(anchor).click( function() {
            return window[func]($(anchor).attr('href'));
        });
    }
    else if (arguments.length == 1) {
        $(anchor).click( function() {
            window.open($(anchor).attr('href'));
            return false;
        });
    }
}


/**
 *  Find Special Links [jQuery]
 *  Finds all 'rel="external"' and 'rel="local"' anchors on a page and
 *  automatically makes those open in a new window, without harming
 *  accessibility.
 *  Last modified: 2009-04-27 {pf}
 */

function findSpecialLinks() {
    $('a[rel="external"], a[rel="local"]').each( function() {
        if ( $(this).attr('name') && $(this).attr('name').length > 0 ) {
            openInNewWindow( $(this), $(this).attr('name') );
        }
        else {
            openInNewWindow( $(this) );
        }
    });
}

$(document).ready( function() {
   findSpecialLinks(); 
});


/**
 *  Local Popup
 *  Opens a small auxillary window of information related to the
 *  current website.
 *  Last modified: 2009-04-27 {pf}
 */
function localPopup(href) {
    window.open(href, 'local', 'toolbar=0,status=0,width=640,height=480,scrollbars=1');
    return false;
}


/**
 *  Share on Facebook
 *  Lets you post the current page to your Facebook profile. Based on
 *  Facebook's original "Share Partners" code (but tweaked):
 *  http://www.new.facebook.com/share_partners.php
 *  Last modified: 2009-04-27 {pf}
 */
function fbs_click(href) {
    window.open(href, 'sharer', 'toolbar=0,status=0,width=970,height=540');
    return false;
}
