/**
 * 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) {
        
        if ( $('div.warning', thisForm).length < 1 ) {
            //  Requires 'reqWarn' HTML string (top of this file)
            $(reqWarn).prependTo(thisForm).slideDown(250);
        }
        else {
            $('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);
}
            
// Bind form validation when DOM ready [uses jQuery]
$(document).ready( function() {
    if ( $(':input.required').length > 0 ) {
        findRequireds();
    }
});


/**
 *  Content Modals
 *  Allows the user to automagically create modal windows for any link.
 *  Last modified: 2010-05-04 {pf}
 */
var contentModalDefaults = {
    autoOpen : false,
    draggable : false,
    width : 854,
    height : 650,
    modal : true,
    resizable : false
};

function createContentModal(contentID) {
    var modalID = contentID + 'Modal';
    var contentIDRef = '#' + contentID;
    var contentURL = $(contentIDRef).attr('href');
    var contentModal = $('<div id="' + modalID + '" class="modal"></div>').html('<iframe src="' + contentURL + '" frameborder="0" marginwidth="0" marginheight="0" scrolling="auto" width="800" height="600"></iframe>');
    $('body').append(contentModal);
    modalIDRef = '#' + modalID;
    $(modalIDRef).dialog(contentModalDefaults);
    $(modalIDRef).css('padding', '0');
    return modalIDRef;
}

$(document).ready( function() {
    $('a.modal').each( function() {
        var modalID = createContentModal( $(this).attr('id') );
        $(this).click( function() {
            $(modalID).dialog('open');
            return false;//prevent default hyperlink action
        });
    });
});


/**
 *  Automatically Open Modal via URI
 *  This is a callback that opens a modal window by ID in the URI upon
 *  page load.
 *  Last modified: 2010-05-05 {pf}
 */
function autoOpenModal() {
    if ( document.location.href.indexOf('?') ) {
        var uriParts = document.location.href.split('open=');
        var hashID = '#' + uriParts[1];
        if ( $(hashID) && $(hashID).hasClass('dialog')) {
            $(hashID).dialog('open');
        }
    };
}


/**
 *  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(); 
});


/**
 *  Test IE7
 *  This is a very simple function to test if the user is browsing
 *  with Internet Explorer 7. It's not comprehensive as we only need
 *  to test (and change certain features) for IE7 alone.
 *  Last modified: 2010-06-23 {pf}
 */
function testIE7() {
    
    var result = false;
    
	var ie = navigator.userAgent.indexOf('MSIE');
    
	if ( ie != -1 && ie >= 0) {
		ie = parseFloat(navigator.appVersion.split('MSIE')[1]);
		if ( ie == 7 ) {
            result = true;
        }
    }
    
    return result;
    
}

//  Global reference var for other libraries/functions
var isIE7 = testIE7();


/**
 *  "In the press" News Ticker
 *  Last modified: 2011-02-04 {pf}
 */
function inThePress() {
    
    var carousel = $('#newsTicker');
    
    $('#scrollPrev').unbind('click').click( function () {
        
        if ( !jQuery(this).hasClass('disabled') ) {
            
            var currBlock = carousel.find('li.current');
            var nextBlock = currBlock.prev();
            
            scrollCarousel( carousel, nextBlock );
            
        }
        
        clearInterval(scrollTimer);
        
        return false;
        
    });
    
    $('#scrollNext').unbind('click').click( function () {
        
        if ( !jQuery(this).hasClass('disabled') ) {
            
            var currBlock = carousel.find('li.current');
            var nextBlock = currBlock.next();
            
            scrollCarousel( carousel, nextBlock );
            
        }
        
        clearInterval(scrollTimer);
        
        return false;
        
    });
    
    //  Auto scrolling
    var scrollTimer = setInterval( function() { autoScroll(carousel, scrollTimer) }, 5000);
    
}

function autoScroll(carousel, scrollTimer) {
    var nextBlock = carousel.find('li.current').next();
    if ( nextBlock.position() != null ) {
        scrollCarousel( carousel, nextBlock );
    }
    else {
        // Already on last block; stop auto-scrolling (clear interval)
        clearInterval(scrollTimer);
    }
}

function scrollCarousel( carousel, nextBlock ) {
    
    carousel.find('ul').stop().animate( {left: -nextBlock.position().left}, function () {
        $(window).resize();
    });
    
    carousel.find('li.current').removeClass('current');
    nextBlock.addClass('current');
    
    updateCNav( carousel, nextBlock );
    
}

function updateCNav( carousel, currBlock ) {
    
    var $firstBlock = carousel.find('li:first');
    var $lastBlock = carousel.find('li:last');
    
    carousel.find('a.scroll').removeClass('disabled');
    
    if ( currBlock.attr('id') == $firstBlock.attr('id') ) {
        $('#scrollPrev').addClass('disabled');
    }
    else if ( currBlock.attr('id') == $lastBlock.attr('id') ) {
        $('#scrollNext').addClass('disabled');
    }
    
}

$(function() {
    if ( $('#newsTicker').length > 0 ) {
        inThePress();
    }
});


/**
 *  Media Centre
 *  Last modified: 2011-04-05 {pf}
 */
$(function() {
    var photos = $('ul.images input:checkbox');
    var all = $('p.all input');
    all.change( function() {
        if ( all.attr('checked') ) {
            photos.attr('checked','checked');
        }
        else {
            all.removeAttr('checked');
            photos.removeAttr('checked');
        }
    });
});

