/**
 * Custom Javascript - Specifically one-off and non-global functions
 */

var isTouchDevice = ('ontouchstart' in window || 'onmsgesturechange' in window);

$(document).ready(function() {
    if( $('.slider-tabs').length ){
        initTabSlider();
    }
    if( $('.modal-target').length ){
        initImageModal();
    }
    if( $('.tabbed-content-ui').length ){
        initTabbedContentUI(true)
    }

    if( $('section#timeline').length ){
        initAnniversaryTimeline();
    }

    if( $('#new-ad-portfolio').length ){
        initNewAdPortfolio();
    }

    if( $('.headshot-tiles').length ){
        initHeadshotTiles();
    }

    if( $('.faq-wrapper').length ){
        initFAQAccordion();
    }

    if( $('body.page-template-page-creative-showcase-cross-platform').length ){
        initCrossPlatformCreativeShowcase();
    } else if( $('#creative-showcase').length ){
        initCreativeShowcase();
    } else if( $('#filterable-grid').length ){
        initCreativeShowcase();
    }

    if( $('body').hasClass('page-template-page-single-page-event-template') ){
        initSinglePageEventTemplate();
    }

    if( $('#recertification').length ){
        //initRecertification();
        $('.event-month-wrapper').each(function(){
            var numActive = $(this).find('.article-list__row.certificate-active').length;
            if(numActive<1){
                $(this).hide();
            }
        });
    }

    if( $('body').hasClass('category-learning') ){
        $('.has-sublinks .arrow-wrapper').click(function(){
            var li = $(this).parent();
            li.toggleClass('closed').toggleClass('open');
            $('.' + li.attr('id')).slideToggle();
        });
    }

    if( $('body').hasClass('category-certification') || $('body').hasClass('iab-digital-media-sales-certification-overview') || $('body').hasClass('iab-ad-ops-certification-overview') || $('body').hasClass('iab-data-solutions-certification-overview') ){
        //initModalAlert( 'Temporary Registration Issues', 'We are currently having an issue with our registration system. If you are having a problem resetting your password reach out to <a href="mailto:certification@iab.com" target="_blank">certification@iab.com</a>. <br />We apologize for any inconvenience.' );
    }

    if( $('body').hasClass('category-learning') || $('body').hasClass('about-iab-digital-leadership-program') || $('body').hasClass('advprogrammatic') ){
        //initModalAlert( 'Temporary Registration Issues', 'We are currently having an issue with our registration system.  To register for a class please email us at <a href="mailto:learning@iab.com" target="_blank">learning@iab.com</a>.  <br />We apologize for any inconvenience' );
    }
});

function trace(msg){
    if(console){
        console.log(msg);
    }
}

function addZero(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

function formatAMPM(hours) {
    return hours >= 12 ? 'PM' : 'AM';
}

//
// initTabSlider - configures a tab-like user interface with a sliding indicator; the html must match a specific template
//
function initTabSlider(){

    $(".slider-tabs>ul li a").click(function(event) {
        event.preventDefault();
        $(this).parent().addClass("current");
        $(this).parent().siblings().removeClass("current");
        var tab = $(this).attr("href");
        var tabNumber = tab.replace("#", "").replace("tab-", "");
        $(".slider-tabs>div>div").not(tab).css("display", "none");
        $(tab).fadeIn();

        $('.slider-arrow').animate({
            width: $(this).parent().width(),
            left: $(this).parent().position().left
        }, 1000, function() {
            // Animation complete.
        });

        history.replaceState(undefined, undefined, '#' + tabNumber);
        //$('.slider-arrow').css('width', $(this).parent().width()).css('left', $(this).parent().position().left);
    });
    function selectTab( id ){
        var newID = id.replace('#','').replace('tab-','');
        var link = $('a[href="#tab-' + newID + '"]');
        $(link).click();
    }
    $('.slider-select').change(function(){
        selectTab( $(this).val() );
    });
    if(document.location.hash){
        var hashNumber = document.location.hash.replace('#','');
        selectTab( '#tab-' + hashNumber );
        setTimeout(function(){
            window.scrollTo(0,0);
        }, 1);
    } else {
        $(".slider-tabs>ul li:first-child a").click();
    }

}

//
// initImageModal - add a click event on any image with modal-target class, when clicked the image shows full screen over a shaded layer
//
function initImageModal(){
    // I was just using this when the cache on the site was enabled during testing - these css rules are already in custom_styles.css
    //var style = $('<style>div#modal-bg { display:none;cursor:pointer;position: fixed;width:100%;height: 100%;top:0;left: 0;background: rgba(0,0,0,.5);z-index: 999998;min-height: 1000px;}.modal-target{cursor:pointer;}.modal-big{display:none;position:fixed;width:100%;height:100%;top:0;left: 0;z-index: 999999;text-align:center;}.modal-big img {max-width:90%;margin:20px auto 0;}</style>');
    //$('html > head').append(style);

    $('body').append('<div id="modal-bg"></div>');

    var i = 1;
    var i = 1;
    $('.modal-target').each(function(){
        $(this).addClass('modal-small-' + i).data('count', i);
        var src = $(this).attr('src');
        $('body').append('<div class="modal-big modal-big-' + i + '"><img src="' + src + '" /></div>');
        $(this).click(function(){
            var count = $(this).data('count');
            //trace( 'clicked target - showing [' + count + ']' );
            $('#modal-bg').fadeIn();
            $('.modal-big-' + count).fadeIn();
        });
        i++;
    });

    $('#modal-bg,.modal-big').click(function(){
        $('.modal-big').fadeOut();
        $('#modal-bg').fadeOut();
    });
}

//
//
//
function initModalAlert( title, content ){
    $('body').append('<div id="modal-alert"><h4>' + title + '</h4><p>' + content + '</p><div id="close-alert">Close</div></div>');
    $('body').append('<div id="modal-bg"></div>');
    $('#modal-bg,#close-alert').click(function(){
        $('#modal-alert').fadeOut();
        $('#modal-bg').fadeOut();
    });
    $('#modal-bg,#modal-alert').fadeIn();
}

//
//
//
function initTabbedContentUI( slider ){
    var listItems = $('.tabbed-content-ui>ul>li');
    var contentDivs = $('.tabbed-content-ui>.content>div');

    listItems.each(function(){
        function activateEvent( target ){
            var number = $( ".tabbed-content-ui>ul>li" ).index( target );
            if( $(window).width() < 761 ){
                window.location = contentDivs.eq( number).find('a').attr('href');
            } else {
                if( !contentDivs.eq( number).is(':visible') ){
                    selectTab( number );
                }
            }
        }
        $(this).mouseover(function(){
            activateEvent( this );
        });
        $(this).click(function(){
            //activateEvent( this );
            var number = $( ".tabbed-content-ui>ul>li" ).index( this );
            window.location = contentDivs.eq( number).find('a').attr('href');
        });
    });

    // properly init (since its already showing, can't just selectTab()
    var first = listItems.eq(0);
    $('.slider').animate({
        left: (first.position().left + first.width()/2 - 30)
    }, 200, function(){});

    function selectTab( number ) {
        contentDivs.fadeOut(500);
        contentDivs.eq(number).fadeIn(500);

        var li = listItems.eq(number);
        $('.slider').animate({
            left: (li.position().left + li.width() / 2 - 30)
        }, 500, function () {
        });
        var id = li.find('img').attr('id');
        $('.content').removeClass().addClass('content').addClass(id);
        $('.slider').removeClass().addClass('slider').addClass(id);
    }
}


jQuery(document).ready(function($){

    /*filter certificate events*/

   // $(".filtercertificate #true").on("click", function(e){
    $(document).on('click', '.filtercertificate #true', function(e){

        if(this.checked) {
            $(this).attr('checked','checked');
            $('.certificate-disable').fadeOut();
            /*$('.event-month-wrapper').each(function(){
                var numActive = $(this).find('.article-list__row.certificate-active').length;
                if(numActive<1){
                    $(this).fadeOut();
                }
            });*/
            //alert("Checkbox is checked.");
        } else {
            $(this).removeAttr('checked');
            $('.certificate-disable').fadeIn();
            /*$('.event-month-wrapper').fadeIn();*/
           // alert("Checkbox is unchecked.");
        }
    });


    var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : sParameterName[1];
            }
        }
    };

    var tech = getUrlParameter('pryear');
    //trace(tech);

    if(tech !=null) { // year is in url with get
        $( ".blocktext a" ).each(function() {
            var $aval = $( this ).html();
            if($aval == tech){ // if is  parrameter
                $(this).addClass('active');
            }
        });
    }else{ // is not in url with get

        var href = location.href.split('/');
        var $year_string = href[href.length - 2 ].match(/\d+/);
        //console.log("not in url" +  $year_string);

        $( ".blocktext a" ).each(function() {
            var $aval = $( this ).html();
            if($aval == $year_string){ // if is  parrameter
                $(this).addClass('active');
            }
        });

    }

});

