1window.onload=function() {
2    document.body.addEventListener('click', editOnLink);
3    document.body.addEventListener('contextmenu', editOnLink);
4};
5function editOnLink(e) {
6    var a = e.target || e.srcElement;
7    if (a.tagName === 'A' && (a.classList.contains("wikilink1") || a.classList.contains("wikilink2") || a.classList.contains("breadcrumbs"))) {
8
9        // In case of multy-line link, simple getBoundingClientRect wouldn't work well,
10        // so we find the spot by adding another element with the same positioning as
11        // that ":after" button. Thus we know where the popover button is.
12        var v = document.createElement('span');
13        v.id = 'plugin__editonlink';
14        a.appendChild(v);
15        var xy = v.getBoundingClientRect(),
16            x = xy.right,
17            y = xy.top,                         // x,y = of the popover button center
18            xya = a.getBoundingClientRect(),    // the mouse click was related to <a>
19            dx = e.offsetX + xya.left - x,      // how far the click was from the button?
20            dy = e.offsetY + xya.top - y,
21            r = parseFloat(window.getComputedStyle(a, ':after')['height'])/2 + 1;
22        if ((dx*dx + dy*dy) < r*r) {
23            a.setAttribute('data-editonlink', a.href);      // maybe ctrl-click etc
24            a.href = (a.href.split('#'))[0];                // link href (without anchor hash)
25            if (a.href.indexOf('?') < 0) a.href += '?do=edit';// add EDIT to the link
26            else {
27                if (a.href.search(/\bdo=/) < 0) a.href += '&do=edit';
28                else a.href.replace(/\bdo=[^&]*/, 'do=edit');
29            }
30            v.remove();
31            a.addEventListener('mouseleave', editOnLinkOut);    // to restore the link back
32        }
33    }
34}
35function editOnLinkOut(e) {
36    var a = e.target || e.srcElement;
37    if (a.tagName !== 'A') return;
38    var d = a.getAttribute('data-editonlink');
39    if (d) {
40        a.href = d;
41        a.removeAttribute('data-editonlink');
42    }
43    a.removeEventListener('mouseleave');
44}
45