Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// See the talk page for information about this script and how to use it.

if (mw.config.get('wgNamespaceNumber') == 6 && mw.config.get('wgAction') == "edit" && /[&?]nfurbacklink=/.test(window.location.search)) {
    addOnloadHook(function () {
        var editform = document.editform;
        if (!editform) return;
        var textbox = editform.wpTextbox1;
        if (!textbox) return;

        var previewDiv = document.getElementById("wikiPreview");

        var backlink = decodeURIComponent(/[&?]nfurbacklink=([^&]*)/.exec(window.location.search)[1]);

        var nfur_tag = " *(:? *[Tt]emplate: *)?(([Nn]on-free ((fair )?use|media) r|[Ff]air use r|[Rr])ationale|[Aa]lbum cover fur)";
        nfur_tag = nfur_tag.replace(/ /g, "[_\\s]").replace(/\(/g, "(?:");

        // bonus feature: automatically change "ResolutionReduced" to "Low_resolution"
        textbox.value = textbox.value.replace(new RegExp ("(\\|\s*)ResolutionReduced(\s*=)", "g"), "$1Low_resolution$2");

        var new_value = textbox.value.replace(new RegExp ("\\{\\{(" + nfur_tag + "[_ ]*(?:\\s*<!--(?:-?[^\\-])*--> *)?)\n?(\\s*\\|\\s*)(?:Article\\s*=\\s*\\|\\s*)?"), "{"+"{$1\n$2Article="+backlink+"\n$2");
        var safety_re = new RegExp ("\\{\\{" + nfur_tag + "[_\\s]*(?:<!--(?:-?[^\\-])*-->\\s*)?(?:\\|[\\s\\S]*)?(?:\\{\\{" + nfur_tag + "[_\\s]*\\||\\|\\s*Article\\s*=\\s*[^\\s|])");

        if (new_value != textbox.value && !safety_re.test(textbox.value)) {
            textbox.value = new_value;
            if (editform.wpSummary) editform.wpSummary.value = "adding [[Template:Non-free use rationale|NFUR]] backlink to ["+"["+backlink+"]"+"] with [[User:Ilmari Karonen/nfurbacklink.js|javascript assistance]]";
            if (editform.wpMinoredit) editform.wpMinoredit.checked = true;
            if (window.nfurbacklinkautosave && editform.wpSave) editform.wpSave.click();  // not recommended, but some people like to take risks...
            else if (editform.wpDiff) editform.wpDiff.click();
        }
        else if (previewDiv) {
            var errorMsg = document.createElement("div");
            errorMsg.style.padding = "4px";
            errorMsg.style.border = "2px solid red";
            errorMsg.style.margin = "1em 0";
            errorMsg.appendChild(document.createTextNode("Unable to fix backlink, please add \""));
            errorMsg.appendChild(document.createElement("code"));
            errorMsg.lastChild.appendChild(document.createTextNode("|Article=" + backlink));
            errorMsg.appendChild(document.createTextNode("\" manually."));
            previewDiv.parentNode.insertBefore(errorMsg, previewDiv);
        }
    });
}
else if (mw.config.get('wgNamespaceNumber') == 6 && mw.config.get('wgAction') == "view") {
    addOnloadHook(function () {
        var linkList = document.getElementById("mw-imagepage-section-linkstoimage");
        if (!linkList) return;

        var rationale = false;
        var tables = document.getElementsByTagName("table");
        for (var i = 0; i < tables.length; i++) {
            var summary = tables[i].getAttribute("summary");
            if (!/^The (non-free|fair) use rationale of this image/.test(summary)) continue;
            if (rationale) return; // more than one rationale
            rationale = tables[i];
        }
        if (!rationale) return;
        tables = null;  // free DOM NodeList object

        var links = linkList.getElementsByTagName("a");
        var title = links[0].getAttribute("title");
        if (links.length != 1) title = "";  // should have exactly one link here
        if (/^(Talk|User|Wikipedia|Image|File|MediaWiki|Template|Help|Category|Portal)( talk)?:/.test(title)) title = "";  // wrong ns
        links = null;  // free DOM NodeList object

        var cells = rationale.getElementsByTagName("td");
        for (var j = 0; j < cells.length; j++) {
            if (/^\s*\[\[(\{\{\{Article\}\}\})?\]\]\s*$/.test(cells[j].textContent)) {
                var cellContent = cells[j].getElementsByTagName("p")[0]; 
                if (!cellContent) cellContent = cells[j];  // fallback, in case markup changes

                var fixLink = document.createElement("a");
                fixLink.className = "external";
                fixLink.href = mw.config.get('wgScript') + "?title=" + encodeURIComponent(mw.config.get('wgPageName')) + "&action=edit";
                if (title) {
                    fixLink.href += "&nfurbacklink=" + encodeURIComponent(title);
                    fixLink.appendChild(document.createTextNode("set to "));
                    fixLink.appendChild(document.createElement("i"));
                    fixLink.lastChild.appendChild(document.createTextNode(title));
                } else {
                    fixLink.appendChild(document.createTextNode("please fix manually"));
                }
                var fixSpan = document.createElement("span");
                fixSpan.className = "plainlinks";
                fixSpan.appendChild(document.createTextNode(" ["));
                fixSpan.appendChild(fixLink);
                fixSpan.appendChild(document.createTextNode("] "));
                cellContent.appendChild(fixSpan);
            }
        }
    });
}