/**
*  Input Hinting
*  Takes the title of an input classed with "hint" and sets that as
*  the display value onload; removes it on focus and reinstates it if
*  the user doesn't enter anything.
*  Last modified: 2010-07-29 {pf}
*/
function inputHinting() {
    
    $(':input.hint').each(function() {

        var $input = $(this);
        var $hint = $input.attr('title');

        //  Check this input has a title value
        if ($input.attr('title').length > 0) {

            //  Populate value with "title"
            if ( $input.val() == '' ) {
                $input.val($hint);
            }

            //  Blank value on focus
            $input.focus(function() {
                if ( $input.val() == $hint) {
                    $input.val('');
                }
                $input.addClass('hinted');
            });

            //  Reinstate hint if field left empty
            $input.blur(function() {
                if ($input.val() == '') {
                    $input.val($hint).removeClass('hinted');
                }
            });

        }

    });

}

/**
* 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>Please check the form fields highlighted below and try again.</p>';
var reqWarn = '<div class="message warning"><h3>' + reqWarnTitle + '</h3>' + reqWarnBody + '</div>';

function validateField(field) {

    //console.log( field.attr('id') + ' -> ' + 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() == field.attr('title') || !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.
*
* Only displays confirmation message if a callback is used otherwise
* assumes server-side functionality.
*
* Last modified: 2009-01-22 {pf}
*/
function checkRequireds(thisForm, hasCallback) {

    var validated = false;

    //  Failure counter
    var failed = 0;
    
    //  NOTE: ':input' is jQuery shorthand for *all* form field types
    $(':input.required:visible', 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>');
            }
            
            //$(this).parents('.row').addClass('errorRow');
            
        }
        else {
            
            //  Remove error highlight (if present)
            //$(this).parents('.errorRow').removeClass('errorRow');
            $(this).parent().removeClass('error');
            
        }
        
    });
    
    if (failed > 0) {
        
        var $alert = $('div.alert', thisForm);
        
        if ( $alert.length < 1) {
            //  Requires 'reqWarn' HTML string (compiled in head of actual HTML document)
            thisForm.prepend(reqWarn);
            $alert = $('div.alert', thisForm);
            $alert.hide();
        }
        
        $alert.slideDown( 250, function() {
            if ( $.isFunction($.scrollTo) ) {
                var $offset = $alert.offset();
                    $offset = $offset.top - 30;
                    $offset <= 0 ? 0 : $offset;
                $.scrollTo( $offset, 500 );
            }
        });
        
    }
    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 elements with a class of 
* formWrapper. 
*
* formWrapper is the identifier for a individual
* form inside a page as the use of the .net form warpper 
* removes the ability to add multiple forms to a page.
*
* Then adds a click event to each submit button within 
* formWrapper to validate any element marked as 'required'.
*
* By specifying a formCallback class a callback function can
* called on successful validation. 
*
* See below (where callbackFunction is the function to 
* callback):
*
*      <div class="formWrapper formCallback(callbackFunction)">
*
* Last modified: 2011-04-12 {pf}
*/

function findRequireds() {
    
    $('.formWrapper').each(function() {
        
        var thisForm = $(this);
        var $callback;
        
        $class = thisForm.attr('class');
        $splitClass = $class.split(' ');
        
        if ($splitClass.length > 1) {
            for (i = 0; i < $splitClass.length; i++) {
                if ($splitClass[i].substring(0, 12) == 'formCallback') {
                    $callback = $splitClass[i].substring(13, $splitClass[i].length - 1);
                }
            }
        }
        
        if ($(':input.required', thisForm)) {
            $(':submit:not(.ignore)', thisForm).click( function() {
                
                //  Check for optional fields and validate if shown
                var $optionals = $('.optional :input:visible');
                if ( $optionals.length >= 1 ) {
                    $(':input', $optionals).addClass('required');
                }
                
                if (checkRequireds(thisForm, $callback != null)) {
                    if ($callback != null) {
                        callFunction($callback, [thisForm]);
                    }
                    return true;
                } else {
                    return false;
                }
                
            });
        }
        
    });
    
}

/**
* Call Function
*
* Takes a function name in a string format and calls the named 
* function along with any arguments passed in as an array.
*
* Last modified: 2010-02-24 {dn}
*/

function callFunction(name, arguments) {
    var fn = window[name];
    if (typeof fn !== 'function')
        return;

    fn.apply(window, arguments);
}

$(document).ready(function() {
    if ($(':input.required').length > 0) {
        findRequireds();
    }
    inputHinting();
});



/**
 *  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(); 
});


/**
 * 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();
});


/**
 *  HR Application Form
 *  Last modified: 2011-03-24 {pf}
 */