//
// initAnniversaryTimeline - anniversary timeline
//
function initAnniversaryTimeline(){
    $('.flik-timeline').flikScrollEffect();

    $('section#timeline,section#timeline div#flik-timeline-overscroll').addClass('loaded');

    // set variable for use in a couple places below
    var firstItemLeftEdgeStartingPosition = parseFloat($('.flik-timeline-item:first').offset().left);
    //trace('firstItemLeftEdgeStartingPosition is [' + firstItemLeftEdgeStartingPosition + ']' );

    // set up click events
    var leftArrow = $('.left-arrow-wrapper');
    leftArrow.click(function(){
        //trace( 'click left' );
        slide('left');
    });
    leftArrow.mouseenter(function(){
        //trace( 'mouseover left' );
        slide('left');
        if(!isMobile()){
            leftTimer = setInterval(function(){
                slide('left');
            }, 400);
        }
    });
    leftArrow.mouseleave(function(){
        //trace( 'mouseout left' );
        clearInterval(leftTimer);
        //slide('left','easeOutCubic', 400);
    });

    var rightArrow = $('.right-arrow-wrapper');
    rightArrow.click(function(){
        //trace( 'click right' );
        slide('right');
    });
    rightArrow.mouseenter(function(){
        //trace( 'mouseover right' );
        slide('right');
        if(!isMobile()){
            rightTimer = setInterval(function(){
                slide('right');
            }, 400);
        }
    });
    rightArrow.mouseleave(function(){
        //trace( 'mouseout right' );
        clearInterval(rightTimer);
        //slide('right','easeOutCubic', 400);
    });

    //run some functions when the div scrolls - make sure we haven't reached the edge and update the year nav
    $('div#flik-timeline-overscroll').scroll(function() {
        hasEdgeBeenReached( 'left' );
        hasEdgeBeenReached( 'right' );
        updateYear();
    });

    //jump to year
    $('.year-row span').each(function(){
        $(this).click(function(){
            $('.selected').removeClass('selected');
            $(this).addClass('selected');
            jumpToYear($(this).data('year'));
        });
    });

    function isMobile(){
        return ($(window).width() < 500);
    }
    function hasEdgeBeenReached( edge, increment ){
        var firstItemLeftEdge = parseFloat($('.flik-timeline-item:first').offset().left);
        var lastItemRightEdge = parseFloat($('.flik-timeline-item:last').offset().left) + parseFloat($('.flik-timeline-item:last').width());
        var rightEdgeOfWindow = ( $('#flik-timeline-overscroll').width() + $('#flik-timeline-overscroll').offset().left )
        //trace( 'in hasEdgeBeenReached: firstItemLeftEdge = [' + firstItemLeftEdge + '] and lastItemRightEdge = ['+lastItemRightEdge+'] and firstItemLeftEdgeStartingPosition =['+firstItemLeftEdgeStartingPosition+'] and rightEdgeOfWindow = ['+rightEdgeOfWindow+']' );
        if( edge == 'left' ){
            if( firstItemLeftEdge > firstItemLeftEdgeStartingPosition ){
                //trace('left edge has been reached, stop scrolling: firstItemLeftEdge = [' + firstItemLeftEdge + ']');
                navigationArrows('left',true);
                return true;
            } else {
                //trace('left edge not reached, keep scrolling = [' + firstItemLeftEdge + '] and lastItemRightEdge = [' + lastItemRightEdge + ']');
                navigationArrows('left',false);
                return false;
            }
        } else {
            if( lastItemRightEdge < rightEdgeOfWindow ){
                //trace('right edge has been reached, stop scrolling');
                navigationArrows('right',true);
                return true;
            } else {
                //trace('right edge not reached, keep scrolling');
                navigationArrows('right',false);
                return false;
            }
        }
    }
    function navigationArrows(direction,endReached){
        if(direction == 'left'){
            if(endReached){
                if($('.left-arrow-wrapper.arrow-wrapper').hasClass('visible')){
                    $('.left-arrow-wrapper.arrow-wrapper').fadeOut( null, function() {
                        $(this).removeClass('visible');
                    });
                }
                if(!$('.right-arrow-wrapper.arrow-wrapper').hasClass('visible')){
                    $('.right-arrow-wrapper.arrow-wrapper').fadeIn( null, function() {
                        $(this).addClass('visible');
                    });
                }
            } else {
                if(!$('.left-arrow-wrapper.arrow-wrapper').hasClass('visible')){
                    $('.left-arrow-wrapper.arrow-wrapper').fadeIn( null, function() {
                        $(this).addClass('visible');
                    });
                }
                if(!$('.right-arrow-wrapper.arrow-wrapper').hasClass('visible')){
                    $('.right-arrow-wrapper.arrow-wrapper').fadeIn( null, function() {
                        $(this).addClass('visible');
                    });
                }
            }
        } else {
            if(endReached){
                if(!$('.left-arrow-wrapper.arrow-wrapper').hasClass('visible')){
                    $('.left-arrow-wrapper.arrow-wrapper').fadeIn( null, function() {
                        $(this).addClass('visible');
                    });
                }
                if($('.right-arrow-wrapper.arrow-wrapper').hasClass('visible')){
                    $('.right-arrow-wrapper.arrow-wrapper').fadeOut(null, function() {
                        $(this).removeClass('visible');
                    });
                }
            } else {
                if(!$('.left-arrow-wrapper.arrow-wrapper').hasClass('visible')){
                    $('.left-arrow-wrapper.arrow-wrapper').fadeIn( null, function() {
                        $(this).addClass('visible');
                    });
                }
                if(!$('.right-arrow-wrapper.arrow-wrapper').hasClass('visible')){
                    $('.right-arrow-wrapper.arrow-wrapper').fadeIn( null, function() {
                        $(this).addClass('visible');
                    });
                }
            }
        }
    }
    function jumpToYear(year){
        //trace('jump to year: [' + year + ']');

        var found = false;
        var isFirst = false;
        var isLast = false;
        $('.flik-timeline-item').each(function(){
            //trace('loop')
            if( $(this).data('date').indexOf(year) > -1 ){
                //trace('found');
                //$(this).addClass('found');
                var leftPosition = parseFloat($(this).position().left);
                if($(this).is(':first-child')){
                    isFirst = true;
                } else if($(this).is(':last-child')) {
                    isLast = true;
                }
                if(!isFirst){
                    leftPosition = leftPosition-90;
                }
                //trace('leftPosition is [' + leftPosition + ']');
                $('ul.flik-timeline.flik-timeline-7').animate({
                    left:(-1 * leftPosition)
                },{
                    easing: 'linear',
                    duration: 400,
                    speed: 'fast',
                    complete:function(){
                        //trace('done animating');
                        hasEdgeBeenReached('left');
                    }
                });
                found = true;
                return false;
            }
        });
        if(!found){
            $('.flik-timeline-item').each(function(){
                //trace('loop2')
                if( $(this).data('date').indexOf(year+1) > -1 ){
                    //trace('found');
                    $(this).addClass('found');
                    var leftPosition = parseFloat($(this).position().left);
                    //trace('leftPosition is [' + leftPosition + ']');
                    if($(this).is(':first-child')){
                        isFirst = true;
                    } else if($(this).is(':last-child')) {
                        isLast = true;
                    }
                    if(!isFirst){
                        leftPosition = leftPosition-90;
                    }
                    $('ul.flik-timeline.flik-timeline-7').animate({
                        left:(-1 * leftPosition)
                    },{
                        easing: 'linear',
                        duration: 400,
                        speed: 'fast',
                        complete:function(){
                            //trace('done animating');
                            hasEdgeBeenReached('left');
                        }
                    });
                    found = true;
                    return false;
                }
            });
        }
        if(!found){
            $('.flik-timeline-item').each(function(){
                //trace('loop3')
                if( $(this).data('date').indexOf(year+2) > -1 ){
                    //trace('found');
                    $(this).addClass('found');
                    var leftPosition = parseFloat($(this).position().left);
                    //trace('leftPosition is [' + leftPosition + ']');
                    if($(this).is(':first-child')){
                        isFirst = true;
                    } else if($(this).is(':last-child')) {
                        isLast = true;
                    }
                    if(!isFirst){
                        leftPosition = leftPosition-90;
                    }
                    $('ul.flik-timeline.flik-timeline-7').animate({
                        left:(-1 * leftPosition)
                    },{
                        easing: 'linear',
                        duration: 400,
                        speed: 'fast',
                        complete:function(){
                            //trace('done animating');
                            hasEdgeBeenReached('left');
                        }
                    });
                    found = true;
                    return false;
                }
            });
        }
        if(isFirst){
            //trace('is first');
            navigationArrows('left',true);
        } else if(isLast) {
            //trace('is last');
            navigationArrows('right',true);
        }
    }
    function slide(direction, ease, duration, increment){
        if(!ease){
            ease = 'linear';
        }
        if(!duration){
            duration = 400;
        }
        if(!increment){
            increment = 150;
        }

        //trace( 'Slide - direction: [' + direction + '] - ease: [' + ease + '] - duration: [' + duration + '] - increment: [' + increment + ']' );

        if( !hasEdgeBeenReached(direction, increment)){

            var firstItemLeftEdge = parseFloat($('.flik-timeline-item:first').offset().left);
            var lastItemLeftEdge = parseFloat($('.flik-timeline-item:last').offset().left);
            var lastItemRightEdge = lastItemLeftEdge + parseFloat($('.flik-timeline-item:last').width());
            var rightEdgeOfWindow = ($('#flik-timeline-overscroll').width() + $('#flik-timeline-overscroll').offset().left);
            var leftEdgeOfWindow = $('#flik-timeline-overscroll').offset().left;
            if(!firstItemLeftEdge){
                firstItemLeftEdge = 0;
            }
            //trace('firstItemLeftEdge is [' + firstItemLeftEdge + '] and lastItemLeftEdge = ['+lastItemLeftEdge+'] and lastItemRightEdge = ['+lastItemRightEdge+']');
            $('ul.flik-timeline.flik-timeline-7').stop( true, true );
            if(direction == 'right'){
                if( (lastItemRightEdge - increment) < rightEdgeOfWindow ){
                    //trace('this will go too far right!');
                    increment = lastItemRightEdge - rightEdgeOfWindow;
                    clearInterval(rightTimer);
                }
                //trace('firstItemLeftEdge is [' + firstItemLeftEdge + '] and increment is [' + increment + ']');

                $('ul.flik-timeline.flik-timeline-7').animate({left:'-='+increment},{ easing: ease,duration: duration, speed: 'slow'});
            } else {
                if( firstItemLeftEdge + increment > leftEdgeOfWindow ){
                    increment = leftEdgeOfWindow - firstItemLeftEdge;
                    //trace('this will go too far left! new increment is [' + increment + ']');
                    $('ul.flik-timeline.flik-timeline-7').animate({left:0},{ easing: ease,duration: duration, speed: 'slow'});
                    clearInterval(leftTimer);
                } else {
                    $('ul.flik-timeline.flik-timeline-7').animate({left:'+='+increment},{ easing: ease,duration: duration, speed: 'slow'});

                }

                //trace('firstItemLeftEdge is [' + firstItemLeftEdge + '] and increment is [' + increment + ']');

            }
            updateYear();
        }
    }
    function updateYear(){
        var timelineLeftEdge = $('#flik-timeline-overscroll').offset().left;
        var timelineWidth = $('ul.flik-timeline').innerWidth();
        var timelineCenter = timelineLeftEdge + (timelineWidth/2);
        //trace( 'timelineCenter is [' + timelineCenter + ']' );
        $('.flik-timeline-item').each(function(){
            //
            var itemLeft = $(this).offset().left;
            var itemWidth = $(this).width();
            var itemRight = itemLeft + itemWidth;
            if( ( timelineCenter > itemLeft ) && ( timelineCenter < itemRight ) ){
                //trace( 'found the center item! left is [' + itemLeft + '] and right is [' + itemRight + ']' );
                //$(this).css('border-top','5px solid yellow');
                var date = $(this).data('date');
                var year = date.replace(/\D/g,'');;
                //trace('year is [' + year + ']');
                $('.selected').removeClass('selected');
                $('.year-row span[data-year="' + year + '"]').addClass('selected');
            }
        });
    }
}

