Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
/**
 * @author Stöger Florian D. M. (//fdms.eu)
 * @license EUPL 1.1 (//joinup.ec.europa.eu/sites/default/files/eupl1.1.-licence-en_0.pdf)
 * @copyright © (//joinup.ec.europa.eu/sites/default/files/eupl1.1.-licence-en_0.pdf) Stöger Florian D. M. (//fdms.eu)
 */

if (mw.config.get("wgArticleId") !== 70885851) throw new Error("relgen.js must be used through COM:relgen.");

var relgen = 1.4;
var progress, radioSelectInput_s1, namei, repi, authi, radioSelectInput_s2, radioSelectInput_s3, fileri, licensei, iagi;
var filea = [];
var license = "";

document.title = "Wikimedia OTRS release generator - Wikimedia Commons";
$("#firstHeading, #section_0").text("Wikimedia OTRS release generator");
$("#contentSub").html("Version " + relgen + " | developed and maintained by <a href='//commons.wikimedia.org/wiki/User:FDMS4'>FDMS4</a> (<a href='//commons.wikimedia.org/wiki/User_talk:FDMS4?action=edit&section=new&preloadtitle=Wikimedia+OTRS+release+generator+feedback+by+%7B%7Bsubst%3AREVISIONUSER%7D%7D%0A'>feedback</a>)");
$("#mw-content-text").html("Loading …");

function urlaubambauernhof(lko_id) {
    $(".hof").hide();
    $("html, body").animate({
        scrollTop: 0
    }, 400);
    $("#s" + lko_id).show();
    progress.setProgress(lko_id * 17);
    $(".mw-indicators").html("<div id='mw-indicator-mw-helplink' class='mw-indicator'><a href='//commons.wikimedia.org/wiki/Commons:Help_desk?action=edit&section=new&preloadtitle=Help+with+Wikimedia+OTRS+release+generator+step+" + lko_id + "' target='_blank' class='mw-helplink'>Help</a></div>");
    $(".tagline").html("Version " + relgen + " | developed and maintained by <a href='//commons.wikimedia.org/wiki/User:FDMS4'>FDMS4</a> (<a href='//commons.wikimedia.org/wiki/User_talk:FDMS4?action=edit&section=new&preloadtitle=Wikimedia+OTRS+release+generator+feedback+by+%7B%7Bsubst%3AREVISIONUSER%7D%7D%0A'>feedback</a>) | <a href='//commons.wikimedia.org/wiki/Commons:Help_desk?action=edit&section=new&preloadtitle=Help+with+Wikimedia+OTRS+release+generator+step+" + lko_id + "' target='_blank'>help</a>");
}

function smsc(lko_id) {
    $("#back_s" + lko_id).fadeIn(200);
    $("html, body").animate({
        scrollTop: $("#back_s" + lko_id).offset().top
    }, 400);
}

function s1v() {
    if (!namei.getValue().match(/\S/)) {
        mw.notify("Please fill out all fields");
    } else {
        if (($("#irep").css("display") != "none") && (!repi.getValue().match(/\S/) || !authi.getValue().match(/\w/))) {
            mw.notify("Please fill out all fields");
        } else {
            urlaubambauernhof(2);
        }
    }
}

function s3v() {
    filea = [];
    if ($("#iup").css("display") != "none") {
        var s3v_fileackey = s3v_defkey = fileswoissues = 0;
        filea = fileri.getValue().replace(/^\s*\|\s*/, "").replace(/\s*\|\s*$/, "").split(/\s*\|\s*/);
        while (s3v_fileackey < filea.length) {
            if (!filea[s3v_fileackey].match(/\S/)) filea.splice(s3v_fileackey, 1);
            else s3v_fileackey++;
        }   // TO-DO: dupe check
        if (filea.length > 0) {
            var s3v_defexec = function(filea) {
				filea[s3v_defkey] = filea[s3v_defkey].replace(/(?:File:|(?:http|https):\/\/(?:commons|en)\.(?:m\.)?wiki(?:m|p)edia\.org\/(?:wiki\/|w\/index\.php\?title=)File:)?([^&]+).*/, "$1");
                s3v_deffunc(filea[s3v_defkey], function() {
                    s3v_defkey++;
                    if (s3v_defkey < filea.length) s3v_defexec(filea);
                });
            };
            function s3v_deffunc(file, callback) {
                $.getJSON("/w/api.php?action=query&format=json&list=logevents&letype=upload&letitle=File%3A" + file, function(data) {
                    try {
                        if (data.query.logevents.length == 0) {
                            mw.notify("No file named " + file + " has been uploaded to Wikimedia Commons");
                            fileri.setValidityFlag(false);
                            s3v_defkey = filea.length;
                        } else {
                            fileswoissues ++;
                            if (fileswoissues == filea.length) urlaubambauernhof(4);
                        }
                    } catch(err) {
                        mw.notify("\"" + file + "\" is not a valid file name or URL (" + err + ")");
                        s3v_defkey = filea.length;
                    }
                }).done(function() {callback();});
            }
            s3v_defexec(filea);
        } else {
            mw.notify("Please specify one or more file names or URLs");
        }
    } else {
        urlaubambauernhof(4);
    }
}

