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.
// This is auto save version of [[User:Ilmari Karonen/nfurbacklink.js]]
// Copyright holder is [[User:Ilmari Karonen]]

if (wgCanonicalNamespace == "Image" && 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";
        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 + "[_ ]*)\n?(\\s*\\|\\s*)"), "{"+"{$1\n$2Article="+backlink+"\n$2");
        var safety_re = new RegExp ("\\{\\{" + nfur_tag + "[_\\s]*(?:\\|[\\s\\S]*)?(?:\\{\\{" + nfur_tag + "[_\\s]*\\||\\|\\s*Article\\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:OsamaK/nfurbacklink.js|javascript assistance]]";
            if (editform.wpMinoredit) editform.wpMinoredit.checked = true;
            if (editform.wpSave) editform.wpSave.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.appendChild(errorMsg);
        }
    });
}
else if (wgCanonicalNamespace == "Image" && wgAction == "view") {
    addOnloadHook(function () {
        var linkList = document.getElementById("filelinks");
        while (linkList && (!linkList.tagName || linkList.tagName.toLowerCase() != "ul")) linkList = linkList.nextSibling;
        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 (summary != "The fair use rationale of this image.") 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|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 = 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);
            }
        }
    });
}