/***************************************************
Design & Technology by Reading Room
www.readingroom.com (020) 7173 2800
* Author: Lucy Kavanagh
* Created: Jan 2010
* Updated: Apr 2010
***************************************************/

/***** ~~~~~ activate font replacement ~~~~~ *****/
	
Cufon.replace('#menu strong, #menu em, .spotlight h2, #supporting .body h2', {fontFamily: 'Gill Sans MT'});
Cufon.replace('blockquote p', {fontFamily: 'Daniel'});

jQuery(document).ready(function() {

    /***** ~~~~~ misc enhancements ~~~~~ *****/

    // Detect IE
    if (jQuery.browser.msie) {
        var ieX = (parseInt(jQuery.browser.version));
        if (ieX == 8) { jQuery('body').addClass('ie8'); }
        else if (ieX == 7) { jQuery('body').addClass('ie7'); }
        else if (ieX == 6) { jQuery('body').addClass('ie6'); };
    }

    // Target="_blank" solution for external links in XHTML strict
    jQuery('a.ext').click(function() { window.open(jQuery(this).attr('href')); return false; })
    jQuery('a.ext[!title]').each(function() {
        if (jQuery(this).attr('title') !== undefined && jQuery(this).attr('title') !== "") {
            var extTitle = jQuery(this).attr('title');
            jQuery(this).attr('title', extTitle + ' (opens in a new window)');
        }
        else {
            jQuery(this).attr('title', 'This link will open in a new window');
        }
    });

    // Equalise spotlight columns
    jQuery('.threeCol .spotlight').equalCols();

    // Bonus
    var bonuscombo = [], konami = "38,38,40,40,37,39,37,39,66,65";
    jQuery(document).keydown(function(e) { bonuscombo.push(e.keyCode); if (bonuscombo.toString().indexOf(konami) >= 0) { jQuery(document).unbind('keydown', arguments.callee); jQuery('.logo').animate({ paddingLeft: "400px" }, 1500).animate({ paddingLeft: "0" }, 1500) } });

    /***** ~~~~~ enhanced rollover / tabbing ~~~~~ *****/

    // General focus enhancement for IE6's benefit (:focus pseudo in IE6 will not respect backgrounds/borders)
    jQuery('a,input').focus(function() { jQuery(this).addClass('focus'); });
    jQuery('a,input').blur(function() { jQuery(this).removeClass('focus'); });

    // Team thumbnail rollover / tabbing
    jQuery('.teamGrid li').hover(
		function() { jQuery(this).children('dl').slideDown('slow'); },
		function() { jQuery(this).children('dl').slideUp(); }
	);
    jQuery('.teamGrid a').focus(function() { jQuery(this).siblings('dl').slideDown('slow'); });
    jQuery('.teamGrid a').blur(function() { jQuery(this).siblings('dl').slideUp('slow'); });

    // Tertiary nav clicking / tabbing
    jQuery('.tertiary').attr('id', 'dropdown');
    jQuery('.tertiary em').wrapInner('<a href="#dropdown"></a>').toggle(
		function() { jQuery(this).addClass('open'); jQuery('.tertiary ol li').slideDown(750); },
		function() { jQuery(this).removeClass('open'); jQuery('.tertiary ol li').slideUp(750).removeClass('open'); }
	);
    jQuery('.tertiary em a').focus(function() { jQuery('.tertiary ol li').slideDown(750); })
    jQuery('.tertiary ol li:last a').blur(function() { jQuery('.tertiary ol li').slideUp(750); });

    /***** ~~~~~ activate plugins ~~~~~ *****/

    // Start homepage cycle
    if (jQuery('.highlights') != null) {
        jQuery('.highlights').addClass('cycleGen');
        jQuery('.ie7 .highlights, .ie8 .highlights').removeClass('cycleGen').addClass('cycleIE');
        jQuery('.highlights .top').remove();
        jQuery('.cycleGen ul').cycle({
            fx: 'scrollLeft', speed: 1200, timeout: 7000, pager: '.panelThumbs', pagerAnchorBuilder:
			function(idx, slide) { return '.panelThumbs li:eq(' + idx + ') a'; }
        });
        jQuery('.cycleIE ul').cycle({
            fx: 'none', speed: 1200, timeout: 7000, pager: '.panelThumbs', pagerAnchorBuilder:
			function(idx, slide) { return '.panelThumbs li:eq(' + idx + ') a'; }
        });
        jQuery('.highlights ul li').css('visibility', 'visible');
        Cufon.replace('.highlights h3', { fontFamily: 'Gill Sans MT' });
        Cufon.replace('.highlights h4', { fontFamily: 'Arial Narrow' });
    };

    // Start media carousel
    if (jQuery('.reel li').length > 5) {
        jQuery(".reelOuter").prepend('<a href="#" class="next"><img src="/images/G4S Sports/design/button-next.gif" alt="Next" /></a><a href="#" class="prev"><img src="/images/G4S Sports/design/button-prev.gif" alt="Prev" /></a>')
        jQuery(".reelInner").jCarouselLite({ btnNext: ".reel .next", btnPrev: ".reel .prev", visible: 5, scroll: 5, speed: 1000 });
    }

    // Start img modals
    jQuery("a[rel='cat01'],a[rel='cat02'],a[rel='reelImg'],a[rel='profileImg']").colorbox({
        current: '<em>{current} of {total}:</em> Photos',
        previous: '<img src="/images/G4S Sports/design/button-prev.png" alt="Prev" />',
        next: '<img src="/images/G4S Sports/design/button-next.png" alt="Next" />',
        close: '<img src="/images/G4S Sports/design/button-close.png" alt="Close" />',
        onOpen: function() { jQuery('object').hide(); },
        onComplete: function() { if (ieX == 6) { DD_belatedPNG.fix('#cboxPrevious img,#cboxNext img,#cboxClose img') } },
        onCleanup: function() { jQuery('object').show(); }
    });

    // Start vid modals
    jQuery("a[rel='reelVid'],a[rel='profileVid']").colorbox({
        current: "{current} of {total} Videos",
        iframe: true,
        innerWidth: 400,
        innerHeight: 300,
        previous: '<img src="/images/G4S Sports/design/button-prev.png" alt="Prev" />',
        next: '<img src="/images/G4S Sports/design/button-next.png" alt="Next" />',
        close: '<img src="/images/G4S Sports/design/button-close.png" alt="Close" />',
        onOpen: function() { jQuery('object').hide(); },
        onComplete: function() { if (ieX == 6) { DD_belatedPNG.fix('#cboxPrevious img,#cboxNext img,#cboxClose img') } },
        onCleanup: function() { jQuery('object').show(); }
    });

    /***** ~~~~~ thumbnail switcher ~~~~~ *****/

    // Move gallery links to bottom
    jQuery('.gallerySplit .moreMedia').append('<li class="more"></li>').siblings('p.more').each(function() {
        jQuery(this).children('a').appendTo('.gallerySplit li.more');
        jQuery(this).remove();
    });

    // Create tabs and default first category to active
    jQuery('.gallerySplit').prepend('<p class="choices">View: </p>')
    jQuery('.gallerySplit .thumbs').prev('h3').each(function() {
        var tFst = 'cat01';
        var tTxt = jQuery(this).html();
        var tCls = jQuery(this).attr('class');
        var tCon = jQuery(this).next('.thumbs');
        var tLinks = jQuery(this).siblings('.choices');
        jQuery(this).appendTo(tLinks).replaceWith('<a href="#none" class="' + tCls + '">' + tTxt + '</a>');
        if (tCls == tFst) { tCon.addClass('on'); }
        else { jQuery('.gallerySplit .moreMedia .' + tCls).hide(); }
    });
    jQuery('.gallerySplit .choices').children('a:first').addClass('on').after('&nbsp;&#47;&nbsp;');

    // Switch to new tab (but only when clicking non active tab)
    jQuery('.gallerySplit .choices a').click(function() {
        var cat = jQuery(this).attr('class');
        if (cat.match('on') == null) {
            jQuery(this).addClass('on').siblings('a').removeClass('on');
            jQuery('.gallerySplit .thumbs').removeClass('on');
            jQuery('.gallerySplit .thumbs.' + cat).addClass('on');
            jQuery('.gallerySplit .moreMedia .more a').hide();
            jQuery('.gallerySplit .moreMedia .' + cat).show();
        }
        return false;
    });

    /***** ~~~~~ news filter ~~~~~ *****/

    var filO = jQuery('.filter');
    var filI = jQuery('.filter .wrap');

    // Hide filter
    filI.hide();

    // Don't hide filter if search has been performed
    if (jQuery('.dateFrom, .dateTo').attr('value') !== 'DD/MM/YYYY' || jQuery('.filter .keywords').is('[value]')) { filI.show(); };

    // Make legend control filter
    jQuery('.filter legend').wrapInner('<a href="#" title="Show filter"></a>');
    jQuery('.filter legend a').click(function() {
        if (filO.hasClass('open')) { filO.removeClass('open'); filI.slideUp(); }
        else { filO.addClass('open'); filI.slideDown(); }
        return false;
    });

    // Activate datepicker
    jQuery('.dateFrom, .dateTo').datepicker({
        showOn: "both",
        beforeShow: dateRanges,
        dateFormat: "dd/mm/yy",
        firstDay: 1,
        changeFirstDay: false
    });

    // Start date cannot be after end date / end date cannot be before start date
    function dateRanges() {
        var dateMin = new Date(2008, 0, 1);
        var dateMax = null;
        if (jQuery(this).hasClass('dateFrom')) {
            if (jQuery(".dateTo").datepicker("getDate") != null && jQuery(".dateTo").attr('value') !== 'DD/MM/YYYY') { dateMax = jQuery(".dateTo").datepicker("getDate"); }
            else { dateMax = new Date(); }
        }
        else if (jQuery(this).hasClass('dateTo')) {
            dateMax = new Date();
            if (jQuery(".dateFrom").datepicker("getDate") != null && jQuery(".dateFrom").attr('value') !== 'DD/MM/YYYY') { dateMin = jQuery(".dateFrom").datepicker("getDate"); }
        }
        return { minDate: dateMin, maxDate: dateMax };
        jQuery('.datepicker iframe').remove();
    }

    // Remove default date value on focus
    jQuery('.dateFrom, .dateTo').focus(function() {
        if (jQuery(this).attr('value') == 'DD/MM/YYYY') {
            jQuery(this).removeAttr('value');
        }
    }).blur(function() {
        cur = jQuery(this);
        if (!cur.is('[value]')) {
            cur.attr('value', 'DD/MM/YYYY');
        }
    });

    /***** ~~~~~ modal form ~~~~~ *****/

    //	if (jQuery('.newsletter').length < 1 && jQuery('.overlay').length < 1) {

    //		jQuery('.promo .major a').click(function(){
    //			nlUrl = jQuery(this).attr('href') + '?mode=ajax';
    //	
    //			jQuery('form').prepend('<div class="overlay"></div>').children('.overlay').load(nlUrl.replace(/ /g,"%20") + " .content .wrap", function(){
    //				jQuery('object').hide();
    //				jQuery('.container').fadeTo('medium', 0.1);
    //				jQuery('.overlay .wrap').prepend('<a href="#none" title="Close the newsletter sign up form" class="close"><img src="/images/G4S Sports/design/icon-cross.gif" alt="Cross" /></a>')
    //				Cufon.replace('.overlay h1', {fontFamily: 'Gill Sans MT'});
    //				jQuery('.overlay .close').click(function(){
    //					jQuery('object').show();
    //					jQuery('.overlay').fadeOut(function(){jQuery(this).remove();});
    //					jQuery('.container').fadeTo('medium', 1);
    //				});
    //				nlValid();
    //			});
    //			return false;
    //		});
    //		
    //	};

    /***** ~~~~~ live form validation ~~~~~ *****/

    // intention: this function will be called in the dynamically loaded version of form
    // objective: to present more user friendly validation in the modal box through the use of inline validation
    function nlValid() {
        if (jQuery('.newsletter').length = 1) {
            jQuery("form").submit(function(event) {

                var nmV = jQuery('.nlName').val();
                var nmC = jQuery('.nlName').parent('div');
                var mlV = jQuery('.nlMail').val();
                var mlC = jQuery('.nlMail').parent('div');
                var tcV = jQuery('.nlTerms').attr('checked');
                var tcC = jQuery('.nlTerms').parent('div');
                var dot = '.';
                var at = '@';

                function nmE() { nmC.addClass('error').children('.msg').remove(); };
                function mlE() { mlC.addClass('error').children('.msg').remove(); };

                // if any of these errors exist, do not submit
                if (nmV == "" || nmV.length < 3 || nmV.length > 100 || mlV == "" || mlV.length > 200 || mlV.indexOf(at) == -1 || mlV.indexOf(dot) == -1 || mlV.length < 6 || tcV == false) {

                    event.preventDefault();

                    // name field error notification
                    if (nmV == "" || nmV.length < 3 || nmV.length > 100) {
                        if (nmV == "" || nmV.length < 3) {
                            nmE(); nmC.prepend('<em class="msg">Please let us know your name:</em>');
                        }
                        else if (nmV.length > 100) {
                            nmE(); nmC.prepend('<em class="msg">Please enter 100 characters here:</em>');
                        }
                    }
                    else { nmC.removeClass('error').children('.msg').remove(); }

                    // email field error notification
                    if (mlV == "" || mlV.length > 200 || mlV.indexOf(at) == -1 || mlV.indexOf(dot) == -1 || mlV.length < 6) {
                        if (mlV == "") {
                            mlE(); mlC.prepend('<em class="msg">Don\'t forget to give us your email address:</em>');
                        }
                        else if (mlV.length > 200) {
                            mlE(); mlC.prepend('<em class="msg">Please enter no more than 200 characters here:</em>');
                        }
                        else if (mlV.indexOf(at) == -1 || mlV.indexOf(dot) == -1 || mlV.length < 6) {
                            mlE(); mlC.prepend('<em class="msg">Please enter a valid email (eg: yourname@provider.com):</em>');
                        }
                    }
                    else { mlC.removeClass('error').children('.msg').remove(); }

                    // terms checkbox error notification
                    if (tcV == false) {
                        tcC.addClass('error').children('.msg').remove();
                        tcC.prepend('<em class="msg">Please tick to confirm you agree:</em>');
                    }
                    else { tcC.removeClass('error').children('.msg').remove(); }

                    return false;
                }

                else { return true; }

            });
        };
    };



});