function s4v() {
    var name = rep = auth = s1 = s2 = s3 = p1s = p1s_ = p1s_m = p2s = p3s = p3sm = b1 = b1m = b2 = b3 = b4 = b5 = b5m = b6 = subj = relt = "";
    
    license = licensei.getValue();

    if (!license.match(/\w/)) {
        mw.notify("Please specify a free license");
    } else {
        s1 = parseInt(radioSelectInput_s1.value);
        s2 = parseInt(radioSelectInput_s2.value);
        s3 = parseInt(radioSelectInput_s3.value);

        name = namei.getValue();
        rep = repi.getValue();
        auth = authi.getValue();

        switch (s1) {
            case 1:
                p1s = ", " + name + ", am";
                break;
            case 2:
                p1s = " represent " + rep + ",";
                p1s_ = "<br />" + auth + " of " + rep;
                p1s_m = "%0A" + auth + " of " + rep;
                break;
        }
        switch (s2) {
            case 1:
                p2s = "the following media work";
                break;
            case 2:
                p2s = "the work depicted in the following media";
                break;
            case 3:
                p2s = "both the work depicted and the following media";
                break;
        }
        switch (s3) {
            case 1:
            	emaila = "permissions-commons@wikimedia.org";
                $.each(filea, function(key, file) {
                	if (key !== 0) {
	                    if (key == filea.length - 1) {p3s += "<br />"; p3sm += "%0A"; subj += " and ";}
	                    else {p3s += "<br />"; p3sm += "%0A"; subj += ", ";}
                	}
                    p3s += "* <a href='//commons.wikimedia.org/wiki/File:" + encodeURIComponent(file.replace(/ /g , "_")) + "' target='_blank'>https://commons.wikimedia.org/wiki/File:" + file.replace(/ /g , "_") + "</a>";
                    p3sm += "%2A https:%2F%2Fcommons.wikimedia.org%2Fwiki%2FFile:" + encodeURIComponent(file.replace(/ /g , "_"));
                    subj += file;
                });
                $("#editwarning").show();
                break;
            case 2:
                emaila = "photosubmission@wikimedia.org";
                p3s = p3sm = subj = "content attached to this email";
                $("#editwarning").hide();
                break;
        }
        b1 = "I hereby affirm that I" + p1s + " the creator and/or sole owner of the exclusive copyright of " + p2s + ":";
        b2 = "I agree to publish the above-mentioned work under the " + license + ".";
        b3 = "I acknowledge that by doing so I grant anyone the right to use the work, even in a commercial product or otherwise, and to modify it according to their needs, provided that they abide by the terms of the license and any other applicable laws.";
        b4 = "I am aware that this agreement is not limited to Wikipedia or related sites.";
        if (license != "Creative Commons CC0 1.0 Universal") {
            b5 = "<br />I am aware that the copyright holder always retains ownership of the copyright as well as the right to be attributed in accordance with the license chosen. Modifications others make to the work will not be claimed to have been made by the copyright holder.";
            b5m = "%0AI am aware that the copyright holder always retains ownership of the copyright as well as the right to be attributed in accordance with the license chosen. Modifications others make to the work will not be claimed to have been made by the copyright holder.";
        }
        b6 = "I acknowledge that I cannot withdraw this agreement, and that the content may or may not be kept permanently on a Wikimedia project.";
        tracking = "[generated using relgen.js]";
        relt = b1 + "<br />" + p3s + "<br />" + b2 + "<br />" + b3 + "<br />" + b4 + b5 + "<br />" + b6 + "<br /><br />" + name + p1s_ + "<br />" + new Date().toJSON().slice(0,10) + "<br /><br />" + tracking;
        $("#emaila-text").text(emaila).prop("href", "mailto:" + emaila);
        $("#front_s5 .mw-ui-button").remove();
        $("#front_s5").append('<a class="mw-ui-button" onclick="nowOP(false);" href="mailto:' + emaila + '?subject=release of ' + subj + '&amp;body=' + b1 + '%0A' + p3sm + '%0A' + b2 + '%0A' + b3 + '%0A' + b4 + b5m + '%0A' + b6 + '%0A%0A' + name + p1s_m + '%0A' + new Date().toJSON().slice(0,10) + '%0A%0A' + tracking + '">create release email</a>');
        $("#back_s5 .releasetext").remove();
        $("#back_s5").prepend("<div class='releasetext'  onclick='nowOP(true);' style='background-color:#eaecf0; padding:8px;'>" + relt + "</div>");

        urlaubambauernhof(5);
    }
}