//
// initRecertification - recertification
//
function initRecertification(){

}

function showCityClasses( target ){
    //trace('now in showCityClasses, target is [' + target + ']')
    $('.class-location').hide();
    $('.class-location.' + target ).show();
}

//
// initNewAdPortfolioLEAN - initializing the New Ad Portfolio LEAN page,
//
function initNewAdPortfolioLEAN(){
    var thumbs = $('#gallery').slippry({
        slippryWrapper: '<div class="slippry_box thumbnails" />',
        transition: 'horizontal',
        pager: false,
        auto: false,
        captions: false,
        onSlideBefore: function (el, index_old, index_new) {
            $('.thumbs a img').removeClass('active');
            $('img', jQuery('.thumbs a')[index_new]).addClass('active');
        }
    });
    $('.thumbs a').unbind('click').click(function () {
        thumbs.goToSlide($(this).data('slide'));
        return false;
    });
}

//
// initNewAdPortfolio - initializing the New Ad Portfolio page, including a custom slider and other functionality
//
var center_slide = 1;
var counter = 1;
var slider_wrapper_width = $('.slider-wrapper').width();
var autoPlay;

function initNewAdPortfolio() {
    $('.subnav-close').click(function(){
        $('section#new-ad-portfolio-subnav').toggleClass('mobile-nav-open')
    });

    /* Device Slider */

    //var center_slide = 1;
    //var counter = 1;
    //var slider_wrapper_width = $('.slider-wrapper').width();
    //var autoPlay;

    $(window).resize(function(){
        slider_wrapper_width = $('.slider-wrapper').width();
        positionAd();
        if($(window).width() > 736 ){
            initSlider();
        }
    });

    function slide( direction ){
        var increment;
        if($(window).width() < 550 ){
            increment = slider_wrapper_width;
        } else {
            increment = slider_wrapper_width/2;
        }
        center_slide += 1;
        /*if(direction == 'previous'){
            var next_slide_img_position = $('.devices div[data-device="' + (center_slide - 1) + '"] img').position();
            var next_slide_img_width = $('.devices div[data-device="' + (center_slide - 1) + '"] img').width();
            $( ".devices" ).animate({
                left: "+=" + increment
            }, 400, function() {
                positionAd();
            });
            center_slide -= 1;

            $('.ad.current').removeClass('current').fadeOut();
            $('.ad[data-device="' + (center_slide) + '"]').addClass('current').fadeIn();

            ads.animate({
                left:  next_slide_img_position.left,
                top: next_slide_img_position.top,
                width: next_slide_img_width
            }, 800, function() {});
        //} else if( direction == 'next' && (center_slide != $('.devices div.device').length)) {
        } else {*/

        var next_slide = $('.devices div[data-device="' + center_slide + '"] img');
        var next_slide_img_position = next_slide.position();
        var next_slide_img_width = next_slide.width();
        $( ".devices" ).animate({
            left: "-=" + increment
        }, 400, function() {
            positionAd();
            //trace('counter is [' + counter + ']');
            if(counter > 1){
                $('.devices .device:last').after($('.devices .device').eq(center_slide-2).clone());
                $('.devices .device:last').attr('data-device', counter+3);
                $('.ads .ad:last').after($('.ads .ad').eq(center_slide-2).clone());
                $('.ads .ad:last').attr('data-device', counter+3);
            }
        });
        counter++;

        $('.ad.current').removeClass('current').animate({ opacity: 0 }, 300, function() {});
        $('.ad[data-device="' + (center_slide) + '"]').addClass('current').animate({ opacity: 1 }, 300, function() {});

        var ads = $('.ads');
        ads.animate({
            left:  next_slide_img_position.left,
            top: next_slide_img_position.top,
            width: next_slide_img_width
        }, 800, function() {});

        //trace('center_slide is [' + center_slide + ']');
        //trace('ad.current.index is [' + $('.ad.current').index() + ']');

        /*} else {
            center_slide = 1;
            var next_slide_img_position = $('.devices div[data-device="' + (center_slide) + '"] img').position();
            var next_slide_img_width = $('.devices div[data-device="' + (center_slide) + '"] img').width();
            $( ".devices" ).animate({
                left: 0
            }, 400, function() {
                positionAd();
            });

            $('.ad.current').removeClass('current').fadeOut();
            $('.ad[data-device="' + (center_slide) + '"]').addClass('current').fadeIn();

            ads.animate({
                left:  next_slide_img_position.left,
                top: next_slide_img_position.top,
                width: next_slide_img_width
            }, 800, function() {});
        }*/

        $('.devices .center').removeClass('center');
        $('.devices div[data-device="' + (center_slide) + '"]').addClass('center');

    }

    function positionAd(){
        var img_position = $('.devices div.center img').position();
        var img_width = $('.devices div.center img').width();
        $( ".ads" ).stop(true,false).animate({
            width: img_width,
            left: img_position.left,
            top: img_position.top
        }, 200, function() {});
    }

    function updateSlideInfo(){
        $('.devices').removeClass('center');
        $('.devices div[data-device="' + (center_slide) + '"]').addClass('center');
    }

    function initSlider(){
        if($(window).width() < 550 ){
            $('.devices>div').width( slider_wrapper_width );
        } else {
            $('.devices>div').width( slider_wrapper_width/2 );
        }
        var img_position = $('.devices div.center img').position();
        var img_width = $('.devices div.center img').width();
        if (img_position) {
            $('.ads').stop().css({
                "width": img_width,
                "left": img_position.left,
                "top": img_position.top
            });
        }
        clearInterval(autoPlay);
        autoPlay = setInterval(function(){ slide('next') }, 2400);
    }

    function stopAutoPlay() {
        clearInterval(autoPlay);
    }

    if($(window).width() > 736 ) {
        initSlider();
    }

    /* Galleries */

    function initRatioGallery( startNum ){
        console.log('in initRatioGallery - startNum is [' + startNum + ']');
        if(!startNum){
            startNum = 1;
        }
        $('.ratio-gallery-wrapper,.backdrop').fadeIn();
        var ratio_thumbs = $('#ratio-gallery').slippry({
            slippryWrapper: '<div class="slippry_box thumbnails" />',
            transition: 'horizontal',
            pager: false,
            auto: false,
            captions: false,
            start: startNum,
            onSlideBefore: function (el, index_old, index_new) {
                $('.ratio-gallery-wrapper .thumbs a img').removeClass('active');
                $('img', $('.ratio-gallery-wrapper .thumbs a')[index_new]).addClass('active');
            }
        });
        $('.ratio-gallery-wrapper .thumbs a').unbind('click').click(function () {
            ratio_thumbs.goToSlide($(this).data('slide'));
            return false;
        });
    }

    function initLEANGallery( startNum ){
        if(!startNum){
            startNum = 1;
        }
        $('.lean-gallery-wrapper,.backdrop').fadeIn();
        var lean_thumbs = $('#lean-gallery').slippry({
            slippryWrapper: '<div class="slippry_box thumbnails" />',
            transition: 'horizontal',
            pager: false,
            auto: false,
            captions: false,
            start: startNum,
            onSlideBefore: function (el, index_old, index_new) {
                $('.lean-gallery-wrapper .thumbs li a').removeClass('active');
                $('.lean-gallery-wrapper .thumbs li').eq(index_new).find('a').addClass('active');
            }
        });
        $('.lean-gallery-wrapper .thumbs a').unbind('click').click(function () {
            lean_thumbs.goToSlide($(this).data('slide'));
            return false;
        });
    }

    function initNewMediaGallery( startNum ){
        if(!startNum){
            startNum = 1;
        }
        $('.newmedia-gallery-wrapper,.backdrop').fadeIn();
        var newmedia_thumbs = $('#newmedia-gallery').slippry({
            slippryWrapper: '<div class="slippry_box thumbnails" />',
            transition: 'horizontal',
            pager: false,
            auto: false,
            captions: false,
            start: startNum,
            onSlideBefore: function (el, index_old, index_new) {
                $('.newmedia-gallery-wrapper .thumbs a img').removeClass('active');
                $('img', $('.newmedia-gallery-wrapper .thumbs a')[index_new]).addClass('active');
            }
        });
        $('.newmedia-gallery-wrapper .thumbs a').unbind('click').click(function () {
            newmedia_thumbs.goToSlide($(this).data('slide'));
            return false;
        });
    }

        //set click event for initializing galleries
    $('.ratio-gallery-links span,.ratio-gallery-link').click(function(){
        initRatioGallery( $(this).data('slide') );
    });
    $('.lean-gallery-link').click(function(){
      console.log('test');
        initLEANGallery();
    });
    $('.newmedia-gallery-link').click(function(){
        initNewMediaGallery();
    });
    if( document.URL.indexOf('show=newmediagallery') > -1 ){
        initNewMediaGallery();
    } else if( document.URL.indexOf('show=leangallery') > -1 ){
        initLEANGallery();
    } else if( document.URL.indexOf('show=ratiogallery') > -1 ){
        initRatioGallery();
    }

        //When to close overlays
    $('.backdrop,.overlay-close').click(function(){
        $('.overlay-wrapper,.backdrop').fadeOut();
    });
}

