/**
 *  Table Striper
 *  Shades even table body rows inside tables with a class of
 *  "stripes".
 *  Last modified: 2010-07-28 {pf}
 */
function tableStriper() {
    $('table.stripes tr:even').addClass('shade');
}

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


/**
 *  Find Externals [new window]
 *  Simple function that looks for any links with a "rel" attribute set
 *  to "external" and sets them to open in new windows.
 *  Last modified: 2010-05-17 {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(); 
});

/**
* Used for the Destination list of the Destinations page
* works with 2nd level nested lists
*/
function expandingLists() {

    $('.expander li ul').hide();

    $('.expander li ul').prev().click(
        function(event) {
            event.preventDefault();
            
            var checkElement = $(this).next();
            
            if((checkElement.is('.expander li ul')) && (checkElement.is(':visible'))) {
                checkElement.parent().removeClass('current');
                checkElement.slideUp('fast');
            }
            if((checkElement.is('.expander li ul')) && (!checkElement.is(':visible'))) {
                checkElement.parent().addClass('current');
                checkElement.slideDown('fast');
            }
            
            return false;
        }
    );

}

/**
* Used for the FAQ area of the Contact page
* works with 1 level list with a p element as the expanding element.
*/
 
function expander() {

    $('.expander li p').hide();
    
    $('.expander li:first p').parent().addClass('current');
    $('.expander li:first p').slideDown('fast');

    $('.expander li h3').click(
        function() {
            
            var checkElement = $(this).next();

            if((checkElement.is('.expander li p')) && (checkElement.is(':visible'))) {
                checkElement.parent().removeClass('current');
                checkElement.slideUp('fast');
            }
            
            if((checkElement.is('.expander li p')) && (!checkElement.is(':visible'))) {
                //$('.expander li p:visible').slideUp('fast');
                checkElement.parent().addClass('current');
                checkElement.slideDown('fast');
            }
            
            return false;
        }
    );

}

/**
* TODO: Would be nice to have a reusable function for expanding lists.
* I have tried but my jQuery fu is not that good. (Dave Sayer)
*/
//function genericExpander() { }

/**
 *  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);
        
        //  Check this input has a title value
        if ( $input.attr('title').length > 0 ) {
            
            //  Populate value with "title"
            $input.val( $input.attr('title') );
            
            //  Blank value on focus
            $input.focus( function() {
                $input.val('');
            });
            
            //  Reinstate hint if field left empty
            $input.blur(function() {
                if ($input.val() == '') {
                    $input.val($input.attr('title'));
                }
            });
            
        }
        
    });
}

/**
 * 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') + ' 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.
 *
 * 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', 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) {

            $('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 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;
                }
            });
        }
    });
    
}

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

/**
 * Bind Date
 * 
 * Automatically binds a jQuery UI date picker to a field in
 * the main content, if it has a class of "date".
 * 
 * Last modified: 2010-11-17 {pf}
 */
function bindDate() {
	
	if ( $('#content .formWrapper input.date').length ) {
		
		var dateNow = new Date();
		
		var datepickerDefaults = {
			dateFormat: 'dd/mm/yy',
			firstDay: 1, /* Monday */
			minDate: -364,
			maxDate: dateNow
		};
		
		$('#content .formWrapper input.date').datepicker( datepickerDefaults );
		
	}
	
}

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

