/*global jQuery, State, window*/
(function () {
    var $ = jQuery;
    var $nav = $('.upfronts-nav');

    function setupStickyFooter () {
        var $elem = $('.download');
        var $footer = $('.fox-footer');
        
        var updateStickyFooter = function () {
            var is_fixed = (window.pageYOffset + window.innerHeight) <= $footer.offset().top;
            $elem.toggleClass('fixed', is_fixed);
        };
        
        $(window).on('scroll', updateStickyFooter);
        $(window).on('resize', updateStickyFooter);
    }

    function setupTagFilter () {
        var $shows = $('.shows .show');
        var current_filter = window.current_filter = new State();
        
        // parse data attribute
        $shows.each(function () {
            var $show = $(this);
            $show.data('tags', $show.attr('data-tags').split(','));
        });

        var filterShows = function (filter) {
            if (filter === 'all') {
                $shows.addClass('active');
                return;
            }

            // toggle visibility based on whether the filter matches one of the show's tags
            $shows.each(function () {
                var $show = $(this);
                var tags = $show.data('tags');
                var is_active = tags.indexOf(filter) !== -1;
                
                $show.toggleClass('active', is_active);
            });
        };

        // update whenever the filter changes
        current_filter.watch(filterShows);

        // also update the nav state to match the filter
        current_filter.watch(function (filter) {
            $nav.find('li.active').removeClass('active');
            $nav.find('li[data-tag="' + filter + '"]').addClass('active');
        });
        
        var onHashUpdate = function () {
            var val = location.hash.replace('#', '');
            
            // no filter means show all
            if (val === '') { val = 'all'; }
            current_filter.set(val);
        };
        $(window).on('hashchange', onHashUpdate);
        
        // call once to start
        onHashUpdate();        
    }

    function setupNav () {
        // nav items with a tag should activate that tag rather than changing the page
        $nav.on('click', 'li[data-tag]', function (event) {
            event.preventDefault();
            
            var tag = $(this).attr('data-tag');
            location.hash = tag;
        });
    }
    
    // ----

    // only apply to home page
    if ($('body').hasClass('page-home')) {
        setupNav();
        setupTagFilter();
    }

    // only apply to schedule page
    if ($('body').hasClass('page-schedule')) {
        setupStickyFooter();
    }

    // pdf links always open in a new window/tab
    $('a.btn').attr('target', '_blank');
}());