//
// initHeadshotTiles - initializing the user interface for Data Rockstars and Native Predictions (News) item
//
var currentHeadshot = null;

function initHeadshotTiles(){
    var maxNumberHeadshots = $('.tile.headshot').length;
    $('.tiles-wrapper .tile.headshot, .tiles-wrapper .tile.link.open_headshot').click(function(){
        $wrapper = $(this).closest('.tiles-wrapper');
        var id = $(this).data('id');
        currentHeadshot = id;
        $('.backdrop').fadeIn();
        $wrapper.find('.tile-dialog.dialog-' + id).fadeIn();
    });
    $('.backdrop,.dialog-close').click(function(){
        $('.tile-dialog').fadeOut();
        $('.backdrop').fadeOut();
        currentHeadshot = null;
    });
    if( document.URL.indexOf('winner=') > -1 ){
        var winnerName = getUrlParameter('winner');
        $('.tiles-wrapper .tile[data-shortname="' + winnerName + '"]').click();
    } else if( document.URL.indexOf('show=') > -1 ){
        var showTarget = getUrlParameter('show');
        $('.tiles-wrapper .tile[data-shortname="' + showTarget + '"]').click();
    }
    $('.dialog-prev').click(function(){
        $wrapper = $('.tile-dialog:visible').closest('.tiles-wrapper');
        var maxNumberHeadshots = $wrapper.find('.tile.headshot').length;
        if(currentHeadshot == 1){
            currentHeadshot = maxNumberHeadshots;
        } else {
            currentHeadshot--;
        }
        $('.tile-dialog').fadeOut();
        $wrapper.find('.tile[data-id="' + currentHeadshot + '"]').click();
    });
    $('.dialog-next').click(function(){
        $wrapper = $('.tile-dialog:visible').closest('.tiles-wrapper');
        var maxNumberHeadshots = $wrapper.find('.tile.headshot').length;
        if( currentHeadshot == maxNumberHeadshots ){
            currentHeadshot = 1;
        } else {
            currentHeadshot++;
        }
        $('.tile-dialog').fadeOut();
        $wrapper.find('.tile[data-id="' + currentHeadshot + '"]').click();
    });
}

