jQuery(function()
{
    'use strict';

    var page = jQuery(document);

    page.find('a[data-animation="smooth-scroll"]').on('click', function(e)
    {
        e.preventDefault();

        var hash = this.hash;
        var target = jQuery(hash);

        if (!target.length) {
            return;
        }

        jQuery('html, body').animate({ scrollTop: target.offset().top }, 'slow', function() {
            location.hash = hash;

            target.focus();

            if (!target.is(':focus')) {
                target
                    .attr('tabindex', '-1')
                    .focus();
            }
        });
    });

    var is_scrolled_into_view = function(elem)
    {
        var doc_view_top = jQuery(window).scrollTop();
        var doc_view_bottom = doc_view_top + jQuery(window).height();
        var elem_offset = 0;

        if (elem.data('offset') != undefined)
        {
            elem_offset = elem.data('offset');
        }

        var elem_top = jQuery(elem).offset().top;
        var elem_bottom = elem_top + jQuery(elem).height();

        if (elem_offset != 0)
        {
            if (doc_view_top - elem_top >= 0)
            {
                elem_top = jQuery(elem).offset().top + elem_offset;
            }
            else
            {
                elem_bottom = elem_top + jQuery(elem).height() - elem_offset;
            }
        }

        if ((elem_bottom <= doc_view_bottom) && (elem_top >= doc_view_top))
        {
            jQuery(elem).addClass('viewed');

            var anim_elems_left = jQuery('[data-animation="slide-in"]:not(.viewed)').length;
            if (anim_elems_left == 0)
            {
                jQuery(window).off('scroll');
            }
        }
    }

    jQuery(window).on('scroll', function(e)
    {
        page.find('[data-animation="slide-in"]').each(function(i, elem)
        {
            if (jQuery(elem).hasClass('viewed'))
            {
                return;
            }

            is_scrolled_into_view(jQuery(elem));
        });
    });

    jQuery(window).scroll();

});
