// From: http://css-tricks.com/snippets/jquery/smooth-scrolling/
var $ = require('jquery');
var debounce = require('../debounce.js');

module.exports = function() {
    $(document).on('click', 'a', function(e) {
        if (this.hash.length > 0 && location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target, hash = this.hash;

            try {
                target = $(hash);
            } catch (e) {
            }

            if (!target || !target.length) {
                target = $('[name=' + hash.slice(1) + ']');
            }

            if (!!target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top
                }, function() {
                    location.href = hash;
                });

                e.preventDefault();
            }
        }
    });

    $(function() {
        var $window = $(window);

        var header = $('.header');
        var subnav = $('.subnav');
        var toplink = $('.toplink');

        var threshold;

        var visibleAdded = false;

        function calc() {
            threshold = header.innerHeight();

            if (subnav.length) {
                threshold += subnav.innerHeight();
            }
        }

        function scroll() {
            var scrollTop = $window.scrollTop();

            if (scrollTop > threshold) {
                !visibleAdded && toplink.addClass('toplink--visible');
                visibleAdded = true;
            } else {
                visibleAdded && toplink.removeClass('toplink--visible');
                visibleAdded = false;
            }
        }

        calc();
        scroll();

        $window.resize(debounce(function() {
            calc();
            scroll();
        }, 50));

        $window.scroll(scroll);
    });
};
