// load typekit
try { Typekit.load(); } catch(e) {}

var Caba = function() {
    /**
     * Check IE version
     */
    var ieVersion = function() {
        var rv = -1;
        if (navigator.appName == 'Microsoft Internet Explorer') {
            var ua = navigator.userAgent;
            var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat( RegExp.$1 );
        }
        return rv;
    };
    /**
     * Sets and replaces default search text
     */
    var defaultSearch = function() {
        var txt = "Search";
        if (!$('input.search').val()) {
            $('input.search').val(txt);
        }
        $('input.search').focus(function(){
            if ($('input.search').val() == txt) {
                $('input.search').val('');
            }
        });
        $('input.search').blur(function(){
            if (!$('input.search').val()) {
                $('input.search').val(txt);
            }
        });
    };
    /**
     * Homepage feature boxes behaviour
     */
    var initFeatureBoxes = function() {
        var boxCount = 0;
		// show initial image before rollover behaviour
        $('.feature-boxes .section').each(function(){
            if (0 == boxCount) {
                $(this).addClass('active');
            } else {
                $(this).addClass('inactive');
            }
            boxCount++;
        });
        var links = [
            'feature-link-one',
            'feature-link-two', 
            'feature-link-three', 
            'feature-link-four'
        ];
        var linkCount = 0;
        $('.feature-links .section').each(function(){
            $(this).addClass('inactive').removeClass(links[linkCount]).attr('id', links[linkCount]);
            linkCount++;
        });
        $('.feature-links .section').hover(
            function() { _toggleActive($(this)); },
            function() { /* no blur action */ }
        );
        $('#feature-container').wrap('<a href="" id="tabLink" />');
    };
    /**
     * Internal utility function that sets active classes on corresponding 
     * content elements given a title element
     * @param {Object} el
     */
    var _toggleActive = function(el) {
    	var box = '.' + el.attr('id').replace(/link/, 'box');
        $('.feature-links .section').removeClass('active').addClass('inactive');
        $('.feature-boxes .section').removeClass('active').addClass('inactive');
        $(box).removeClass('inactive').addClass('active');
        el.removeClass('inactive').addClass('active');
        
        var tabLink = $('#tabLink'); 
        var mainLink = $('.feature-boxes .active a.button-link');
        var target = mainLink.attr('target');
        
        tabLink.removeAttr('target');
        tabLink.attr('href', mainLink.attr('href'));
        if (target) {
        	tabLink.attr('target', target);
        }
    };
    /**
     * Add selected class to homepage only on the homepage
     */
    var addSelectedMenuItem = function() {
        if (!$('.main-menu li').hasClass('selected')) {
            $('.main-menu li:first').addClass('selected');
        }
        $('.main-menu ul.level1 li:last-child').addClass('last');
        $('.rhs-sub-menu ul.level1 li:last-child').addClass('last');
        $('.rhs-sub-menu ul.level2 li:first-child').addClass('first');
        $('.rhs-sub-menu ul.level2 li:last-child').addClass('last');
        $('#rhs-nav .related-pages a:last').addClass('last');
        $('.cmsTagsFilter li:last, .cmsWidgetMonths li:last').addClass('last');
        
        $('ul.level1 > li').each(function(){
            var txt = $(this).find('a:first').text();
            $(this).addClass(txt.replace(/\s/g,'-').toLowerCase());
        });
    };
    /**
     * Sets up the tabs for the body section of homepage
     */
    var initTabs = function() {
        $('#body #title-news').addClass('active');
        $('#body #content-news').addClass('active');
        $('#body .tabbed-content .titles div').click(function(){
            $('#body .tabbed-content .titles div').removeClass('active');
            $(this).addClass('active');
            var el = '#' + $(this).attr('id').replace(/title/, 'content');
            $('#body .tabbed-content .content div').removeClass('active');
            $(el).addClass('active');
        });
        
        // contact form tabs
        var activeTitle = "#tab-title-" + $('#body .tabs').attr('id');
        var activeTab = "#tab-content-" + $('#body .tabs').attr('id');
        
        $(activeTab).addClass('active');
        $(activeTitle).addClass('active');
        
        $('.edit-member .tabs .titles div').click(function(){
            $('.edit-member .tabs .titles div').removeClass('active');
            $(this).addClass('active');
            var el = '#' + $(this).attr('id').replace(/title/, 'content');
            $('.edit-member .tabs .content div').removeClass('active');
            $(el).addClass('active');
        });
        // show the correct form on errors
        if ($('.edit-member .tabs .content').find('ul').hasClass('errors')) {
            $('.edit-member .tabs .content div').removeClass('active');
            $('.edit-member .tabs .content').find('ul.errors').parents('.tab').addClass('active');
            try {
                var el = '#' + $('.edit-member .tabs .content').find('ul.errors').parents('.tab').attr('id').replace(/content/, 'title');
            } catch (e) {}
            $('.edit-member .tabs .titles div').removeClass('active');
            $(el).addClass('active').css({color: '#cc0000'});
        }
        
    };
    /**
     * Adds additional html markup to style pull quotes correctly
     */
    var replacePullQuotes = function() {
        var htmlTop = '<div class="top"></div>';
        var htmlMid = '<div class="middle"></div>';
        var htmlBot = '<div class="bottom"></div>';
        $('.pullquote-right-blue, .pullquote-left-blue, .pullquote-right-green, .pullquote-left-green').wrapInner(htmlMid).prepend(htmlTop).append(htmlBot);
    };
    /**
     * Add view all buttons to RHS nav bar for blog/news listings
     */
    var addRhsButtons = function() {
        var button = '<a class="button-link" href="/news-and-stories/blog/" '
                   + 'title="View all blog posts"></a>';
        $('.searchResults.blogs .result').append(button);
        var button = '<a class="button-link" href="/news-and-stories/press/" '
                   + 'title="View all news stories"></a>';
        $('.searchResults.news .result').append(button);
    };
    /**
     * Add click behaviour to whole li elements
     */
    var initMenu = function() {
        $('.main-menu ul.level2 li').click(function(e){
            e.preventDefault();
            e.stopPropagation();
            window.location.href = $(this).find('a').attr('href');
        });
        $('.main-menu ul.level1 li').click(function(e){
            e.preventDefault();
            e.stopPropagation();
            window.location.href = $(this).find('a').attr('href');
        });
        if (ieVersion() > 0) {
            $('.main-menu ul.level2').hide();
            $('.main-menu li').hover(
                function(){
                    $(this).find('ul.level2').slideDown('fast');
                },
                function(){
                    $(this).find('ul.level2').hide();
                }
            );
        }

        if (typeof $.browser.mozilla != 'undefined') {
            $('#hd .main-menu ul.level1 li').css({ 'padding-left': '11px', 'padding-right': '12px' });
            $('#hd .main-menu ul.level1 li.home').css({ 'padding-left': '15px' });
            $('#hd .main-menu ul.level1 li.last').css({ 'padding-right': '15px' });
        }
        if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
            $('#hd .main-menu ul.level1 li').css({ 'padding-left': '11px', 'padding-right': '11px' });
            $('#hd .main-menu ul.level1 li.home').css({ 'padding-left': '15px' });
            $('#hd .main-menu ul.level1 li.last').css({ 'padding-right': '15px' });
        }
        if((navigator.userAgent.match(/android/i))) {
            $('#hd .main-menu ul.level1 li').css({ 'padding-left': '9px', 'padding-right': '9px' });
            $('#hd .main-menu ul.level1 li.home').css({ 'padding-left': '11px' });
            $('#hd .main-menu ul.level1 li.last').css({ 'padding-right': '11px' });
        }
    };
    /**
     * Apply odd/even classes to listings
     */
    var addOddEven = function() {
        var count = 1;
        $('.subsection .section-listing .snippet-sections li').each(function(){
            if (count % 2) {
                $(this).addClass('odd');
            } else {
                $(this).addClass('even');
            }
            count++;
        });
        var count = 1;
        $('.searchResults .result, .listingItem').each(function(){
            if (count % 2) {
                $(this).addClass('odd');
            } else {
                $(this).addClass('even');
            }
            count++;
        });

        $('ul.staff').each(function(){
            var count = 1;
            $(this).find('li').each(function(){
                if (count % 2) {
                    $(this).addClass('odd');
                } else {
                    $(this).addClass('even');
                }
            count++;
            });
        });
    };
    var miscReplacements = function() {
        $('.next').text('next');
        $('.previous').text('previous');
        $('.main-blog-listing .main-listing-comments').each(function(){
            if ($(this).text() == '' || $(this).text() == '0 comment') {
                var html = '<span class="bubble"></span><span class="count">'
                         + '0 comments</span>';
            } else {
                var html = '<span class="bubble"></span><span class="count">' 
                         + parseInt($(this).text()) + ' comments</span>';
            }
            $(this).html(html);
        });
        $('.main-press-listing .main-listing-comments').each(function(){
            if ($(this).text() == '' || $(this).text() == '0 comment') {
                var html = '<span class="bubble"></span><span class="count">'
                         + '0 comments</span>';
            } else {
                var html = '<span class="bubble"></span><span class="count">' 
                         + parseInt($(this).text()) + ' comments</span>';
            }
            $(this).html(html);
        });
        $('.case-study .date').hide();
    };
    var eventReplacements = function() {
        $('#voucherCode-label').remove();
        /*
        $('.event .date').prepend('<h2 class="event-subHead">Date</h2>');
        $('.event .time').prepend('<h2 class="event-subHead">Time</h2>');
        $('.event .location').prepend('<h2 class="event-subHead">Location</h2>');
        $('.event .venue').prepend('<h2 class="event-subHead">Venue</h2>');
        */
        $('.events #body .event .date').hide();
        $('.events #body .event .time').hide();
        $('.events #body .event .location').hide();
        $('.events #body .event .venue').hide();
        
        $('#applyVoucherCode-label').remove();
        if ($('#eventTicketSelection').length) {
            $('#eventTicketSelection').wrap('<div class="ticket-selection"/>');
            $('.eventVoucherCode').prependTo($('.ticket-selection'));
        } else {
            $('.eventVoucherCode').wrap('<div class="ticket-selection"/>');
        }
        
        $('#noTicketsAvailable').prependTo($('.ticket-selection'));
        $('#noTicketsAvailable').show();
        
        $('.quantity select').each(function(i, el) {
           var name = $(this).attr('name');
           $(this).parents('.quantity').append('1<input type="hidden" name="' + name + '" value="1" />');
           $(this).remove();
        });
        
        $('#guestDetailsForm').wrap('<div class="guestDetailsForm" />');
        $('.quantity select').append('<option value="1">1</option>');
        $('.basketContent').wrap('<div class="basket-wrapper"/>');
        $('.basket-wrapper').prepend('<h2>Your order</h2>');
        
        $('#eventTicketSelectionForm').prepend('<h2>Price: ' + $('.ticketDetails td.price').text() + '</h2>');

        if (document.location.hash != '#eventVoucherCode') {
            $('#eventVoucherCodeForm').hide();
        }  
        $('.eventVoucherCode .title').click(function() {
            $(this).toggleClass('active');
            $('#eventVoucherCodeForm').toggle();    
            $('.eventVoucherCode .messages').toggle();    
        });
        
        $('.events-search dt').each(function() {
            $(this).wrap('<div class="searchItem" />');
            $(this).parents('.searchItem').append($(this).parents('.searchItem').next('dd'));
        });
        
        $('.searchItem:last').addClass('last');
        $('.eventVoucherCode .title').text('Do you have a voucher code');
        $('.guestTitle').hide();
        $('#eventGuestDetails h1').text('Delegate details');
        $('#eventGuestDetails .ticketDetails').wrap('<div class="summary-wrapper" />');
        $('#eventGuestDetails .summary-wrapper').prepend('<h2>Booking</h2>');
        
        var multiBooking = "<div class='clearing'></div>" 
                         + "<div class='event-multi-booking'>"
                         + "<p>If you would like to book multiple places, or "
                         + "apply for a concession if you are unwaged please "
                         + "contact us on <strong>01788 556373</strong>.</p>"
                         + "</div>";
        $('.events .ticket-selection').append(multiBooking);
        $('.onlineForm').hide();
        if ($('#noTicketsAvailable').length) {
            $('.onlineForm').attr('id', 'waiting-list');
            var html = "<div class='waiting-list-intro'>To be contacted "
                     + "if places become "
                     + "available for this event please submit your email "
                     + "address via this form.</div>";
            $('#waiting-list').prepend(html);
            var event = $('.event h1.title').text() + " - "
                      + $('.event div.date').text() + " - "
                      + $('.event div.time').text();
            $('.onlineForm #event').val(event);
            $('.onlineForm').show();
            if ($('#waiting-list .messages').length) {
                $('.waiting-list-intro').remove();
                var html = "<ul class='messages success'><li>Your email has been added</li></ul>";
                $('#waiting-list').prepend(html);
            }
        }
    };
    
    /**
     * Enable fancybox functionality for picture galleries
     */
    var initGallery = function() {
        $('.gallery .snippet-item li a').attr('rel', 'gallery').addClass('gallery-item');
        $('.gallery .snippet-item li a.gallery-item').fancybox();
        
        var overlay = '<img class="play-overlay" '
            + 'src="/images/buttons/play-small.png" '
            + 'width="48px" height="34px" />';
        
        // adds overlaid play buttons and uses thumbnails or youtube images
        $('.video-listing-video').each(function(){
            if ($(this).parent().find('.video-listing-thumbnail').html() != "") {
                var youTube = $(this).text();
                $(this).hide();
                var title = $(this).parent().find('.video-listing-title').text();
                var link = '<a class="inline-block fancybox" '
                    + 'title="'  + title +'" href="http://www.youtube.com/embed/'
                    + youTube + '?autoplay=1" />';
                $(this).parent().find('.video-listing-thumbnail img').wrap(link);
                $(this).parent().find('a.fancybox').append(overlay);
            } else {
                var youTube = $(this).text();
                var link = '<a class="inline-block fancybox" '
                         + 'title="CABA video" href="http://www.youtube.com/embed/'
                         + youTube + '?autoplay=1"><img '
                         + 'src="http://img.youtube.com/vi/' + youTube
                         + '/0.jpg" width="210" height="140"'
                         + '/><img class="play-overlay" '
                         + 'src="/images/buttons/play-small.png" '
                         + 'width="48px" height="34px" /></a>';
                $(this).html(link);
            }
        });

        $('.video-listing .featured .video-listing-thumbnail a').append(overlay);
        $('a.fancybox').fancybox({ type: 'iframe' });
    };
    /**
     * Setup form behaviour for contact section
     */
    var initForms = function() {
        $('input[name=dob], input[name=startDate]').datepicker({ 
            dateFormat: 'dd/mm/yy',
            changeYear: true,
            yearRange: '-110:+0'
        });
        
        $('dt#giftaid-label').html('<img src="/images/branding/giftaid.jpg" width="185px" height="100px" alt="gift aid logo" />');

        // list of optional elements and groups
        var groups = {  
                name : ['newTitle','newForename','newSurname'],
                address : [
                    'newCompanyName','address1','address2','address3',
                    'newTown','newCounty','newPostcode','newCountry'
                ],
                email : ['newEmail'],
                telephone : ['newTelephone','newMobile','newFax'],
                contact : [ 'preferredContact', 'communicationOptOut' ]
        };

        // initially hide all optional elements and labels
        for (prop in groups) {
            if (!$('#updateType-' + prop).is(':checked')) {
                for (var i = 0; i < groups[prop].length; i++) {
                    $('#tab-content-update #' + groups[prop][i] + '-label').hide();
                    $('#tab-content-update #' + groups[prop][i] + '-element').hide();
                }
            }
        }
        // on checkbox tick then show optional group elements
        $('input[type=checkbox]').change(function(){
            if ($(this).is(':checked')) {
                for (var i = 0; i < groups[$(this).val()].length; i++) {
                    $('#tab-content-update #' + groups[$(this).val()][i] + '-label').show();
                    $('#tab-content-update #' + groups[$(this).val()][i] + '-element').show();
                }
            } else {
                for (var i = 0; i < groups[$(this).val()].length; i++) {
                    $('#tab-content-update #' + groups[$(this).val()][i] + '-label').hide();
                    $('#tab-content-update #' + groups[$(this).val()][i] + '-element').hide();
                }
            }
        });
        
        var icaewLabel = $('#tab-content-spouse dt#icaew-label').detach();
        var icaewElement = $('#tab-content-spouse dd#icaew-element').detach();
        var partnerLabel = $('#tab-content-spouse dt#partnerName-label').detach();
        var partnerElement = $('#tab-content-spouse dd#partnerName-element').detach();
        
        $('#tab-content-spouse dl.zend_form').prepend("<div id='spouseMemberDetails'></div>");
        $('#spouseMemberDetails').append(partnerLabel).append(partnerElement).append(icaewLabel).append(icaewElement).append('<dt><h3>Spouse or life partner details:</h3></dt>');
        $('.donation label.required').each(function(){
            $(this).html($(this).text()+'<span class="required">*</span>');
        });
    };
    var initFaq = function() {
        $('.answer').hide();
        $('h3.question').click(function(){
            if ($(this).next('.answer').is(':hidden')) {
                $(this).addClass('open');
                $(this).next('.answer').slideDown('fast');
            } else {
                $(this).removeClass('open');
                $(this).next('.answer').slideUp('fast');
            }
        });
    };
    return {
        initHome: function() {
            defaultSearch();
            initMenu();
            initGallery();
            initFeatureBoxes();
            initTabs();
            addSelectedMenuItem();
        },
        initSubsection: function() {
            defaultSearch();
            initMenu();
            addSelectedMenuItem();
            replacePullQuotes();
            addRhsButtons();
            addOddEven();
            miscReplacements();
            initGallery();
            initFaq();
            initForms();
        },
        initSubsectionPage: function() {
            defaultSearch();
            initMenu();
            addSelectedMenuItem();
            replacePullQuotes();
            addOddEven();
            addRhsButtons();
            miscReplacements();
        },
        initContact: function() {
            defaultSearch();
            initMenu();
            addSelectedMenuItem();
            addRhsButtons();
            initTabs();
            initForms();
        },
        initEvent: function() {
            eventReplacements();
        }
    };
}();

// sitewide initialisation
$(document).ready(function(){
    if ($('#custom-doc').hasClass('home')) {
        Caba.initHome();
    }
    if ($('#custom-doc').hasClass('subsection')) {
        Caba.initSubsection();
    }
    if ($('#custom-doc').hasClass('resources')) {
        Caba.initSubsection();
    }
    if ($('#custom-doc').hasClass('subsection-page')) {
        Caba.initSubsectionPage();
    }
    if ($('#custom-doc').hasClass('video-listing')) {
        Caba.initSubsection();
    }
    if ($('#custom-doc').hasClass('edit-member')) {
        Caba.initContact();
    }
    if ($('body').hasClass('subsection')) {
        Caba.initSubsection();
    }
    if ($('#custom-doc').hasClass('events')) {
        Caba.initEvent();
    }
});

