Wikipedista:Limojoe/AddCommonsCatLinks.js

Z Wikipedie, otevřené encyklopedie

Poznámka: Po uložení musíte vyprázdnit mezipaměť vašeho prohlížeče, jinak změny neuvidíte.

/*
   The following script places a button at the top of lists of historic sites on many registers around the world.
   When the button is clicked, the script looks on Commons to find images and categories linked to each site's unique ID
   and allows the user to choose to add them to the entries on the list.
*/

// global vars
var thiswikitext=""
var Rows=[];
var HTMLRows=[];
var Matches=[];
var FileMatches=[];
var FileSuggestions=[];
var refnum=[];
var currentRow=0
var MatchesFound=false

// register-specific vars
var TopCatName=""
var RowTemplate=""
var PropertyNameParam=""
var IdentifierName=""
var CombineIdentifiers = false

function FindCommonsCatButton() {
    if (location.href.indexOf('action')!=-1||location.href.indexOf('Talk:')!=-1) return
    thiswikitext=getThisWikitext(wgPageName)
    if (thiswikitext=="error"||thiswikitext=="") return
    if (thiswikitext.search(/{{[ ]*Antarctic Protected Area row/g)!=-1) {            // Antarctica
        TopCatName = "Category:Antarctic_Protected_Areas_with_known_IDs"
        RowTemplate = "Antarctic Protected Area row"
        PropertyNameParam = "name"
        IdentifierName = ["type","number"]
        CombineIdentifiers = true
    } else if (thiswikitext.search(/{{[ ]*Table row Aruba monuments/g)!=-1) {        // Aruba
        TopCatName = "Category:Cultural_heritage_monuments_in_Aruba_with_known_IDs"
        RowTemplate = "Table row Aruba monuments"
        PropertyNameParam = "descr_en"
        IdentifierName = "objcode"
    } else if (thiswikitext.search(/{{[ ]*Table row BE/g)!=-1) {                     // Belgium - Flemish Region
        TopCatName = "Category:Onroerend_erfgoed_with_known_IDs"
        RowTemplate = "Table row BE"
        PropertyNameParam = "descr_en"
        IdentifierName = "id"
    } else if (thiswikitext.search(/{{[ ]*Table row Wallonia/g)!=-1) {               // Belgium - Wallonia
        TopCatName = "Category:Cultural_heritage_monuments_in_Wallonia_with_known_IDs"
        RowTemplate = "Table row Wallonia"
        PropertyNameParam = "descr_en"
        IdentifierName = ["niscode","objcode"]
        CombineIdentifiers = true
    } else if (thiswikitext.search(/{{[ ]*HPC row/g)!=-1) {                          // Canada
        TopCatName = "Category:Heritage_properties_in_Canada_with_known_IDs"
        RowTemplate = "HPC row"
        PropertyNameParam = "name"
        IdentifierName = ["idf","idp","idm"]
    } else if (thiswikitext.search(/{{[ ]*NHS China row/g)!=-1) {                    // China
        TopCatName = "Category:Cultural_heritage_monuments_in_China_with_known_IDs"
        RowTemplate = "NHS China row"
        PropertyNameParam = "site"
        IdentifierName = "designation"
    } else if (thiswikitext.search(/{{[ ]*Památky v Česku/g)!=-1) {                    // Czech Republic
        TopCatName = "Category:Cultural_monuments_in_the_Czech_Republic_with_known_IDs"
        RowTemplate = "Památky v Česku"
        PropertyNameParam = "Název"
        IdentifierName = "Id_objektu"
    } else if (thiswikitext.search(/{{[ ]*Ghana Monument row/g)!=-1) {               // Ghana
        TopCatName = "Category:Cultural_heritage_monuments_in_Ghana_with_known_IDs"
        RowTemplate = "Ghana Monument row"
        PropertyNameParam = "name"
        IdentifierName = "id"
    } else if (thiswikitext.search(/{{[ ]*HK Declared Monument row/g)!=-1) {         // Hong Kong - Declared Monuments
        TopCatName = "Category:Declared_monuments_of_Hong_Kong_with_known_IDs"
        RowTemplate = "HK Declared Monument row"
        PropertyNameParam = "name"
        IdentifierName = "id"
    } else if (thiswikitext.search(/{{[ ]*HK Historic Building row/g)!=-1) {         // Hong Kong - Historic Buildings
        TopCatName = "Category:Historic_buildings_of_Hong_Kong_with_known_IDs"
        RowTemplate = "HK Historic Building row"
        PropertyNameParam = "name"
        IdentifierName = "id"
    } else if (thiswikitext.search(/{{[ ]*ASI Monument row/g)!=-1) {                 // India
        TopCatName = "Category:ASI_monuments_with_known_ID's"
        RowTemplate = "ASI Monument row"
        PropertyNameParam = "description"
        IdentifierName = "number"
    } else if (thiswikitext.search(/{{[ ]*Public art in Israel - row/g)!=-1) {       // Israel - WLPA
        TopCatName = "Category:Public_art_in_Israel_with_known_IDs"
        RowTemplate = "Public art in Israel - row"
        PropertyNameParam = "title"
        IdentifierName = "id"
    } else if (thiswikitext.search(/{{[ ]*NHS Japan row/g)!=-1) {                    // Japan
        TopCatName = "Category:National_historic_sites_of_Japan_with_known_IDs"
        RowTemplate = "NHS Japan row"
        PropertyNameParam = "name"
        IdentifierName = "id"
    } else if (thiswikitext.search(/{{[ ]*Kenya Monument row/g)!=-1) {               // Kenya
        TopCatName = "Category:Kenya_Monuments_with_known_IDs"
        RowTemplate = "Kenya Monument row"
        PropertyNameParam = "name"
        IdentifierName = "id"
    } else if (thiswikitext.search(/{{[ ]*Nepal Monument row/g)!=-1) {               // Nepal
        TopCatName = "Category:Cultural_heritage_monuments_in_Nepal_with_known_IDs"
        RowTemplate = "Nepal Monument row"
        PropertyNameParam = "description"
        IdentifierName = "number"
    } else if (thiswikitext.search(/{{[ ]*PKmonument row/g)!=-1) {                   // Pakistan
        TopCatName = "Category:Cultural_heritage_monuments_in_Pakistan_with_known_IDs"
        RowTemplate = "PKmonument row"
        PropertyNameParam = "description"
        IdentifierName = "number"
    } else if (thiswikitext.search(/{{[ ]*Philippine cultural property row/g)!=-1) { // Philippines
        TopCatName = "Category:Cultural_heritage_monuments_in_the_Philippines_with_known_IDs"
        RowTemplate = "Philippine cultural property row"
        PropertyNameParam = "site_name"
        IdentifierName = "cp-wmph-id"
    } else if (thiswikitext.search(/{{[ ]*SAHRA heritage site row/g)!=-1) {          // South Africa
        TopCatName = "Category:South_Africa_Heritage_Resources_with_known_IDs"
        RowTemplate = "SAHRA heritage site row"
        PropertyNameParam = "Site_name"
        IdentifierName = "SiteReference"
    } else if (thiswikitext.search(/{{[ ]*SIoCPoNaRS row/g)!=-1) {                   // Switzerland
        TopCatName = "Category:Cultural_properties_of_national_significance_in_Switzerland_with_known_IDs"
        RowTemplate = "SIoCPoNaRS row"
        PropertyNameParam = "name"
        IdentifierName = "KGS_nr"
    } else if (thiswikitext.search(/{{[ ]*EH listed building row/g)!=-1) {           // UK - England
        TopCatName = "Category:Listed_buildings_in_England_with_known_IDs"
        RowTemplate = "EH listed building row"
        PropertyNameParam = "name"
        IdentifierName = "uid"
    } else if (thiswikitext.search(/{{[ ]*Cadw listed building row/g)!=-1) {         // UK - Wales
        TopCatName = "Category:Listed_buildings_in_Wales_with_known_IDs"
        RowTemplate = "Cadw listed building row"
        PropertyNameParam = "name"
        IdentifierName = "hb"
    } else if (thiswikitext.search(/{{[ ]*Cardiff listed building row/g)!=-1) {      // UK - Wales - Cardiff
        TopCatName = "Category:Listed_buildings_in_Wales_with_known_IDs"
        RowTemplate = "Cardiff listed building row"
        PropertyNameParam = "name"
        IdentifierName = "hb"
    } else if (thiswikitext.search(/{{[ ]*HS listed building row/g)!=-1) {           // UK - Scotland
        TopCatName = "Category:Listed_buildings_in_Scotland_with_known_IDs"
        RowTemplate = "HS listed building row"
        PropertyNameParam = "name"
        IdentifierName = "hb"
    } else if (thiswikitext.search(/{{[ ]*NIEA listed building row/g)!=-1) {         // UK - Northern Ireland
        TopCatName = "Category:Listed_buildings_in_Northern_Ireland_with_known_IDs"
        RowTemplate = "NIEA listed building row"
        PropertyNameParam = "address"
        IdentifierName = "hb"
    } else if (thiswikitext.search(/{{[ ]*NRHP row/g)!=-1) {                         // US NRHP
        TopCatName = "Category:National_Register_of_Historic_Places_with_known_IDs"
        RowTemplate = "NRHP row"
        PropertyNameParam = "name"
        IdentifierName = "refnum"
    } else if (thiswikitext.search(/{{[ ]*CHL row/g)!=-1) {                          // US - CA
        TopCatName = "Category:California_Historical_Landmarks_with_known_IDs"
        RowTemplate = "CHL row"
        PropertyNameParam = "name"
        IdentifierName = "refnum"

        // allow compatibility with other registers here

    } else {
        return
    }
    var button=document.createElement("input")
    button.setAttribute("type", "button");
    button.setAttribute("value", "Check Commons for images and categories");
    button.setAttribute("id", "commonsbutton");
    button.setAttribute("onclick", "CommonsClick()");
    var content=document.getElementById('mw-content-text')

    content.parentNode.insertBefore(button, content)
}

function CommonsClick() {
    var button = document.getElementById('commonsbutton')
    button.disabled = true

    var ProgressDiv = document.createElement("div")
    ProgressDiv.setAttribute("id", "ProgressDiv")
    ProgressDiv.setAttribute("style", "width:500px; border:5px solid black; padding:5px; position:fixed; background:#ffffff; z-index:100")
    ProgressDiv.style.left = "200px"
    ProgressDiv.style.top = "5px"
    commonsbutton.parentNode.insertBefore(ProgressDiv, commonsbutton)

    ProgressDiv.innerHTML="Checking for matches... "
    window.onbeforeunload = OnBeforeUnLoad;
    FindRows()
}

function FindRows() {
    var AllHTMLRows=document.getElementsByTagName("tr")
    for (var i=0; i<AllHTMLRows.length; i++){
        if (AllHTMLRows[i].className.indexOf("vcard")!=-1||AllHTMLRows[i].className.search(/with(out)?_image/g)!=-1) HTMLRows.push(AllHTMLRows[i])
    }

    var str = "{{"+RowTemplate
    var start=0
    var commentstart=0
    while (true) {
        commentstart=thiswikitext.indexOf("<!--",start)
        start=thiswikitext.indexOf(str,start)
        if (start==-1) break
        if (commentstart<start&&commentstart!=-1) {
            start=thiswikitext.indexOf("-->",commentstart)
            start=thiswikitext.indexOf(str,start)
        }
        var open=1
        var index=start+str.length
        while (open!=0 && index<thiswikitext.length) {
            if (thiswikitext.substr(index,2)=="}}") {
                open--
                index++
            } else if (thiswikitext.substr(index,2)=="{{") {
                open++
                index++
            }
            index++
        }
        Rows[Rows.length]=thiswikitext.substr(start,index-start)
        start++
    }
    currentRow=0
    CheckRow()
}

function CheckRow() {
    var ProgressDiv=document.getElementById("ProgressDiv")
    ProgressDiv.innerHTML="Checking for matches... "
    if (currentRow==Rows.length) {
        if (MatchesFound) {
            editPageWithCommonsCat({
                title: wgPageName,
                text: thiswikitext,
                summary: '[[User:Dudemanfellabra/AddCommonsCatLinks|Semi-automated]] addition of image(s) and/or commonscat link(s) to monument list'
            });
        } else {
            ProgressDiv.innerHTML+="No matches found or selected. Script exited."
            window.onbeforeunload = function() {}
        }
        return;
    }
    HTMLRows[currentRow].scrollIntoView()      // highlight current row
    window.scrollBy(0,-10-ProgressDiv.offsetHeight)

    Matches=[]
    FileMatches=[]
    FileSuggestions=[]
    refnum = []
    var HasImage=false
    var HasCommonsCat=false
    if (typeof IdentifierName=='string') {
        IdentifierName = [IdentifierName]
    }
    for (var j=0; j<IdentifierName.length; j++) {
        var regex=new RegExp("\\|[ ]*?"+IdentifierName[j]+"[ ]*?=.*?(\\n|\\||}})", "g")
        var temprefnum=Rows[currentRow].match(regex)
        if (temprefnum==null) continue
        temprefnum=temprefnum[0]
        regex=new RegExp("\\|[ ]*?"+IdentifierName[j]+"[ ]*?=", "g")
        temprefnum=temprefnum.replace(regex,"").replace(/(\n|\||}})/g,"").replace(/ /g, "").replace(/\<\!\-\-(.|[\r\n])*?\-\-\>/g,"").split(",")
        for (var k=0; k<temprefnum.length; k++) {
            if (temprefnum[k]!="") refnum.push(temprefnum[k])
        }
    }
    if (CombineIdentifiers == true) {            // Some countries have multiple fields joined together
        refnum=[refnum.join("-")]
    }
    for (var j=0; j<refnum.length; j++) {
        if (refnum[j].length<8) {
            refnum[j]="00000000"+refnum[j]       // identifiers with less than 8 digits are padded left with zeroes
            refnum[j]=refnum[j].substr(refnum[j].length-8,8)
        }
    }

    var regex = new RegExp("\\|[ ]*?"+PropertyNameParam+"[ ]*?=.*?(\\n|\\||}})", "g")
    var name=Rows[currentRow].match(regex)
    if (name!=null) {
        name = name[0]
    } else {
        name = ""
    }
    regex = new RegExp("\\|[ ]*?"+PropertyNameParam+"[ ]*?=", "g")
    name=name.replace(regex,"").replace(/(\n|\||}})/g,"").replace(/(\[\[|\]\])/g,"").replace(/\<\!\-\-(.|[\r\n])*?\-\-\>/g,"").trim()

    var commonscat=Rows[currentRow].match(/\|[ ]*?commonscat[ ]*?=.*?(\n|\||}})/g)
    if (commonscat!=null) {
        commonscat=commonscat[0].replace(/\|[ ]*?commonscat[ ]*?=/g,"").replace(/(\n|\||}})/g,"").replace(/\<\!\-\-(.|[\r\n])*?\-\-\>/g,"").trim()
        if (commonscat!="") {
            HasCommonsCat = true    // only true if commonscat param there and non-blank
        }
    }
    var image=Rows[currentRow].match(/\|[ ]*?image[ ]*?=.*?(\n|\||}})/g)
    if (image!=null) {
        image=image[0].replace(/\|[ ]*?image[ ]*?=/g,"").replace(/(\n|\||}})/g,"").replace(/\<\!\-\-(.|[\r\n])*?\-\-\>/g,"").trim()
        if (image!="") {
            HasImage = true    // only true if image param there and non-blank
        }
    }
    if (!HasCommonsCat||!HasImage) {
        var temprefnum=[];
        for (var i=0; i<refnum.length; i++) {
            temprefnum[i]=refnum[i]
        }
        CheckForMatches(name,temprefnum,HasCommonsCat,HasImage)
    } else {
        currentRow++
        CheckRow(currentRow)   // if already has both commonscat and image, skip
    }
}

function CheckForMatches(name,temprefnum,HasCommonsCat,HasImage) {
    if (refnum.length==0) {
        if (Matches.length==0&&FileMatches.length==0&&FileSuggestions.length==0) {
            currentRow++
            CheckRow(currentRow)   // skip if no matches found
        } else {
            ChooseCat(name,temprefnum)
        }
        return
    }
    var sortkey=" "+refnum[0].replace(/\?/g,"") // strip question marks used as placeholders.. code breaks without this
    if (!HasCommonsCat) {
        $.ajax({
        url: 'https://commons.wikimedia.org/w/api.php?action=query&list=categorymembers&format=json&cmtitle='+TopCatName+'&cmprop=title|sortkeyprefix&cmtype=subcat&cmlimit=max&cmsort=sortkey&cmstartsortkeyprefix='+sortkey+'&cmendsortkeyprefix='+sortkey+'0',
        data: {
            format: 'json'
        },
        dataType: 'jsonp',
        success: function(CommonsCatjsonObject) {GotCats(CommonsCatjsonObject,name,temprefnum,sortkey,HasCommonsCat,HasImage)}
        });
    } else {
        GotCats({"query":{"categorymembers":[]}},name,temprefnum,sortkey,HasCommonsCat,HasImage)
    }
}

function GotCats(CommonsCatjsonObject,name,temprefnum,sortkey,HasCommonsCat,HasImage) {
    for (var c in CommonsCatjsonObject.query.categorymembers) {
        var title=CommonsCatjsonObject.query.categorymembers[c].title.replace("Category:","")
        Matches[Matches.length] = [title,refnum[0]]
    }

    if (!HasImage) {
        $.ajax({
        url: 'https://commons.wikimedia.org/w/api.php?action=query&list=categorymembers&format=json&cmtitle='+TopCatName+'&cmprop=title|sortkeyprefix&cmtype=file&cmlimit=max&cmsort=sortkey&cmstartsortkeyprefix='+sortkey+'&cmendsortkeyprefix='+sortkey+'0',
        data: {
            format: 'json'
        },
        dataType: 'jsonp',
        success: function(CommonsCatjsonObject) {GotFiles(CommonsCatjsonObject,name,temprefnum,HasCommonsCat,HasImage)}
        });
    } else {
        GotFiles({"query":{"categorymembers":[]}},name,temprefnum,HasCommonsCat,HasImage)
    }
}

function GotFiles(CommonsCatjsonObject,name,temprefnum,HasCommonsCat,HasImage) {
    for (var c in CommonsCatjsonObject.query.categorymembers) {
        var title=CommonsCatjsonObject.query.categorymembers[c].title.replace("File:","")
        FileMatches[FileMatches.length] = [title,refnum[0]]
    }
    if (!HasImage&&HasCommonsCat&&refnum.length==1) {
        var commonscat=Rows[currentRow].match(/\|[ ]*?commonscat[ ]*?=.*?(\n|\||}})/g)
        commonscat=commonscat[0].replace(/\|[ ]*?commonscat[ ]*?=/g,"").replace(/(\n|\||}})/g,"").replace(/\<\!\-\-(.|[\r\n])*?\-\-\>/g,"").trim()
        commonscat=[commonscat]    // make array to allow compatibility with multiple matched categories below
        $.ajax({
        url: 'https://commons.wikimedia.org/w/api.php?action=query&list=categorymembers&format=json&cmtitle=Category:'+commonscat[0].replace(/ /g,"_")+'&cmprop=title&cmtype=file&cmlimit=max',
        data: {
            format: 'json'
        },
        dataType: 'jsonp',
        success: function(CommonsCatjsonObject) {GotSuggestedFiles(CommonsCatjsonObject,name,commonscat,temprefnum,HasCommonsCat,HasImage)}
        });
    } else if (!HasImage&&Matches.length!=0&&refnum.length==1) {
        var commonscat=[]
        for (var i=0; i<Matches.length; i++) {
            commonscat.push(Matches[i][0])
        }
        $.ajax({
        url: 'https://commons.wikimedia.org/w/api.php?action=query&list=categorymembers&format=json&cmtitle=Category:'+commonscat[0].replace(/ /g,"_")+'&cmprop=title&cmtype=file&cmlimit=max',
        data: {
            format: 'json'
        },
        dataType: 'jsonp',
        success: function(CommonsCatjsonObject) {GotSuggestedFiles(CommonsCatjsonObject,name,commonscat,temprefnum,HasCommonsCat,HasImage)}
        });
    } else {
        refnum.splice(0,1)
        CheckForMatches(name,temprefnum,HasCommonsCat,HasImage)  // check next refnum
    }
}

function GotSuggestedFiles(CommonsCatjsonObject,name,commonscat,temprefnum,HasCommonsCat,HasImage) {
    for (var c in CommonsCatjsonObject.query.categorymembers) {
        var title=CommonsCatjsonObject.query.categorymembers[c].title.replace("File:","")
        FileSuggestions[FileSuggestions.length] = [title,commonscat[0]]
    }
    if (commonscat.length!=1) {
        commonscat.splice(0,1)
        $.ajax({
        url: 'https://commons.wikimedia.org/w/api.php?action=query&list=categorymembers&format=json&cmtitle=Category:'+commonscat[0].replace(/ /g,"_")+'&cmprop=title&cmtype=file&cmlimit=max',
        data: {
            format: 'json'
        },
        dataType: 'jsonp',
        success: function(CommonsCatjsonObject) {GotSuggestedFiles(CommonsCatjsonObject,name,commonscat,temprefnum,HasCommonsCat,HasImage)}
        });
    } else {
        refnum.splice(0,1)
        CheckForMatches(name,temprefnum,HasCommonsCat,HasImage)  // check next refnum
    }
}

function ChooseCat(name,temprefnum) {
    var ProgressDiv=document.getElementById("ProgressDiv")
    ProgressDiv.innerHTML+="Matches found!"
    if (FileMatches.length>0) {
        var done = "no"
        var loops = 0
        var toQuery=FileMatches.length
        while (done=="no") {
            if (toQuery>50) {
                var TempFileMatches = FileMatches.slice(50*loops,50*(loops+1))
            } else {
                var TempFileMatches = FileMatches.slice(50*loops)
            }
            var FileTitleStr="File:"+TempFileMatches[0][0]
            for (var j=1; j<TempFileMatches.length; j++) {
                FileTitleStr+="|File:"+TempFileMatches[j][0]
            }
            var URLs=JSON.parse(   // get URLs of images to display
                $.ajax({
                    dataType: "json",
                    url: mw.util.wikiScript('api'),
                    data: {
                        format: 'json',
                        action: 'query',
                        prop: 'imageinfo',
                        iiprop: 'url',
                        iiurlwidth: '100',
                        titles: FileTitleStr
                    },
                    async:false
                })
                .responseText
            );
            for (var p in URLs.query.pages) {
                for (var j=0; j<FileMatches.length; j++) {
                    if (URLs.query.pages[p].title=="File:"+FileMatches[j][0]) {
                        for (var k in URLs.query.pages[p].imageinfo) {
                            FileMatches[j].push(URLs.query.pages[p].imageinfo[k].thumburl)
                        }
                    }
                }
            }
            if (toQuery>50) {
                toQuery = toQuery-50
                loops++
            } else {
                done = "yes"
            }
        }
        var fieldsetfiles = document.createElement("fieldset");
        fieldsetfiles.setAttribute("style","margin:0px")
        var legend = document.createElement("legend");
        legend.innerHTML=name+" (#"+temprefnum+") matches the following images:"
        fieldsetfiles.appendChild(legend);
        fieldsetfiles.innerHTML+="Select one to add:<br>"

        for (var j=0; j<FileMatches.length; j++) {
            var image = document.createElement("input")
            image.setAttribute("type","radio")
            image.setAttribute("name","imageselect")
            image.setAttribute("id","image"+j)
            if (j==0) image.setAttribute("checked","checked")
            fieldsetfiles.appendChild(image);
            var imagelabel = document.createElement("label")
            imagelabel.setAttribute("for","image"+j)
            imagelabel.innerHTML='<a href="https://commons.wikimedia.org/wiki/File:'+encodeURIComponent(FileMatches[j][0])+'" target="_blank"><div style="display:inline-block; vertical-align:middle; width:100px; overflow-x:hidden; text-overflow:ellipsis"><center><img src="'+FileMatches[j][2].replace(/ /g,"_")+'" style="max-height:100%; max-width:100%;"><br>'+FileMatches[j][1]+'<br>'+FileMatches[j][0]+'</center></div></a>'
            fieldsetfiles.appendChild(imagelabel);
            if ((j+1)%5==0) fieldsetfiles.innerHTML+="<br>"
        }
        if (FileSuggestions.length==0) {
            if (FileMatches.length%5!=0) fieldsetfiles.innerHTML+="<br>"
            var skip = document.createElement("input")
            skip.setAttribute("type","radio")
            skip.setAttribute("name","imageselect")
            skip.setAttribute("id","skipimage")
            fieldsetfiles.appendChild(skip);
            var skiplabel = document.createElement("label")
            skiplabel.setAttribute("for","skipimage")
            skiplabel.innerHTML="Do not add any image"
            fieldsetfiles.appendChild(skiplabel);
            fieldsetfiles.innerHTML+="<br>"
        }
        if (Matches.length==0&&FileSuggestions.length==0) {
            var selectbutton=document.createElement("input")
            selectbutton.setAttribute("type", "button")
            selectbutton.setAttribute("value", "Select")
            selectbutton.setAttribute("style","margin-top:7px")
            selectbutton.setAttribute("onclick", "CatChosen()");
            fieldsetfiles.appendChild(selectbutton)
        }
    }
    if (FileSuggestions.length>0) {
        var done = "no"
        var loops = 0
        var toQuery=FileSuggestions.length
        while (done=="no") {
            if (toQuery>50) {
                var TempFileSuggestions = FileSuggestions.slice(50*loops,50*(loops+1))
            } else {
                var TempFileSuggestions = FileSuggestions.slice(50*loops)
            }
            var FileTitleStr="File:"+TempFileSuggestions[0][0]
            for (var j=1; j<TempFileSuggestions.length; j++) {
                FileTitleStr+="|File:"+TempFileSuggestions[j][0]
            }
            var URLs=JSON.parse(   // get URLs of images to display
                $.ajax({
                    dataType: "json",
                    url: mw.util.wikiScript('api'),
                    data: {
                        format: 'json',
                        action: 'query',
                        prop: 'imageinfo',
                        iiprop: 'url',
                        iiurlwidth: '100',
                        titles: FileTitleStr
                    },
                    async:false
                })
                .responseText
            );
            for (var p in URLs.query.pages) {
                for (var j=0; j<FileSuggestions.length; j++) {
                    if (URLs.query.pages[p].title=="File:"+FileSuggestions[j][0]) {
                        for (var k in URLs.query.pages[p].imageinfo) {
                            FileSuggestions[j].push(URLs.query.pages[p].imageinfo[k].thumburl)
                        }
                    }
                }
            }
            if (toQuery>50) {
                toQuery = toQuery-50
                loops++
            } else {
                done = "yes"
            }
        }
        var fieldsetfilesuggestions = document.createElement("fieldset");
        fieldsetfilesuggestions.setAttribute("style","margin:0px")
        var legend = document.createElement("legend");
        if (FileMatches.length!=0) {
            legend.innerHTML="Other suggested images for "+name+" (#"+temprefnum+") from matched or existing categories:"
        } else {
            legend.innerHTML="Suggested images for "+name+" (#"+temprefnum+") from matched or existing categories:"
        }
        fieldsetfilesuggestions.appendChild(legend);
        fieldsetfilesuggestions.innerHTML+="Select one to add:<br>"

        for (var j=0; j<FileSuggestions.length; j++) {
            var image = document.createElement("input")
            image.setAttribute("type","radio")
            image.setAttribute("name","imageselect")
            image.setAttribute("id","imagesuggestion"+j)
            if (j==0&&FileMatches.length==0) image.setAttribute("checked","checked")
            fieldsetfilesuggestions.appendChild(image);
            var imagelabel = document.createElement("label")
            imagelabel.setAttribute("for","imagesuggestion"+j)
            imagelabel.innerHTML='<a href="https://commons.wikimedia.org/wiki/File:'+encodeURIComponent(FileSuggestions[j][0])+'" target="_blank"><div style="display:inline-block; vertical-align:middle; width:100px; overflow-x:hidden; text-overflow:ellipsis"><center><img src="'+FileSuggestions[j][2].replace(/ /g,"_")+'" style="max-height:100%; max-width:100%;"><br>(from Category:'+FileSuggestions[j][1]+')<br>'+FileSuggestions[j][0]+'</center></div></a>'
            fieldsetfilesuggestions.appendChild(imagelabel);
            if ((j+1)%5==0) fieldsetfilesuggestions.innerHTML+="<br>"
        }
        if (FileSuggestions.length%5!=0) fieldsetfilesuggestions.innerHTML+="<br>"
        var skip = document.createElement("input")
        skip.setAttribute("type","radio")
        skip.setAttribute("name","imageselect")
        skip.setAttribute("id","skipimagesuggestions")
        fieldsetfilesuggestions.appendChild(skip);
        var skiplabel = document.createElement("label")
        skiplabel.setAttribute("for","skipimagesuggestions")
        skiplabel.innerHTML="Do not add any image"
        fieldsetfilesuggestions.appendChild(skiplabel);
        fieldsetfilesuggestions.innerHTML+="<br>"

        if (Matches.length==0) {
            var selectbutton=document.createElement("input")
            selectbutton.setAttribute("type", "button")
            selectbutton.setAttribute("value", "Select")
            selectbutton.setAttribute("style","margin-top:7px")
            selectbutton.setAttribute("onclick", "CatChosen()");
            fieldsetfilesuggestions.appendChild(selectbutton)
        }
    }
    if (Matches.length>0) {
        var fieldsetcats = document.createElement("fieldset");
        fieldsetcats.setAttribute("style","margin:0px")
        var legend = document.createElement("legend");
        legend.innerHTML=name+" (#"+temprefnum+") matches the following categories:"
        fieldsetcats.appendChild(legend);
        fieldsetcats.innerHTML+="Select one to add:<br>"

        for (var j=0; j<Matches.length; j++) {
            var cat = document.createElement("input")
            cat.setAttribute("type","radio")
            cat.setAttribute("name","catselect")
            cat.setAttribute("id","cat"+j)
            if (j==0) cat.setAttribute("checked","checked")
            fieldsetcats.appendChild(cat);
            var catlabel = document.createElement("label")
            catlabel.setAttribute("for","cat"+j)
            catlabel.innerHTML=Matches[j][1]+' – <a href="https://commons.wikimedia.org/wiki/Category:'+encodeURIComponent(Matches[j][0])+'" target="_blank">'+Matches[j][0]+'</a>'
            fieldsetcats.appendChild(catlabel);
            fieldsetcats.innerHTML+="<br>"
        }
        var skip = document.createElement("input")
        skip.setAttribute("type","radio")
        skip.setAttribute("name","catselect")
        skip.setAttribute("id","skip")
        fieldsetcats.appendChild(skip);
        var skiplabel = document.createElement("label")
        skiplabel.setAttribute("for","skip")
        skiplabel.innerHTML="Do not add any category"
        fieldsetcats.appendChild(skiplabel);
        fieldsetcats.innerHTML+="<br>"

        var selectbutton=document.createElement("input")
        selectbutton.setAttribute("type", "button")
        selectbutton.setAttribute("value", "Select")
        selectbutton.setAttribute("style","margin-top:7px")
        selectbutton.setAttribute("onclick", "CatChosen()");
        fieldsetcats.appendChild(selectbutton)
    }
    var overlay = document.createElement("tr")
    var td=document.createElement("td")
    td.setAttribute("colspan",HTMLRows[currentRow].getElementsByTagName("td").length+1)
    overlay.appendChild(td)
    if (FileMatches.length>0) td.appendChild(fieldsetfiles)
    if (FileSuggestions.length>0) td.appendChild(fieldsetfilesuggestions)
    if (Matches.length>0) td.appendChild(fieldsetcats)
    overlay.setAttribute("style", "outline:2px solid red; border-top:0px; background:#ffffff")
    overlay.setAttribute("id","overlay")
    HTMLRows[currentRow].setAttribute("style","border-bottom:0px;")
    HTMLRows[currentRow].parentNode.insertBefore(overlay, HTMLRows[currentRow].nextSibling)
}

function CatChosen() {
    var overlay=document.getElementById("overlay")
    var options=overlay.getElementsByTagName("input")
    var titles=overlay.getElementsByTagName("label")
    for (var i=0; i<options.length-1; i++) {
        if (options[i].checked) {
            if (options[i].name.search("cat")!=-1) {
                var link=titles[i].getElementsByTagName("a")
                if (link.length==0) continue    // if chose not to add cat
                MatchesFound = true             // if chose to add something
                var catname=link[0].innerHTML
                var tempRow = Rows[currentRow]
                if (tempRow.match(/\|[ ]*?commonscat[ ]*?=[^\|\n]*?}}/g)!=null) {
                    tempRow=tempRow.replace(/\|[ ]*?commonscat[ ]*?=[^\|\n]*?}}/g, "}}")
                } else if (tempRow.match(/\|[ ]*?commonscat[ ]*?=.*?\|/g)!=null) {
                    tempRow=tempRow.replace(/\|[ ]*?commonscat[ ]*?=.*?\|/g, "|")
                } else if (tempRow.match(/\|[ ]*?commonscat[ ]*?=.*?\n/g)!=null) {
                    tempRow=tempRow.replace(/\|[ ]*?commonscat[ ]*?=.*?\n/g, "")
                }
                var EndOfTemplate=tempRow.lastIndexOf("}}")
                if (tempRow.indexOf("\n")!=-1&&tempRow.indexOf("\n")!=0&&tempRow.indexOf("\n")!=tempRow.length-1) {
                    tempRow = tempRow.substr(0,EndOfTemplate)+"|commonscat="+catname+"\n}}"+tempRow.substr(EndOfTemplate+2,tempRow.length-EndOfTemplate-2)
                } else {
                    tempRow = tempRow.substr(0,EndOfTemplate)+"|commonscat="+catname+"}}"+tempRow.substr(EndOfTemplate+2,tempRow.length-EndOfTemplate-2)
                }
                thiswikitext=thiswikitext.replace(Rows[currentRow],tempRow)
                Rows[currentRow] = tempRow
            } else {
                var link=titles[i].getElementsByTagName("a")
                if (link.length==0) continue    // if chose not to add image
                MatchesFound = true             // if chose to add something
                var imagename=link[0].innerHTML
                var StartIndex=imagename.lastIndexOf("<br>")+4
                imagename=imagename.substr(StartIndex,imagename.indexOf("</center>",StartIndex)-StartIndex)
                var tempRow = Rows[currentRow]
                if (tempRow.match(/\|[ ]*?image[ ]*?=[^\|\n]*?}}/g)!=null) {
                    tempRow=tempRow.replace(/\|[ ]*?image[ ]*?=[^\|\n]*?}}/g, "}}")
                } else if (tempRow.match(/\|[ ]*?image[ ]*?=.*?\|/g)!=null) {
                    tempRow=tempRow.replace(/\|[ ]*?image[ ]*?=.*?\|/g, "|")
                } else if (tempRow.match(/\|[ ]*?image[ ]*?=.*?\n/g)!=null) {
                    tempRow=tempRow.replace(/\|[ ]*?image[ ]*?=.*?\n/g, "")
                }
                var EndOfTemplate=tempRow.lastIndexOf("}}")
                if (tempRow.indexOf("\n")!=-1&&tempRow.indexOf("\n")!=0&&tempRow.indexOf("\n")!=tempRow.length-1) {
                    tempRow = tempRow.substr(0,EndOfTemplate)+"|image="+imagename+"\n}}"+tempRow.substr(EndOfTemplate+2,tempRow.length-EndOfTemplate-2)
                } else {
                    tempRow = tempRow.substr(0,EndOfTemplate)+"|image="+imagename+"}}"+tempRow.substr(EndOfTemplate+2,tempRow.length-EndOfTemplate-2)
                }
                thiswikitext=thiswikitext.replace(Rows[currentRow],tempRow)
                Rows[currentRow] = tempRow
            }
        }
    }
    overlay.parentNode.removeChild(overlay)
    currentRow++
    CheckRow(currentRow)
}

function getThisWikitext(title) {
    try {
        var output=JSON.parse(
            $.ajax({
                dataType: "json",
                url: mw.util.wikiScript('api'),
                data: {
                    format: 'json',
                    action: 'query',
                    prop: 'revisions',
                    rvprop: 'content',
                    titles: title,
                    indexpageids: true,
                    redirects: 'true'
                },
                async:false
            })
            .responseText
        );
        for (var page in output.query.pages) {
            wikitext = output.query.pages[page].revisions[0]['*'];
        }
        return wikitext
    }
    catch(err) {
        return "error"
    }
}

function editPageWithCommonsCat(info,ProgressDiv) {
    var ProgressDiv=document.getElementById("ProgressDiv")
    ProgressDiv.innerHTML+="Done!<br>Editing page... "

    $.ajax({
        url: mw.util.wikiScript( 'api' ),
        type: 'POST',
        dataType: 'json',
        data: {
            format: 'json',
            action: 'edit',
            title: info.title,
            text: info.text,
            summary: info.summary,
            token: mw.user.tokens.get( 'editToken' )
        }
    })
        .done (function( data ) {
            window.onbeforeunload = function() {}
            if (data && data.edit && data.edit.result && data.edit.result == 'Success') {
                ProgressDiv.innerHTML+="Done! Refresh the page to see the result!"
            } else {
                ProgressDiv.innerHTML += " The edit query returned an error."
            }
        })
        .fail (function() {
            alert('Ajax failure.');
        });
}

function OnBeforeUnLoad () {
    return "Are you sure you want to leave the page? All categories/files that you have added will not be saved!";
}

$(FindCommonsCatButton);