//
// getUrlParameter - a subroutine to get a parameter's value from the URL
//
var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;
    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

//
// initFAQAccordion - Initializing the Q&A accordion
//
function initFAQAccordion(){
    $('.faq-question').click(function(){
        if( !$(this).hasClass('open') ){
            $('.faq-answer.open').slideUp();
            $('.open').removeClass('open');
            $(this).addClass('open').next('.faq-answer').slideDown().addClass('open');
        } else {
            $('.faq-answer.open').slideUp();
            $('.open').removeClass('open');
        }
    });
}

//
// initCreativeShowcase - initializing the Creative Lab page
//
function initCreativeShowcase(){
    $('.campaign-tile').click(function(){
        var count = $(this).data('count');
        if( $(this).data('clickevent') == 'overlay' || !$(this).data('clickevent')){
            $('.campaign-dialog[data-count="' + count + '"]').addClass('current').fadeIn();
            $('.backdrop').fadeIn();
            setCampaignSlideshowHeight();
        } else if( $(this).data('clickevent') == 'int_link' ){
            window.open($(this).data('url'));
        } else if( $(this).data('clickevent') == 'ext_link' ){
            window.open($(this).data('url'), '_blank');
        }
        if( typeof ga !== 'undefined' ) {
            if( $(this).find('.campaign-tile-title').length || $(this).data('url').length ){
                var title;
                if( $(this).find('.campaign-tile-title').length ){
                    title = $(this).find('.campaign-tile-title').text();
                } else {
                    title = $(this).data('url');
                }
                ga('send', 'event', document.title, 'click', title);
            }
        }
    });
    $('.backdrop,.close-dialog').click(function(){
        $('.campaign-dialog').removeClass('current').fadeOut();
        $('.backdrop').fadeOut();
    });
    $('.campaign-dialog-prev').click(function(){
        var curid = $('.campaign-dialog.current').data('count');
        var maxnum = $('.campaign-dialog').length;
        var nextid;
        if(curid == 1){
            nextid = maxnum;
        } else {
            nextid = curid-1;
        }
        $('.campaign-dialog.current').removeClass('current').fadeOut();
        $('.campaign-dialog[data-count="' + nextid + '"]').addClass('current').fadeIn();
    });
    $('.campaign-dialog-next').click(function(){
        var curid = $('.campaign-dialog.current').data('count');
        var maxnum = $('.campaign-dialog').length;
        var nextid;
        if(curid == maxnum){
            nextid = 1;
        } else {
            nextid = curid+1;
        }
        $('.campaign-dialog.current').removeClass('current').fadeOut();
        $('.campaign-dialog[data-count="' + nextid + '"]').addClass('current').fadeIn();
    });
    if( $('body').hasClass('page-template-page-inside-influence') ){
        $('.campaign-dialog .prev.campaign-dialog-prev,.campaign-dialog .next.campaign-dialog-next').css('top',$(window).height()*.3);
    }
    if( !isTouchDevice ){
        $('.filter-row .filter').hover(
            function() {
                $( this ).addClass( "open" );
                trace( 'desktop hover: add "open" now' );
            }, function() {
                $( this ).removeClass( "open" );
                trace( 'desktop hover: remove "open" now' );
            }
        );
    } else {
        $('.filter-row .filter').on('click', function(e) {
            if (e.target !== this){
                trace('mobile click hit child element, not toggling');
                return;
            }
            $(this).toggleClass('open');
            trace( 'mobile click: toggle "open" now' );
        });
    }

    if( $.urlParam('show') ){
        $( '.filter-row .filter ul li.' + $.urlParam('show') + ' ' ).not( '.category-title' ).addClass('selected');
        filterCampaigns( $.urlParam('show') );
    }

    $('.filter-row .filter ul li').click(function(){
        if( $(this).hasClass('selected') ){
            $(this).removeClass('selected');
        } else {
            $(this).siblings('li.selected').removeClass('selected');
            $(this).toggleClass('selected');
        }
        filterCampaigns( $(this).data('type') );
        trace( 'remove "open" now' );
        $('.filter-row .filter.open').removeClass('open');
    });

    $('.viewall').click(function(){
        filterCampaigns( 'clear' );
    });

    $('.slideshow-wrapper').each(function(){
        var el = $(this);
        var count = el.find('.slideshow').attr('id').replace('slideshow','');
        el.find('.slideshow-nav .button').click(function(){
            if( !$(this).hasClass('current') ){
                el.find('.button.current').removeClass('current');
                $(this).addClass('current');
                campaignSlideshow( $(this).index(), count);
            }
        });
    });

    if( $.urlParam('v') ){
        $('.campaign-tile[data-count="' + $.urlParam('v') + '"]').click();
    }

    if( $.urlParam('c') ){
        $('.filter.categories ul li[data-value="' + $.urlParam('c') + '"]').click();
    }

    var div, n,
        v = document.getElementsByClassName("youtube-player");
    for (n = 0; n < v.length; n++) {
        div = document.createElement("div");
        div.setAttribute("data-id", v[n].dataset.id);
        div.innerHTML = youtubeEmbedThumb(v[n].dataset.id);
        div.onclick = youtubeEmbedIframe;
        v[n].appendChild(div);
    }

    function youtubeEmbedThumb(id) {
        var thumb = '<img src="https://i.ytimg.com/vi/ID/hqdefault.jpg">',
            play = '<div class="play"></div>';
        return thumb.replace("ID", id) + play;
    }

    function youtubeEmbedIframe() {
        var iframe = document.createElement("iframe");
        var embed = "https://www.youtube.com/embed/ID?autoplay=0";
        iframe.setAttribute("src", embed.replace("ID", this.dataset.id));
        iframe.setAttribute("frameborder", "0");
        iframe.setAttribute("allowfullscreen", "1");
        this.parentNode.replaceChild(iframe, this);
    }

    function filterCampaigns( type ){
        var urlparam = '';

        if( type == 'clear' || $('.filter-row .filter ul li.selected').length < 1 ){

            $('.selected').removeClass('selected');
            $('.campaign-tile').each(function(){
                $(this).fadeIn();
            });

        } else {

            $('.campaign-tile').each(function(){
                $(this).fadeIn();
            });

            $('.filter-row .filter').each(function(){
                var thisType = $(this).data('type');
                var numberSelected = $(this).find('.selected').length;

                if( numberSelected < 1 ){
                    return true;
                }

                var type = $(this).data('type');

                var valuesArray = [];
                $('li[data-type="' + type + '"].selected').each(function(){
                    valuesArray.push( $(this).data('value').toString() );
                });

                $('.campaign-tile').each(function(){

                    var curValuesArray = $(this).attr('data-' + type).replace(' ','').split(',');

                    var pass = false;
                    for (var i = 0; i < curValuesArray.length; ++i) {
                        if( ($.inArray( curValuesArray[i], valuesArray) !== -1) || ( curValuesArray[i] == valuesArray ) ){
                            pass = true;
                        } else {
                            //trace('fail..');
                        }
                    }

                    if( pass ){
                        //$(this).fadeIn();
                    } else {
                        $(this).fadeOut();
                    }
                });

            });

            if( $('.campaign-tile:visible').length < 1 ){
                $('.no-results').fadeIn();
            } else {
                $('.no-results').fadeOut();
            }
        }
    }

    function campaignSlideshow( change, count ){
        var $wrapper = $('#slideshow' + count);
        var currentSlideNum = $wrapper.find('.current').index();
        var targetSlideNum = null;
        var totalSlideCount = $wrapper.find('li').length - 1;

        if( change == 'prev' ){
            if( currentSlideNum == 0 ){
                targetSlideNum = totalSlideCount;
            } else {
                targetSlideNum = currentSlideNum - 1;
            }
        } else if ( change == 'next' ){
            if( currentSlideNum == totalSlideCount ){
                targetSlideNum = 0;
            } else {
                targetSlideNum = currentSlideNum + 1;
            }
        } else {
            targetSlideNum = change;
        }

        $wrapper.find('li').eq(targetSlideNum).addClass('nextUp');
        $wrapper.find('li.current').fadeOut().removeClass('current');
        $wrapper.find('li.nextUp').fadeIn(null,function(){
            setCampaignSlideshowHeight();
            setTimeout(function(){
                setCampaignSlideshowHeight();
            }, 2000);
        }).addClass('current').removeClass('nextUp');
    }

    function setCampaignSlideshowHeight(){
        $('.slideshow:visible').each(function(){
            var count = $(this).attr('id').replace('slideshow','');
            var slideHeight = null;
            var $currentSlide = $('#slideshow' + count + ' li.current');

            if( $currentSlide.find('div.youtube-player').length ) {
                slideHeight = $currentSlide.find('div.youtube-player').outerHeight();
            } else if( $currentSlide.find('img').length ){
                slideHeight = $currentSlide.find('img').height();
            } else if( $currentSlide.find('iframe').length ) {
                slideHeight = $currentSlide.find('iframe').height();
            }

            if( slideHeight > 0 ){
                $('#slideshow' + count).height( slideHeight ).css('min-height',0);
            } else {
                $('#slideshow' + count).css('min-height','315px');
            }
        });
    }
}

