/* globals $: false, document: false, window: false */

'use strict'; // jshint ignore: line

$(document).ready(function() {
    if (document.location && document.location.hash && window.pageYOffset && window.innerHeight)
        window.setTimeout(function() {
            const elem = $(document.location.hash);
            if (elem && elem.length > 0) elem[0].scrollIntoViewIfNeeded();
            window.setTimeout(function() {
                window.scrollTo(window.pageXOffset, window.pageYOffset - window.innerHeight * 0.5);
            }, 500);
        }, 500);
});

@@ -122,104 +122,370 @@
 ) %7B%0A
+%0A
     
-if (document.location && document.location.hash && window.pageY
+var scrolled = 0;%0A%0A    var scrollTo = function(selector) %7B%0A        var elem = $(selector);%0A        if (elem) %7B%0A            var elemOffset = elem%5B0%5D.offsetTop;%0A            var elemHeight = elem.outerHeight(true);%0A            var windowHeight = $(window).height();%0A            window.scrollTo(window.pageXOffset, elem
 Offset 
-&& 
+- (
 window
-.inner
+Height - elem
 Height)
+ / 2);
 %0A   
@@ -489,33 +489,46 @@
         
+%7D%0A    %7D;%0A%0A    $(
 window
+)
 .s
-etTimeout
+croll
 (functio
@@ -545,131 +545,282 @@
     
-    const elem = $(document.location.hash);%0A            if (elem && elem.length %3E 0) elem%5B0%5D.scrollIntoViewIfNeeded();%0A    
+scrolled++;%0A    %7D);%0A%0A    $('a%5Bhref%5E=%22#%22%5D').click(function(e) %7B%0A        e.stopImmediatePropagation();%0A        e.preventDefault();%0A        document.location.hash = e.target.hash;%0A        scrollTo(e.target.hash);%0A    %7D);%0A%0A    if (document.location && document.location.hash) %7B%0A
     
@@ -870,114 +870,176 @@
     
-    
+$(
 window
-.scrollTo(window.pageXOffset, window.pageYOffset - window.innerHeight * 0.5);%0A            %7D, 500
+).off('scroll');%0A            if (scrolled %3C 3)    // Merely loading a page may trigger one or two scroll events.%0A                scrollTo(document.location.hash
 );%0A 
@@ -1054,12 +1054,19 @@
 , 500);%0A
+    %7D%0A%0A
 %7D);%0A

Fix #538