(function($) {


    /**
     * Scrolls page to static pixel offset
     * @param  {Number}
     */
    var scrollTo = function( offset ) {
        $('html, body').stop().animate({
            scrollTop: offset
            }, {
            duration: 1200,
            easing: "easeInOutExpo"
        });
    };

    /**
     * Scrolls to element passed in as object or DOM reference
     * @param  {String|Object}
     */
    var scrollToAnchor = function( hash ) {
        var $target = $( hash );
        // console.log( hash );

        if( ! $target.length ) return;

        var offset  = $target.offset().top;
        var headerH = $('#mk-header').data('sticky-height');
        offset = offset - headerH;

        if( hash === '#top-of-page' ) window.history.replaceState( undefined, undefined, ' ' );
        else window.history.replaceState( undefined, undefined, hash );

        scrollTo( offset );
    };

    /**
     * This should be invoked only on page load. 
     * Scrolls to anchor from  address bar
     */
    var scrollToURLHash = function() {
        var loc = window.location,
            hash = loc.hash;

        if ( hash.length && hash.substring(1).length ) {
            // !loading is added early after DOM is ready to prevent native jump to anchor
            hash = hash.replace( '!loading', '' );

            // Wait for one second before animating 
            // Most of UI animations should be done by then and async operations complited
            setTimeout( function() {
                scrollToAnchor( hash );
            }, 1000 ); 

            // Right after reset back address bar
            setTimeout( function() {
                window.history.replaceState(undefined, undefined, hash);
            }, 1001);
        }
    };

    $( window ).on( 'load', scrollToURLHash);

}(jQuery));