//
// initCrossPlatformCreativeShowcase - initializing the Creative Lab Cross Platform page
//
function initCrossPlatformCreativeShowcase(){
        //init jquery ui tabs in each campaign dialog
    $('.campaign-tab-wrapper').each(function(){
        var curId = $(this).attr('id');
        $('#' + curId).tabs();
    });

        //init click event on campaign thumb
    $('.campaign-tile').click(function(){
        var count = $(this).data('count');
        $('.campaign-dialog[data-count="' + count + '"]').addClass('current').fadeIn(null,function(){
            $(this).height(  $(this).height( $(window).outerHeight()*.8 ) );
            $('html').addClass('fixed-scroll');
        });
        $('.backdrop').fadeIn();
        setCampaignSlideshowHeight();
    });

        //init click event to close dialog
    $('.backdrop,.close-dialog').click(function(){
        $('.campaign-dialog').fadeOut();
        $('.backdrop').fadeOut();
        $('html').removeClass('fixed-scroll');
    });

        //init slideshow and slideshow nav
    $('.slideshow-wrapper').each(function(){
        var el = $(this);
        var id = el.find('.slideshow').attr('id');
        el.find('.slideshow-nav .button').click(function(){
            if( !$(this).hasClass('current') ){
                el.find('.button.current').removeClass('current');
                $(this).addClass('current');
                campaignSlideshow( $(this).index(), id);
            }
        });
    });

        // set up youtube video player
    var div, n,
        v = document.getElementsByClassName("youtube-player");
    for (n = 0; n < v.length; n++) {
        div = document.createElement("div");
        div.setAttribute("data-id", v[n].dataset.id);
        div.innerHTML = youtubeEmbedThumb(v[n].dataset.id);
        div.onclick = youtubeEmbedIframe;
        v[n].appendChild(div);
    }

    function youtubeEmbedThumb(id) {
        var thumb = '<img src="https://i.ytimg.com/vi/ID/hqdefault.jpg">',
            play = '<div class="play"></div>';
        return thumb.replace("ID", id) + play;
    }

    function youtubeEmbedIframe() {
        var iframe = document.createElement("iframe");
        var embed = "https://www.youtube.com/embed/ID?autoplay=0";
        iframe.setAttribute("src", embed.replace("ID", this.dataset.id));
        iframe.setAttribute("frameborder", "0");
        iframe.setAttribute("allowfullscreen", "1");
        this.parentNode.replaceChild(iframe, this);
    }

    function campaignSlideshow( change, id ){
        var $wrapper = $('#' + id);
        var currentSlideNum = $wrapper.find('.current').index();
        var targetSlideNum = null;
        var totalSlideCount = $wrapper.find('.slide').length - 1;

        if( change == 'prev' ){
            if( currentSlideNum == 0 ){
                targetSlideNum = totalSlideCount;
            } else {
                targetSlideNum = currentSlideNum - 1;
            }
        } else if ( change == 'next' ){
            if( currentSlideNum == totalSlideCount ){
                targetSlideNum = 0;
            } else {
                targetSlideNum = currentSlideNum + 1;
            }
        } else {
            targetSlideNum = change;
        }

        $wrapper.find('.slide').eq(targetSlideNum).addClass('nextUp');
        $wrapper.find('.slide.current').fadeOut().removeClass('current');
        $wrapper.find('.slide.nextUp').fadeIn(null,function(){
            setCampaignSlideshowHeight();
            setTimeout(function(){
                setCampaignSlideshowHeight();
            }, 2000);
        }).addClass('current').removeClass('nextUp');
    }

    function setCampaignSlideshowHeight(){
        $('.slideshow:visible').each(function(){
            var id = $(this).attr('id');
            var slideHeight = null;
            var $currentSlide = $('#' + id + ' .slide.current');

            if( $currentSlide.find('div.youtube-player').length ) {
                slideHeight = $currentSlide.find('div.youtube-player').outerHeight();
            } else if( $currentSlide.find('img').length ){
                slideHeight = $currentSlide.find('img').height();
            } else if( $currentSlide.find('iframe').length ) {
                slideHeight = $currentSlide.find('iframe').height();
            }

            if( slideHeight > 0 ){
                $('#' + id).height( slideHeight ).css('min-height',0);
            } else {
                $('#' + id).css('min-height','315px');
            }
        });
    }
}

