/**
 *  Search Star Hero
 *  Simple slideshow for the Search Star homepage.
 *  Last modified: 2010-12-06 {pf}
 */
function hero() {
    
    //  Prepare slides for transitions
    $('.slide').each( function() {
        if ( $(this).hasClass('current') ) {
            //  do nothing; we're on this slide already
        }
        else {
            $(this).fadeOut();
        }
    });
    
    //  Sliding the slides
    $('#buttons a').click( function() {
        $('#buttons a').removeClass('current');
        var clicked = $(this);
            clicked.addClass('current');
        var incoming = clicked.attr('href');
        if ( $(incoming).hasClass('current') ) {
            //  do nothing; we're on this slide already
        }
        else {
            $('#slides .current').removeClass('current').addClass('outgoing');
            $(incoming).addClass('current').fadeIn();
            $('#slides .outgoing').fadeOut().removeClass('outgoing');
        }
        return false;
    });
    
}

$(document).ready( function() {
    hero();
});


/**
 * 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: 2010-12-06 {pf}
 *
 */

//  Warning to appear on form error
var reqWarnBody = 'Please check the form field(s) highlighted and try again.';
var reqWarn = '<div class="warningInner">' + reqWarnBody + '</div>';

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('hint') ) {
                if ( field.val() == field.attr('title') ) {
                    field.val('');
                }
            }
            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.val() == field[0].defaultValue) {
                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: 2010-12-06 {pf}
 */

function checkRequireds(thisForm) {
    
    //  Assume failure by default
    var validated = false;
    
    //  Failure counter
    var failed = 0;
    
    //  NOTE: ':input' is jQuery shorthand for *all* form field types
    $(':input.required', thisForm).each( function () {
        
        
        //  Remove any residual hints before processing
        if ( $(this).hasClass('hint') && $(this).val() == $(this).attr('title') ) {
            $(this).val('');
        }
        
        var fieldValid = validateField($(this));
        
        //  If this field doesn't pass validation, wrap it in an error marker
        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');
            
            //  Reinstate hint
            if ( $(this).hasClass('hint') && $(this).val('') ) {
                $(this).val( $(this).attr('title') );
            }
            
        }
        //  ...otherwise strip out the surrounding error marker if it's now valid
        else {
            
            //  Remove error highlight (if present)
            $(this).parents('.errorRow').removeClass('errorRow');
            $(this).parent().removeClass('error');
            
        }
        
    });
    
    //  If the fail count is above zero, show warning to user
    if (failed > 0) {
        
        //  Attach warning markup from this JS file to page and show
        if ( $('div.warningInner', thisForm).length < 1 ) {
            $(reqWarn).appendTo(thisForm).slideDown(250);
        }
        //  ...or simply show the warning already in the markup
        else {
            $('div.warningInner', thisForm).slideDown(250);
        }
        
    }
    //  ...otherwise they've passed, so flag as successful
    else if (failed == 0) {
        
        validated = true;
        
    }
    
    //  Validation result
    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: 2009-08-14 {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', thisForm).click( function() {
                if (checkRequireds(thisForm, $callback != null)) {
                    if ($callback != null) {
                        callFunction($callback, [thisForm]);
                    }
                    return true;
                } else {
                    return false;
                }
            });
        }
        
    });
    
}

$(document).ready( function() {
    findRequireds();
});


/**
 * 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);
}


/**
 *	Input Hinting
 *	Shows the "title" of a text input as a "hint" inside the field;
 *	clears on focus.
 *	Last modified: 2010-12-06 {pf}
 */
function inputHinting() {
    
	$(':input.hint').each( function() {
        
        //  Only hint if field is already empty (i.e. hasn't failed validation)
        if( $(this).val() == '' || $(this).val() == $(this).attr('title') ) {
            
            //  Add hint by default
            $(this).val($(this).attr('title'));
            
            //  Remove hint on focus (if still present)
            $(this).focus( function() {
                if ( $(this).val() == $(this).attr('title') ) {
                    $(this).val('');
                }
            });
            
            //  Reinstate hint on blur if empty
            $(this).blur( function() {
                if ( $(this).val() == '' ) {
                    $(this).val( $(this).attr('title') );
                }
            });
            
        }
        
	});
    
}

$(document).ready( function() {
    inputHinting();
});