function nowOP(copy) {
    /* if (s3 == 1) {	// disabled pending community consensus
        $.each(filea, function(key, file) {
            $.getJSON("/w/api.php?action=query&format=json&titles=File%3A" + file, function(data_q1) {
                if (!data_q1.query.pages[-1]) {
                    $.getJSON("/w/api.php?action=query&format=json&prop=templates&tltemplates=Template%3AOTRS%20pending&titles=File%3A" + file, function(data_q2) {
                        if (!data_q2.query.pages[Object.keys(data_q2.query.pages)[0]].templates) {
                            new mw.Api().edit(
                                "File:" + file,
                                function(revision) {
                                    return {
                                        prependtext: "{\{subst:OP}}\n\n",
                                        summary: "OTRS pending: a release for this file has been generated using [[COM:relgen|relgen.js]]"
                                    };
                                }
                            ).fail(function(code, result) {
                                mw.notify("Could not automatically place {\{subst:OP}} on the file description page (API error " + code + ")");
                            });
                        }
                    });
                }
            });
        });
    } */
    progress.setProgress(100);
    if(copy) navigator.clipboard.writeText(relt.replaceAll("<br />", "\n"));
}

$.getJSON("/w/api.php?action=query&format=json&prop=revisions&pageids=77494317&rvprop=content", function(data) {
    $("#mw-content-text").html(data.query.pages[77494317].revisions[0]["*"]);
}).done(function() {
    $(document).ready(function(){
        mw.loader.using("oojs-ui-core").done(function () {
            progress = new OO.ui.ProgressBarWidget({progress: 0, id: "progress"});
            $("#container").prepend(progress.$element);
            urlaubambauernhof(1);
            radioSelectInput_s1 = new OO.ui.RadioSelectInputWidget({
                options: [
                    {data: "1", label: "I am the copyright holder"},
                    {data: "2", label: "I represent the copyright holder"},
                    {data: "0", label: "I don't know the copyright holder"},
                    {data: "-1", label: ""}
                ],
                value: "-1"
            });
            radioSelectInput_s1.on("change", function () {if(radioSelectInput_s1.value > 0) {smsc(1); $('#iam').show(); $('#idk').hide(); if(radioSelectInput_s1.value > 1) $('#irep').show(); else $('#irep').hide();} else {smsc(1); $('#iam').hide(); $('#idk').show();}});
            $("#front_s1").append(radioSelectInput_s1.$element);
            namei = new OO.ui.TextInputWidget({placeholder: "John Doe", required: true});
            namei.on("enter", function() {s1v();});
            var nameifl = new OO.ui.FieldLayout(namei, {label: 'My name', align: 'right'});
            $("#iam").prepend("<br />").prepend(nameifl.$element);
            repi = new OO.ui.TextInputWidget({placeholder: "Ace Inc. / Jane Roe", required: true});
            repi.on("enter", function() {s1v();});
            var repifl = new OO.ui.FieldLayout(repi, {label: 'Copyright holder', align: 'right'});
            authi = new OO.ui.TextInputWidget({placeholder: "CEO, appointed representative, …", required: true});
            authi.on("enter", function() {s1v();});
            var authifl = new OO.ui.FieldLayout(authi, {label: 'My authority', align: 'right'});
            $("#irep").prepend(authifl.$element).prepend(repifl.$element);
            radioSelectInput_s2 = new OO.ui.RadioSelectInputWidget({
                options: [
                    {data: "1", label: "I want to release the media work"},
                    {data: "2", label: "I want to release the work depicted in the media work"},
                    {data: "3", label: "I want to release both the work depicted and the media work"},
                    {data: "-1", label: ""}
                ],
                value: "-1"
            });
            radioSelectInput_s2.on("change", function () {if(radioSelectInput_s2.value > 0) {smsc(2);}});
            $("#front_s2").append(radioSelectInput_s2.$element);
            radioSelectInput_s3 = new OO.ui.RadioSelectInputWidget({
                options: [
                    {data: "1", label: "I or others have already uploaded the file to Wikimedia Commons"},
                    {data: "2", label: "I will attach the file to the email"},
                    {data: "-1", label: ""}
                ],
                value: "-1"
            });
            radioSelectInput_s3.on("change", function () {if(radioSelectInput_s3.value > 0) {smsc(3); if(radioSelectInput_s3.value == 1) $('#iup').show(); else $('#iup').hide();}});
            $("#front_s3").append(radioSelectInput_s3.$element);
            fileri = new OO.ui.MultilineTextInputWidget({placeholder: "File1.jpg | File2.jpg | File3.jpg", spellcheck: false, autosize: true, required: true});
            fileri.on("enter", function() {s3v();});
            var filerifl = new OO.ui.FieldLayout(fileri, {label: 'Wikimedia Commons file name', align: 'right', helpInline: 'true', help: 'separate files with pipe characters'});	// [[mw:Manual:Page_title]]
            $("#iup").append(filerifl.$element).append("<br />");
            $("input[value='-1']").parents("label").remove();
            $(".oo-ui-element-hidden .oo-ui-inputWidget-input").val("-1");
            licensei = new OO.ui.ComboBoxInputWidget({
                options: [
                    {data: "Creative Commons Attribution-ShareAlike 4.0 International"},
                    {data: "Creative Commons Attribution 4.0 International"},
                    {data: "Creative Commons CC0 1.0 Universal", label: "Creative Commons CC0 1.0 Universal (public domain dedication)"}
                ],
                value: "Creative Commons Attribution-ShareAlike 4.0 International",
                placeholder: "Free License of Your Choice 1.0",
                required: true
                // menu: {filterFromInput: true} // initially can't select any other option due to default value
            });
            licensei.on("change", function () {iagi.setSelected(false); if(licensei.value.search("CC0") == -1) $('#iawattr').show(); else $('#iawattr').hide();});
            var licenseifl = new OO.ui.FieldLayout(licensei, {
                align: 'top',
                label: 'I agree to publish the specified content under the following free license:',
                help: new OO.ui.HtmlSnippet("Please enter at least one free license (<a href='//commons.wikimedia.org/wiki/Commons:First_steps/License_selection' target='_blank'>more information</a>).")
            });
            $("#front_s4").prepend(licenseifl.$element);
            // $("#licensei .oo-ui-fieldLayout-help").on("click", function () {}); // TO-DO: find way to bypass popover and link directly
            iagi = new OO.ui.CheckboxInputWidget();
            iagi.on("change", function () {if(iagi.selected) {smsc(4);} else {$("#back_s4").fadeOut(200);}});
            var iagifl = new OO.ui.FieldLayout(iagi, {label: "I agree to the terms above", align: "inline"});
            $("#front_s4").append(iagifl.$element);
            $.getJSON("/w/api.php?action=query&format=json&prop=revisions&pageids=11505208&rvprop=content", function(data) {
                $("#back_s5").append("<br /><p>Once you have sent the release email, you're done! A Wikimedia OTRS volunteer will get back to you once your email has been processed (the current backlog is " + data.query.pages[11505208].revisions[0]["*"]  + " days).</p><br />");
            });
        });
    });
});