/**
 * Get a URL parameter
 * $.urlParam('member')
 */
$.urlParam = function(name){
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null){
        return null;
    }
    else{
        return results[1] || 0;
    }
};

//
// initSinglePageEventTemplate - initializing code for the single page event template
//
function initSinglePageEventTemplate(){
    var nav = $('.page-nav');
    var offset = $('.page-nav').offset().top;

    $(window).scroll(function() {
        if( $(this).scrollTop() > offset ) {
            nav.addClass('page-nav-stuck');
        } else {
            nav.removeClass('page-nav-stuck');
        }
    });

    $("a.nav-link").on('click', function(event) {
        if (this.hash !== "") {
            event.preventDefault();
            var hash = this.hash;
            if( hash.length ){
                $('html, body').animate({
                    scrollTop: $(hash).offset().top-200
                }, 800, function(){
                    window.location.hash = hash;
                });
            }
        }
    });

    $('.mobile-menu-btn').click(function(){
        $('.page-nav-wrapper').css('top', $('.page-nav').height() + $('.page-nav').position().top );
        $('.page-nav-wrapper').toggleClass('visible');
        $('.mobile-menu-btn').toggleClass('open');
    });

    $('.page-nav-wrapper a.nav-link').click(function(){
        $('.page-nav-wrapper').removeClass('visible');
    });

    $('.speaker').click(function(){
        var count = $(this).data('count');
        var $wrapper = $(this).closest('section');
        $wrapper.find('.speaker-' + count).fadeIn(null, function(){
            var $target = $('.speaker-' + count);
            var pageNavHeight = $('.page-nav').height() + $('.page-nav').position().top;
            $target.css({
                'top': pageNavHeight + 25,
                'height': $(window).height() - pageNavHeight - 30
            });
        });
    });
    $('.close-speaker-dialog').click(function(){
        $('.speaker-dialog').fadeOut();
    });
    $('.logo-dialog-link.has-dialog').click(function(){
        var count = $(this).data('count');
        $('.logo-' + count).fadeIn();
    });
    $('.close-logo-dialog').click(function(){
        $('.logo-dialog').fadeOut();
    });

    var wrapper = $('#slider');
    setHeight(wrapper);
    var slider = wrapper.unslider({
        autoplay: true,
        delay: 5000,
        nav: true,
        arrows: false,
        animation: 'fade',
        animateHeight: true
    });
    wrapper.height('initial');
    setTimeout(function(){ setHeight(wrapper); }, 3000);
    $('#slider ul li').show();

    function setHeight(target){
        var height = 150;
        target.find('li').each(function(){
            if( $(this).height() > height ){
                height = $(this).height();
            }
        });
        target.height( height );
    }

    /**
     * Ensure the first tab of an agenda always loads.
     */
    $('#agenda #tab__1').on('click touchend', function() {
      if (typeof $('#agenda #tab__1__content') != 'undefined') {
        $('#agenda #tab__1__content').addClass('active');
      }
    });
}

jQuery( document ).ready(function() {
    jQuery("#module-hero-module__footer-container-mobile-id").on("shown", function() {
        jQuery('.module-hero-module__footer-header-action-mobile i')
            .removeClass()
            .addClass('bold iabicon-arrow-in-circle-up');
    });

    jQuery("#module-hero-module__footer-container-mobile-id").on("hidden", function() {
        jQuery('.module-hero-module__footer-header-action-mobile i')
            .removeClass()
            .addClass('bold iabicon-arrow-in-circle-down');
    });
});