$(function() {
    //  Clear Form (jQuery extension)
    //  http://www.learningjquery.com/2007/08/clearing-form-data
    $.fn.clearForm = function() {
        return this.each(function() {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form')
            return $(':input',this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
        });
    };
    //  Hide optional fields by default
    var $optionals = $('#content .formInner .optional');
    $optionals.each( function() {
        var $optional = $(this);
        var hide = true;
        $(':input', $optional).each( function() {
            var $field = $(this);
            if ( $field.attr('type') != 'checkbox' && $field.val() != '' ) {
                hide = false;
            }
            else if ( $field.val() != '' ) {
                hide = false;
            }
        });
        if (hide) {
            $optional.hide();
        }
    });
    //  Nationality & Immigration
    var $nationality = $('select[id$=Nationality]');
    var $_insurance = $('label[for$=Insurance]');
    var $insurance = $('input[id$=Insurance]');
    var $_immigration = $('#immigration');
    var $immigration = $('select[id$=Immigration]');
    var $_immigrationOther = $('#immigrationOther');
    var $immigrationOther = $('input[id$=ImmigrationOther]');
    $nationality.change( function() {
        var val = $nationality.val().toLowerCase();
        if ( val != 'british' ) {
            if ( $_immigration.is(':hidden') ) {
                $_immigration.slideDown().addClass('required');
            }
            $insurance.removeClass('required').parent().removeClass('error');
            $('span:hidden', $_insurance).fadeIn('fast');
        }
        else if ( val == 'british' ) {
            if ( $_immigration.is(':visible') ) {
                $_immigration.slideUp('fast', function() {
                    $(':input', $_immigration).val('');
                }).removeClass('required');
            }
            $insurance.addClass('required');
            $('span:visible', $_insurance).fadeOut();
        }
    });
    if ( $immigration.length > 0 && $immigration.val().toLowerCase() == 'other') {// onload check for pre-filled values
        $_immigrationOther.show();
        $immigrationOther.addClass('required');
    }
    $immigration.change( function() {
        var val = $(this).val().toLowerCase();
        if ( val == 'other' ) {
            $_immigrationOther.slideDown();
            $immigrationOther.addClass('required');
        }
        else if ( val != 'other' && $_immigrationOther.is(':visible') ) {
            $_immigrationOther.slideUp('fast');
            $immigrationOther.removeClass('required').val('');
        }
    });
    //  Convictions
    var $_convictions = $('#convictions');
    var $convictions = $('select[id$=Convictions]');
    $convictions.change( function() {
        var val = $(this).val().toLowerCase();
        if ( val == 'true' && $_convictions.is(':hidden') ) {
            $(':input', $_convictions).addClass('required');
            $_convictions.slideDown();
        }
        else if ( val == 'false' && $_convictions.is(':visible') ) {
            $_convictions.slideUp('fast', function() {
                $(':input', $_convictions).val('').removeClass('required');
            });
        }
    });
    //  "Current" date duration
    var $_noncurrent = $('div.noncurrent');
    var $current = $(':input[id$=Current]');
    var $noncurrents = $(':input', $_noncurrent).not($current);
        $noncurrents.addClass('required');
    if ( $current.is(':checked') ) {
        $_noncurrent.hide();
        $noncurrents.removeClass('required');
        $noncurrents.clearForm();
    }
    $current.click( function() {
        var $checked = $(this).attr('checked');
        $checked
          ? $_noncurrent.slideUp(function() {
              $noncurrents.removeClass('required');
            })
          :
            $_noncurrent.slideDown('fast', function() {
              $noncurrents.addClass('required');
            })
        ;
    });
    //  "Select all" checkboxes
    var $all = $(':checkbox[id$=UKAll]');
    $all.click( function() {
        var $this = $(this);
        var $checked = $this.attr('checked');
        var $siblings = $('#ukRegions :checkbox').not($this);
        $checked
          ? $siblings.attr({
                checked: 'checked',
                disabled: 'disabled'
            })
          : $siblings.attr({
                checked: '',
                disabled: ''
            })
        ;
    });
    //  Higher education
    var $level = $('select[id$=Level]');
    var $_higher = $('#higher');
    var $highers = $(':input', $_higher).not($current);
    var $val = $level.val();
    if ( $val == '' || $val == 'none' || $val == 'secondary' ) {
        $_higher.hide();
        $highers.removeClass('required');
        $highers.clearForm();
    }
    $level.change( function() {
        $val = $(this).val();
        if ( $val != '' && $val != 'none' && $val != 'secondary' ) {
            $_higher.slideDown(function() {
                $highers.addClass('required');
            });
        }
        else {
            $_higher.slideUp('fast', function() {
                $highers.removeClass('required');
            });
        }
    });
});

