/**
 * Created by jballis on 18.03.15.
 */

jQuery(document).ready(function ($) {
    // browser window scroll (in pixels) after which the "back to top" link is shown
    var offset = 300,
        //browser window scroll (in pixels) after which the "back to top" link opacity is reduced
        offset_opacity = 1200,
        //duration of the top scrolling animation (in ms)
        scroll_top_duration = 600,
        //grab the "back to top" link
        $back_to_top = $('.back-to-top');

    //hide or show the "back to top" link
    $(window).scroll(function () {
        ($(this).scrollTop() > offset) ? $back_to_top.addClass('is-visible') : $back_to_top.removeClass('is-visible fade-out');
        if ($(this).scrollTop() > offset_opacity) {
            $back_to_top.addClass('fade-out');
        }
    });

    //smooth scroll to top
    $back_to_top.on('click', function (event) {
        event.preventDefault();
        $('body,html').animate({
                scrollTop: 0
            }, scroll_top_duration
        );
    });

});

$(document).ready(function () {
    inputScrollTop();
    initNavWithTransition();
});


function initNavWithTransition() {
    $('.nav-with-transition').each(function() {

        // When the page is initialized, set the position and width of the active underlining to the
        // current active link
        var $activeLink = $(this).find('a[data-toggle="tab"].active');
        var leftPos = $activeLink.position().left;
        var width = $activeLink.outerWidth();
        var $target = $(this).find('span.target');
        $target.css({
            'left': leftPos,
            'width': width
        });

        // Make sure all carousel items have the same height, based on the highest of all
        // This is necessary because Flickity has a bug when initializing hidden carousels
        var highest = 0;
        $('.carousel-cell').each(function() {
            if ($(this).outerHeight() > highest) {
                highest = $(this).outerHeight();
            }
        });
        $('.carousel-cell, .carousel-cell .card').css('height', highest);


        // Whenever a new tab item is selected, move the underline to its left pos and adapt its width
        $(this).find('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
             var leftPos = $(this).position().left;
             var width = $(this).outerWidth();
             var $target = $(this).parents('.nav-with-transition').find('span.target');
             $target.css({
                 'left': leftPos,
                 'width': width
             });
             $('.hetsl-carousel').flickity('resize');
         })
    });


    // Change hash for page-reload
    $('.nav-tabs a').on('click', function (e) {
        history.pushState(null, null, window.location.pathname + $(this).attr('href'));
    });
}

// When we click on input, the viewport place the input on the top
function inputScrollTop () {
    var $input = $('.inputTop');
    var $topPosition = $input.offset();

    $input.click(function () {
        $('html, body').animate({ scrollTop: $topPosition.top - 20 }, 200);
    });

}

// Change chevron position in Boostrap accordion
function toggleChevron (e) {
    $(e.target)
        .prev('.panel-heading')
        .find('span.indicator')
        .toggleClass('glyphicon-triangle-right glyphicon-triangle-bottom');
}

$('.bootstrap-accordion').on('hidden.bs.collapse', toggleChevron);
$('.bootstrap-accordion').on('shown.bs.collapse', toggleChevron);

$('.nav-main .collapse')
    .on('show.bs.collapse', function () {
        $('#header').toggleClass('open', true);
    })
    .on('hide.bs.collapse', function () {
        $('#header').toggleClass('open', false);
    });

/**
 * Add a sticky top behavior to an element, allowing it to be positioned statically when it reaches the top of the viewport
 *
 * @param element {String} A selector string for the element to add the sticky behavior to
 * @param content {String} A selector for the content that follows the sticky element
 * @param offset {String} A selector for an element that is stickily placed before
 */
function enableStickyBehavior (element, content, offset) {
    // Polyfill requestAnimationFrame for old browsers
    var raf = window.requestAnimationFrame
        || window.webkitRequestAnimationFrame
        || window.mozRequestAnimationFrame
        || function (cb) {
            setTimeout(cb, 1 / 60);
        };

    // Get jQuery references to header and start of page content
    var $header = $(element),
        $page = $(content),
        $offset = $(offset);

        var headerOffset = 0,
            sticky = false,
            animationTicking = false,
            latestKnownScrollY = 0,
            initialPadding = parseInt($page.css('padding-top'));

        document.addEventListener('scroll', onScroll, false);

        // Trigger once for page load (if anchor or previous clicked)
        onScroll();

        if ($offset.length) {
            // Listen for the end of CSS transition on offset element to replace the current one after it
            $offset.on('transitionend', function () {
                if (!sticky) return;

                $header.css('top', $offset.outerHeight())
            })
        }

    function onScroll () {
        if (!sticky && $header.length > 0)
            headerOffset = $header.offset().top - ($offset.length ? $offset.outerHeight() : 0);

        latestKnownScrollY = $(window).scrollTop();

        requestAnimationTick();
    }

    function requestAnimationTick () {
        if (!animationTicking)
            raf(update);

        animationTicking = true;
    }

    function update () {
        // reset for next onScroll capture
        animationTicking = false;

        if (!sticky && latestKnownScrollY > headerOffset)
            stick();

        else if (sticky && latestKnownScrollY <= headerOffset)
            unstick();
    }

    function stick () {
        sticky = true;

        if ($offset.length) {
            window.addEventListener('resize', handleWindowResize);
        }

        $header.css('top', $offset.outerHeight()).parent().addClass('sticky');
        $page.css('padding-top', ($header.height() + initialPadding) + 'px');
    }

    function unstick () {
        sticky = false;

        $header.css('top', '').parent().removeClass('sticky');
        $page.css('padding-top', '');
        window.removeEventListener('resize', handleWindowResize);
    }

    function handleWindowResize () {
        $header.css('top', $offset.outerHeight())
    }
}

enableStickyBehavior('.nav-main', '.header-border-wrapper', null);

if ($('.navbar-sub').length)
    enableStickyBehavior('.navbar-sub', '#content', '.nav-main');
