User:Richard0612/monobook.js

From Wikipedia, the free encyclopedia

If a message on your talk page led you here, please be wary of who left it. Code that you insert on this page could contain malicious content capable of compromising your account. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. If this is a .js page, the code will be executed when previewing the page.
Note: After saving, you have to bypass your browser's cache to see the changes. In Internet Explorer and Firefox, hold down the Ctrl key and click the Refresh or Reload button. Opera users have to clear their caches through Tools→Preferences, see the instructions for Opera. Konqueror and Safari users can just click the Reload button.
// [[User:Lupin/popups.js]]
 
document.write('<script type="text/javascript" src="' 
             + 'http://en.wikipedia.org/w/index.php?title=User:Lupin/popups.js' 
             + '&action=raw&ctype=text/javascript&dontcountme=s"></script>');
 
//<nowiki> Admin-like RC Patrol tools
 
document.write('<script type="text/javascript" src="' 
             + 'http://en.wikipedia.org/w/index.php?title=User:VoA/monobook.js' 
             + '&action=raw&ctype=text/javascript&dontcountme=s"></script>');
 
//</nowiki>[[Category:Wikipedians who use RC script ]]
 
// Interiot's Tool2
 
document.write('<script type="text/javascript" src="' 
    + 'http://en.wikipedia.org/w/index.php?title=User:Interiot/Tool2/code.js' 
    + '&action=raw&ctype=text/javascript&dontcountme=s"></script>');
// addLink helper
/*
 
*/
//A helper function to add a button to one of the toolbars in the interface.
//An improved(I hope) version of [[Wikipedia:WikiProject User scripts/Scripts/Add LI link|addlilink]].
//[[User:JesseW/sig|JesseW, the juggling janitor]] 05:33, 8 November *2005 (UTC)
 
function addLink(where, url, name, id, title, key, after){
    //* where is the id of the toolbar where the button should be added;
    //   i.e. one of "p-cactions", "p-personal", "p-navigation", or "p-tb".
    //
    //* url is the URL which will be called when the button is clicked.
    //   javascript: urls can be used to do more complex things.
    //
    //* name is what will appear as the name of the button.
    //
    //* id is the id of the button; it's best to define one.  
    //   Use a prefix to make sure its unique. Optional.
    //
    //* title is the tooltip title that gives a longer description 
    //   of the button; if you define a accesskey, mention it here. Optional.
    //
    //* key is the char you want for the accesskey. Optional.
    //
    //* after is the id of the button you want to follow this one. Optional.
    //
    var na = document.createElement('a');
    na.href = url;
    na.appendChild(document.createTextNode(name));
    var li = document.createElement('li');
    if(id) li.id = id;
    li.appendChild(na);
    var tabs = document.getElementById(where).getElementsByTagName('ul')[0];
    if(after) {
        tabs.insertBefore(li,document.getElementById(after));
    } else {
        tabs.appendChild(li);
    }
    if(id) {
        if(key && title) { ta[id] = [key, title]; }
        else if(key) { ta[id] = [key, '']; }
        else if(title) { ta[id] = ['', title];} 
    }
    // re-render the title and accesskeys from existing code in wikibits.js
    akeytt();
    return li;
}
/*
 
*/
// RBL CHECK LINK: <pre><nowiki>
 
addOnloadHook(function () {
    var href = document.getElementById('t-contributions');
    if (href) href = href.getElementsByTagName('a');
    if (href) href = href[0];
    if (href) href = href.href;
    else href = window.location.href;
 
    var addr = /(\/wiki\/|[?&]title=)Special:Contributions(\/([^\/?&#]*)|[?&#]|$)/.exec(href);
    if (!addr) return;
    addr = addr[3];
    if (!addr) {
        addr = /^[^?#]*\?([^&#]*&)*target=([^&#]*)/.exec(href);
        if (!addr) return;
        addr = addr[2];
    }
    if (!/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/.test(addr)) return;
 
    addLink('p-tb', 'http://www.robtex.com/rbls/'+addr+'.html', 'RBL check', 't-rblcheck', 'Multi-RBL check', null, 't-contributions');
});
 
// </nowiki></pre>
 
importScript('User:AzaToth/morebits.js');
importScript('User:AzaToth/twinklefluff.js');
importScript('User:AzaToth/twinklediff.js');
importScript('User:AzaToth/twinkleprotect.js');
importScript('User:AzaToth/twinkleimage.js')
importScript('User:AzaToth/twinkleunlink.js');
importScript('User:AzaToth/twinkledelimages.js');
importScript('User:AzaToth/twinkledeprod.js');
importScript('User:AzaToth/twinklebatchdelete.js');
importScript('User:AzaToth/twinklebatchprotect.js');
importScript('User:AzaToth/twinkleimagetraverse.js');
importScript('User:AzaToth/twinklesalt.js');
 
//<nowiki> Log tools
document.write('<script type="text/javascript" src="' 
             + 'http://en.wikipedia.org/w/index.php?title=User:Voice_of_All/Sleeper/monobook.js' 
             + '&action=raw&ctype=text/javascript&dontcountme=s"></script>');
 
//</nowiki>[[Category:Wikipedians who use VoA script|{{PAGENAME}}]]
 
 
 
// If TwinkleConfig aint exist.
if( typeof( TwinkleConfig ) == 'undefined' ) {
TwinkleConfig = {};
}
 
/**
TwinkleConfig.summaryAd (string)
If ad should be added or not to summary, default [[WP:TWINKLE|TWINKLE]]
*/
if( typeof( TwinkleConfig.summaryAd ) == 'undefined' ) {
TwinkleConfig.summaryAd = " using [[WP:TW|TW]]";
}
 
/**
TwinkleConfig.watchProdPages (boolean)
If, when applying prod template to page, watch it, default true
*/
if( typeof( TwinkleConfig.watchProdPages ) == 'undefined' ) {
TwinkleConfig.watchProdPages = true;
}
 
function twinkleprod() {
if (twinkleConfigExists)
{
addPortletLink( 'p-cactions', "javascript:twinkleprod.callback()", "prod", "tw-prod", "Propose deletion via WP:PROD", "");
}
else
{
addPortletLink('p-cactions', 'javascript:alert("Your account is too new to use Twinkle.");', 'prod', 'tw-prod', 'Propose deletion via WP:PROD', '');
}
}
addOnloadHook(twinkleprod);
 
twinkleprod.callback = function twinkleprodCallback() {
var Window = new SimpleWindow( 800, 400 );
Window.setTitle( "WP:PROD" );
var form = new QuickForm( twinkleprod.callback.evaluate );
var field = form.append( {
type: 'field',
label: 'Reason for proposed deletion'
} );
field.append( {
type: 'textarea',
name: 'reason',
label: 'Reason:'
} );
field.append( { type:'submit' } );
 
var result = form.render();
Window.setContent( result );
Window.display();
}
 
twinkleprod.callbacks = {
main: function( self ) {
var form = self.responseXML.getElementById('editform');
var text = form.wpTextbox1.value;
 
var tag_re = /(\{\{(?:db-?|delete|[aitcmrs]fd|md1)[^{}]*?\|?[^{}]*?\}\})/;
 
if( tag_re.test( text ) ) {
self.statelem.warn( 'Page already tagged with a deletion template, aborting procedure' );
return;
}
// Notification to first contributor
var query = {
'action': 'query',
'prop': 'revisions',
'titles': wgPageName,
'rvlimit': 1,
'rvprop': 'user',
'rvdir': 'newer'
}
var callback = function( self ) {
var xmlDoc = self.responseXML;
var user = xmlDoc.evaluate( '//rev/@user', xmlDoc, null, XPathResult.STRING_TYPE, null ).stringValue;
var query = {
'title': 'User talk:' + user,
'action': 'submit'
};
var wikipedia_wiki = new Wikipedia.wiki( 'Notifying of initial contributor (' + user + ')', query, twinkleprod.callbacks.userNotification );
wikipedia_wiki.params = self.params;
wikipedia_wiki.get();
}
 
var wikipedia_api = new Wikipedia.api( 'Grabbing data of initial contributor', query, callback );
wikipedia_api.params = self.params;
wikipedia_api.post();
 
var postData = {
'wpMinoredit': undefined, // Per memo
'wpWatchthis': TwinkleConfig.watchProdPages ? '' : form.wpWatchthis.checked ? '' : undefined,
'wpStarttime': form.wpStarttime.value,
'wpEdittime': form.wpEdittime.value,
'wpAutoSummary': form.wpAutoSummary.value,
'wpEditToken': form.wpEditToken.value,
'wpSummary': "Proposing article for deletion per [[WP:PROD]]." + TwinkleConfig.summaryAd,
'wpTextbox1': "\{\{subst:prod|1=" + self.params.reason + "}}\n" + text
};
 
self.post( postData );
},
userNotification: function( self ) {
var form = this.responseXML.getElementById( 'editform' );
var text = form.wpTextbox1.value;
text += "\n\{\{subst:PRODWarning|1=" + wgPageName + "\}\} \~\~\~";
var postData = {
'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
'wpStarttime': form.wpStarttime.value,
'wpEdittime': form.wpEdittime.value,
'wpAutoSummary': form.wpAutoSummary.value,
'wpEditToken': form.wpEditToken.value,
'wpSummary': 'PROD nomination of \[\[' + wgPageName + '\]\].' + TwinkleConfig.summaryAd,
'wpTextbox1': text
};
 
self.post ( postData );
}
}
 
twinkleprod.callback.evaluate = function twinkleprodCallbackEvaluate(e) {
var form = e.target;
var reason = form.reason.value;
 
wgPageName = wgPageName.replace(/_/g, ' ');
 
Status.init( form );
var query = { 
'title': wgPageName, 
'action': 'submit'
};
 
var wikipedia_wiki = new Wikipedia.wiki( 'Tagging page', query, twinkleprod.callbacks.main );
wikipedia_wiki.params = { reason: reason };
wikipedia_wiki.followRedirect = false;
wikipedia_wiki.get();
}
 
// If TwinkleConfig aint exist.
if( typeof( TwinkleConfig ) == 'undefined' ) {
    TwinkleConfig = {};
}
 
/**
 TwinkleConfig.showSharedIPNotice may take arguments:
 true: to show shared ip notice if an IP address
 false: to not print the notice
 */
if( typeof( TwinkleConfig.showSharedIPNotice ) == 'undefined' ) {
    TwinkleConfig.showSharedIPNotice = true;
}
 
/**
 TwinkleConfig.watchWarnings (boolean)
 if true, watch the page which has been dispatched an warning or notice, if false, default applies
 */
if( typeof( TwinkleConfig.watchWarnings ) == 'undefined' ) {
    TwinkleConfig.watchWarnings = true;
}
 
/**
 TwinkleConfig.summaryAd (string)
 If ad should be added or not to summary, default [[WP:TWINKLE|TWINKLE]]
 */
if( typeof( TwinkleConfig.summaryAd ) == 'undefined' ) {
    TwinkleConfig.summaryAd = " using [[WP:TW|TW]]";
}
 
function twinklewarn() {
    if( wgNamespaceNumber == 3 ) {
        addPortletLink( 'p-cactions', (twinkleConfigExists ? "javascript:twinklewarn.callback()" : 'javascript:alert("Your account is too new to use Twinkle.");'), "warn", "tw-warn", "Warn/Notify user", "");
    }
}
addOnloadHook(twinklewarn);
 
twinklewarn.callback = function twinklewarnCallback() {
    var Window = new SimpleWindow( 600, 400 );
    Window.setTitle( "Warn/Notify user" ); 
    var form = new QuickForm( twinklewarn.callback.evaluate );
 
    var main_select = form.append( {
            type:'field',
            label:'Choose type of warning/notice to issue', 
            tooltip:'Choose first the main group you want to issue, then choose an appropriate type to issue.'
        } );
 
    var main_group = main_select.append( {
            type:'select',
            name:'main_group',
            event:twinklewarn.callback.change_category 
        } );
 
    main_group.append( { type:'option', label:'General Note (1)', value:'level1', selected:true } );
    main_group.append( { type:'option', label:'Caution (2)', value:'level2' } );
    main_group.append( { type:'option', label:'Warning (3)', value:'level3' } );
    main_group.append( { type:'option', label:'Final warning (4)', value:'level4' } );
    main_group.append( { type:'option', label:'Only warning (4im)', value:'level4im' } );
    main_group.append( { type:'option', label:'Single issue notices', value:'singlenotice' } );
    main_group.append( { type:'option', label:'Single issue warnings', value:'singlewarn' } );
    if( userIsInGroup( 'sysop' ) ) {
        main_group.append( { type:'option', label:'Blocking', value:'block' } );
    }
 
    main_select.append( { type:'select', name:'sub_group' } ); //Will be empty to begin with.
 
    form.append( { 
            type:'input',
            name:'article',
            label:'Linked article',
            value:( QueryString.exists( 'vanarticle' ) ? QueryString.get( 'vanarticle' ) : '' ),
            tooltip:'An article might be linked to the notice, either it was a revert to said article that dispatched this notice. Leave empty for no article to be linked'
        } );
 
 
    var more = form.append( { type:'field', label:'Fill in an optional reason and hit \"Submit\"' } );
    more.append( { type:'textarea', label:'More:', name:'reason', tooltip:'Perhaps a reason, or that a more detailed notice must be appended' } );
    more.append( { type:'submit', label:'Submit' } );
    var result = form.render();
    Window.setContent( result );
    Window.display();
    result.main_group.root = result;
 
    // We must init the first choice (General Note);
    var evt = document.createEvent( "Event" );
    evt.initEvent( 'change', true, true );
    result.main_group.dispatchEvent( evt );
 
}
 
// This is all the messages that might be dispatched by the code
twinklewarn.messages = {
    level1: {
        "uw-vandalism1": { 
            label:"Vandalism", 
            summary:"General note: Vandalism" 
        },
        "uw-test1": { 
            label:"Editing tests", 
            summary:"General note: Editing tests" 
        },
        "uw-delete1": { 
            label:"Page blanking, removal of content or templates", 
            summary:"General note: Page blanking, removal of content or templates" 
        },
        "uw-joke1": { 
            label:"Using improper humor", 
            summary:"General note: Using improper humor" 
        },
        "uw-create1": { 
            label:"Creating inappropriate pages", 
            summary:"General note: Creating inappropriate pages" 
        },
        "uw-upload1": { 
            label:"Uploading inappropriate images", 
            summary:"General note: Uploading inappropriate images" 
        },
        "uw-image1": { 
            label:"Image-related vandalism", 
            summary:"General note: Image-related vandalism" 
        },
        "uw-spam1": { 
            label:"Adding spam links", 
            summary:"General note: Adding spam links" 
        },
        "uw-advert1": { 
            label:"Using Wikipedia for advertising or promotion", 
            summary:"General note: Using Wikipedia for advertising or promotion" 
        },
        "uw-npov1": { 
            label:"Not adhering to neutral point of view", 
            summary:"General note: Not adhering to neutral point of view" 
        },
        "uw-unsourced1": { 
            label:"Addition of unsourced material without proper citations", 
            summary:"General note: Addition of unsourced material without proper citations" 
        },
        "uw-error1": { 
            label:"Introducing deliberate factual errors", 
            summary:"General note: Introducing deliberate factual errors" 
        },
        "uw-biog1": { 
            label:"Adding unreferenced controversial information about living persons", 
            summary:"General note: Adding unreferenced controversial information about living persons" 
        },
        "uw-defam1": { 
            label:"Defamation not specifically directed", 
            summary:"General note: Defamation not specifically directed" 
        },
        "uw-uncen1": { 
            label:"Censorship of material", 
            summary:"General note: Censorship of material" 
        },
        "uw-mos1": { 
            label:"Manual of style", 
            summary:"General note: Formatting, date, language, etc (Manual of style)" 
        },
        "uw-move1": { 
            label:"Page moves", 
            summary:"General note: Page moves" 
        },
        "uw-chat1": { 
            label:"Using talk page as forum", 
            summary:"General note: Using talk page as forum" 
        },
        "uw-tpv1": { 
            label:"Refactoring others' talk page comments", 
            summary:"General note: Refactoring others' talk page comments" 
        },
        "uw-afd1": { 
            label:"Removing \{\{afd\}\} templates", 
            summary:"General note: Removing \{\{afd\}\} templates" 
        },
        "uw-speedy1": { 
            label:"Removing \{\{speedy deletion\}\} templates", 
            summary:"General note: Removing \{\{speedy deletion\}\} templates" 
        },
        "uw-npa1": { 
            label:"Personal attack directed at a specific editor", 
            summary:"General note: Personal attack directed at a specific editor" 
        },
        "uw-agf1": { 
            label:"Not assuming good faith", 
            summary:"General note: Not assuming good faith" 
        },
        "uw-own1": { 
            label:"Ownership of articles", 
            summary:"General note: Ownership of articles"
        },
        "uw-nor1": { 
            label:"Adding original research", 
            summary:"General note: Adding original research, including unpublished syntheses of sourced material"
        }
    },
    level2: {
        "uw-vandalism2": { 
            label:"Vandalism", 
            summary:"Caution: Vandalism" 
        },
        "uw-test2": { 
            label:"Editing tests", 
            summary:"Caution: Editing tests" 
        },
        "uw-delete2": { 
            label:"Page blanking, removal of content or templates", 
            summary:"Caution: Page blanking, removal of content or templates" 
        },
        "uw-joke2": { 
            label:"Using improper humor", 
            summary:"Caution: Using improper humor" 
        },
        "uw-create2": { 
            label:"Creating inappropriate pages", 
            summary:"Caution: Creating inappropriate pages" 
        },
        "uw-upload2": { 
            label:"Uploading inappropriate images", 
            summary:"Caution: Uploading inappropriate images" 
        },
        "uw-image2": { 
            label:"Image-related vandalism", 
            summary:"Caution: Image-related vandalism" 
        },
        "uw-spam2": { 
            label:"Adding spam links", 
            summary:"Caution: Adding spam links" 
        },
        "uw-advert2": { 
            label:"Using Wikipedia for advertising or promotion", 
            summary:"Caution: Using Wikipedia for advertising or promotion" 
        },
        "uw-npov2": { 
            label:"Not adhering to neutral point of view", 
            summary:"Caution: Not adhering to neutral point of view" 
        },
        "uw-unsourced2": { 
            label:"Addition of unsourced material without proper citations", 
            summary:"Caution: Addition of unsourced material without proper citations" 
        },
        "uw-error2": { 
            label:"Introducing deliberate factual errors", 
            summary:"Caution: Introducing deliberate factual errors" 
        },
        "uw-biog2": { 
            label:"Adding unreferenced controversial information about living persons", 
            summary:"Caution: Adding unreferenced controversial information about living persons" 
        },
        "uw-defam2": { 
            label:"Defamation not specifically directed", 
            summary:"Caution: Defamation not specifically directed" 
        },
        "uw-uncen2": { 
            label:"Censorship of material", 
            summary:"Caution: Censorship of material" 
        },
        "uw-mos2": { 
            label:"Manual of style", 
            summary:"Caution: Formatting, date, language, etc (Manual of style)" 
        },
        "uw-move2": { 
            label:"Page moves", 
            summary:"Caution: Page moves" 
        },
        "uw-chat2": { 
            label:"Using talk page as forum", 
            summary:"Caution: Using talk page as forum" 
        },
        "uw-tpv2": { 
            label:"Refactoring others' talk page comments", 
            summary:"Caution: Refactoring others' talk page comments" 
        },
        "uw-afd2": { 
            label:"Removing \{\{afd\}\} templates", 
            summary:"Caution: Removing \{\{afd\}\} templates" 
        },
        "uw-speedy2": { 
            label:"Removing \{\{speedy deletion\}\} templates", 
            summary:"Caution: Removing \{\{speedy deletion\}\} templates" 
        },
        "uw-npa2": { 
            label:"Personal attack directed at a specific editor", 
            summary:"Caution: Personal attack directed at a specific editor" 
        },
        "uw-agf2": { 
            label:"Not assuming good faith", 
            summary:"Caution: Not assuming good faith" 
        },
        "uw-own2": { 
            label:"Ownership of articles", 
            summary:"Caution: Ownership of articles"
        },
        "uw-nor2": { 
            label:"Adding original research", 
            summary:"Caution: Adding original research, including unpublished syntheses of sourced material"
        }
    },
    level3: {
        "uw-vandalism3": { 
            label:"Vandalism", 
            summary:"Warning: Vandalism" 
        },
        "uw-test3": { 
            label:"Editing tests", 
            summary:"Warning: Editing tests" 
        },
        "uw-delete3": { 
            label:"Page blanking, removal of content or templates", 
            summary:"Warning: Page blanking, removal of content or templates" 
        },
        "uw-joke3": { 
            label:"Using improper humor", 
            summary:"Warning: Using improper humor" 
        },
        "uw-create3": { 
            label:"Creating inappropriate pages", 
            summary:"Warning: Creating inappropriate pages" 
        },
        "uw-upload3": { 
            label:"Uploading inappropriate images", 
            summary:"Warning: Uploading inappropriate images" 
        },
        "uw-image3": { 
            label:"Image-related vandalism", 
            summary:"Warning: Image-related vandalism" 
        },
        "uw-spam3": { 
            label:"Adding spam links", 
            summary:"Warning: Adding spam links" 
        },
        "uw-advert3": { 
            label:"Using Wikipedia for advertising or promotion", 
            summary:"Warning: Using Wikipedia for advertising or promotion" 
        },
        "uw-npov3": { 
            label:"Not adhering to neutral point of view", 
            summary:"Warning: Not adhering to neutral point of view" 
        },
        "uw-unsourced3": { 
            label:"Addition of unsourced material without proper citations", 
            summary:"Warning: Addition of unsourced material without proper citations" 
        },
        "uw-error3": { 
            label:"Introducing deliberate factual errors", 
            summary:"Warning: Introducing deliberate factual errors" 
        },
        "uw-biog3": { 
            label:"Adding unreferenced controversial information about living persons", 
            summary:"Warning: Adding unreferenced controversial information about living persons" 
        },
        "uw-defam3": { 
            label:"Defamation not specifically directed", 
            summary:"Warning: Defamation not specifically directed" 
        },
        "uw-uncen3": { 
            label:"Censorship of material", 
            summary:"Warning: Censorship of material" 
        },
        "uw-mos3": { 
            label:"Manual of style", 
            summary:"Warning: Formatting, date, language, etc (Manual of style)" 
        },
        "uw-move3": { 
            label:"Page moves", 
            summary:"Warning: Page moves" 
        },
        "uw-chat3": { 
            label:"Using talk page as forum", 
            summary:"Warning: Using talk page as forum" 
        },
        "uw-tpv3": { 
            label:"Refactoring others' talk page comments", 
            summary:"Warning: Refactoring others' talk page comments" 
        },
        "uw-afd3": { 
            label:"Removing \{\{afd\}\} templates", 
            summary:"Warning: Removing \{\{afd\}\} templates" 
        },
        "uw-speedy3": { 
            label:"Removing \{\{speedy deletion\}\} templates", 
            summary:"Warning: Removing \{\{speedy deletion\}\} templates" 
        },
        "uw-npa3": { 
            label:"Personal attack directed at a specific editor", 
            summary:"Warning: Personal attack directed at a specific editor" 
        },
        "uw-agf3": { 
            label:"Not assuming good faith", 
            summary:"Warning: Not assuming good faith" 
        },
        "uw-own3": { 
            label:"Ownership of articles", 
            summary:"Warning: Ownership of articles"
        },
        "uw-nor3": { 
            label:"Adding original research", 
            summary:"Warning: Adding original research, including unpublished syntheses of sourced material"
        }
    },
    level4: {
        "uw-vandalism4": { 
            label:"Vandalism", 
            summary:"Final warning: Vandalism" 
        },
        "uw-delete4": { 
            label:"Page blanking, removal of content or templates", 
            summary:"Final warning: Page blanking, removal of content or templates" 
        },
        "uw-joke4": { 
            label:"Using improper humor", 
            summary:"Final warning: Using improper humor" 
        },
        "uw-create4": { 
            label:"Creating inappropriate pages", 
            summary:"Final warning: Creating inappropriate pages" 
        },
        "uw-upload4": { 
            label:"Uploading inappropriate images", 
            summary:"Final warning: Uploading inappropriate images" 
        },
        "uw-image4": { 
            label:"Image-related vandalism", 
            summary:"Final warning: Image-related vandalism" 
        },
        "uw-spam4": { 
            label:"Adding spam links", 
            summary:"Final warning: Adding spam links" 
        },
        "uw-advert4": { 
            label:"Using Wikipedia for advertising or promotion", 
            summary:"Final warning: Using Wikipedia for advertising or promotion" 
        },
        "uw-npov4": { 
            label:"Not adhering to neutral point of view", 
            summary:"Final warning: Not adhering to neutral point of view" 
        },
        "uw-biog4": { 
            label:"Adding unreferenced controversial information about living persons", 
            summary:"Final warning: Adding unreferenced controversial information about living persons" 
        },
        "uw-defam4": { 
            label:"Defamation not specifically directed", 
            summary:"Final warning: Defamation not specifically directed" 
        },
        "uw-move4": { 
            label:"Page moves", 
            summary:"Final warning: Page moves" 
        },
        "uw-chat4": { 
            label:"Using talk page as forum", 
            summary:"Final warning: Using talk page as forum" 
        },
        "uw-afd4": { 
            label:"Removing \{\{afd\}\} templates", 
            summary:"Final warning: Removing \{\{afd\}\} templates" 
        },
        "uw-speedy4": { 
            label:"Removing \{\{speedy deletion\}\} templates", 
            summary:"Final warning: Removing \{\{speedy deletion\}\} templates" 
        },
        "uw-npa4": { 
            label:"Personal attack directed at a specific editor", 
            summary:"Final warning: Personal attack directed at a specific editor"
        },
        "uw-nor4": { 
            label:"Adding original research", 
            summary:"Final Warning: Adding original research, including unpublished syntheses of sourced material"
        }
    },
    level4im: {
        "uw-vandalism4im": { 
            label:"Vandalism", 
            summary:"Only warning: Vandalism" 
        },
        "uw-delete4im": { 
            label:"Page blanking, removal of content or templates", 
            summary:"Only warning: Page blanking, removal of content or templates" 
        },
        "uw-create4im": { 
            label:"Creating inappropriate pages", 
            summary:"Only warning: Creating inappropriate pages" 
        },
        "uw-upload4im": { 
            label:"Uploading inappropriate images", 
            summary:"Only warning: Uploading inappropriate images" 
        },
        "uw-image4im": { 
            label:"Image-related vandalism", 
            summary:"Only warning: Image-related vandalism" 
        },
        "uw-spam4im": { 
            label:"Adding spam links", 
            summary:"Only warning: Adding spam links" 
        },
        "uw-defam4im": { 
            label:"Defamation not specifically directed", 
            summary:"Only warning: Defamation not specifically directed" 
        },
        "uw-move4im": { 
            label:"Page moves", 
            summary:"Only warning: Page moves" 
        },
        "uw-npa4im": { 
            label:"Personal attack directed at a specific editor", 
            summary:"Only warning: Personal attack directed at a specific editor"
        }
    },
    singlenotice: {
        "uw-2redirect": { 
            label:"Creating double redirects through bad page moves", 
            summary:"Notice: Creating double redirects through bad page moves" 
        },
        "uw-aiv": { 
            label:"Bad AIV report", 
            summary:"Notice: Bad AIV report" 
        },
        "uw-articlesig": { 
            label:"Adding signatures to article space", 
            summary:"Notice: Adding signatures to article space" 
        },
        "uw-autobiography": { 
            label:"Creating autobiographies", 
            summary:"Notice: Creating autobiographies" 
        },
        "uw-badcat": { 
            label:"Adding incorrect categories", 
            summary:"Notice: Adding incorrect categories" 
        },
        "uw-bite": { 
            label:"\"Biting\" newcomers", 
            summary:"Notice: \"Biting\" newcomers" 
        },
        "uw-coi": { 
            label:"Conflict of Interest", 
            summary:"Notice: Conflict of Interest" 
        },
        "uw-c&pmove": { 
            label:"Cut and paste moves", 
            summary:"notice: Cut and paste moves" 
        },
        "uw-date": { 
            label:"Unnecessarily changing date formats", 
            summary:"Notice: Unnecessarily changing date formats" 
        },
        "uw-deadlink": { 
            label:"Removing proper sources containing dead links", 
            summary:"Notice: Removing proper sources containing dead links" 
        },
        "uw-editsummary": { 
            label:"Not using edit summary", 
            summary:"Notice: Not using edit summary" 
        },
        "uw-english": { 
            label:"Not communicating in English", 
            summary:"Notice: Not communicating in English" 
        },
        "uw-hangon": { 
            label:"User forgets to place a hang-on reasoning to the talk page", 
            summary:"Notice: User forgets to place a hang-on reasoning to the talk page" 
        },
        "uw-italicize": { 
            label:"Italicize books, films, albums, magazines, TV series, etc within articles", 
            summary:"Notice: Italicize books, films, albums, magazines, TV series, etc within articles" 
        },
        "uw-lang": { 
            label:"Unnecessarily changing between British and American English", 
            summary:"Notice: Unnecessarily changing between British and American English" 
        },
        "uw-linking": { 
            label:"For excessive addition of redlinks or repeated blue links", 
            summary:"Notice: For excessive addition of redlinks or repeated blue links" 
        },
        "uw-minor": { 
            label:"Incorrect use of minor edits check box", 
            summary:"Notice: Incorrect use of minor edits check box" 
        },
        "uw-nonfree": { 
            label:"Uploading replaceable non-free images", 
            summary:"Notice: Uploading replaceable non-free images" 
        },
        "uw-notaiv": { 
            label:"Do not report complex abuse to AIV", 
            summary:"Notice: Do not report complex abuse to AIV" 
        },
        "uw-notvote": { 
            label:"We use consensus, not voting", 
            summary:"Notice: We use consensus, not voting" 
        },
        "uw-preview": { 
            label:"Use preview button to avoid mistakes", 
            summary:"Notice: Use preview button to avoid mistakes" 
        },
        "uw-selfrevert": { 
            label:"Reverting self tests", 
            summary:"Notice: Reverting self tests" 
        },
        "uw-samename": { 
            label:"Rename request impossible", 
            summary:"Notice: Rename request impossible"
        },
        "uw-sandbox": { 
            label:"Removal of the Sandbox header", 
            summary:"Notice: Removal of the Sandbox header" 
        },
        "uw-spellcheck": { 
            label:"Review spelling, etc.", 
            summary:"Notice: Review spelling, etc." 
        },
        "uw-socialnetwork": { 
            label:"Wikipedia is not a social network", 
            summary:"Notice: Wikipedia is not a social network" 
        },
        "uw-subst": { 
            label:"Remember to subst: templates", 
            summary:"Notice: Remember to subst: templates" 
        },
        "uw-talkinarticle": { 
            label:"Talk in article", 
            summary:"Notice: Talk in article" 
        },
        "uw-tilde": { 
            label:"Not signing posts", 
            summary:"Notice: Not signing posts" 
        },
        "uw-uaa": { 
            label:"Reporting of username to WP:UAA not accepted", 
            summary:"Notice: Reporting of username to WP:UAA not accepted" 
        },
        "uw-warn": { 
            label:"Warning vandals", 
            summary:"Notice: Warning vandals"
        }
    },
    singlewarn: {
        "uw-3rr": { 
            label:"Potentially violating the three revert rule", 
            summary:"Warning: Potentially violating the three revert rule" 
        },/*
        "uw-attack": { 
            label:"Creating attack pages", 
            summary:"Warning: Creating attack pages" 
        },*/
        "uw-bv": { 
            label:"Blatant vandalism", 
            summary:"Warning: Blatant vandalism" 
        },
        "uw-canvass": { 
            label:"Canvassing", 
            summary:"Warning: Canvassing" 
        },
        "uw-copyright": { 
            label:"Copyright violation", 
            summary:"Warning: Copyright violation" 
        },
        "uw-copyright-link": { 
            label:"Linking to copyrighted works violation", 
            summary:"Warning: Linking to copyrighted works violation" 
        },
        "uw-hoax": { 
            label:"Creating hoaxes", 
            summary:"Warning: Creating hoaxes" 
        },
        "uw-legal": { 
            label:"Making legal threats", 
            summary:"Warning: Making legal threats" 
        },
        "uw-longterm": { 
            label:"Long term pattern of vandalism", 
            summary:"Warning: Long term pattern of vandalism" 
        },
        "uw-multipleIPs": { 
            label:"Usage of multiple IPs", 
            summary:"Warning: Usage of multiple IPs" 
        },
        "uw-pinfo": { 
            label:"Personal info", 
            summary:"Warning: Personal info" 
        },
        "uw-redirect": { 
            label:"Creating malicious redirects", 
            summary:"Warning: Creating malicious redirects"
        },
        "uw-upv": { 
            label:"Userpage vandalism", 
            summary:"Warning: Userpage vandalism"
        },
        "uw-tempabuse": { 
            label:"Improper use of warning or blocking template", 
            summary:"Warning: Improper use of warning or blocking template"
        },
        "uw-trivia": { 
            label:"Adding useless trivia", 
            summary:"Warning: Adding useless trivia"
        },
        "uw-wrongsummary": { 
            label:"Using inaccurate or inappropriate edit summaries", 
            summary:"Warning: Using inaccurate or inappropriate edit summaries"
        },
        "uw-username": { 
            label:"Username is against policy", 
            summary:"Warning: Username is against policy"
        },
        "uw-userpage": { 
            label:"Userpage or subpage is against policy", 
            summary:"Warning: Userpage or subpage is against policy"
        },
        "uw-ra": { 
            label:"Racially motivated edit", 
            summary:"Warning: Racially motivated edit"
        }
    },
    block: {
        "uw-block1": {
            'label':"Block level 1",
            'summary':"You have been temporarily blocked"
        },
        "uw-block2": {
            'label':"Block level 2",
            'summary':"You have been blocked"
        },
        "uw-block3": {
            'label':"Block level 3",
            'summary':"You have been indefinitely blocked"
        },
        "uw-ablock": {
            'label':"Anonymous block",
            'summary':"Your IP address has been blocked"
        },
        "uw-sblock": {
            'label':"Spam block",
            'summary':"You have been blocked for spamming"
        },
        "uw-vblock": {
            'label':"Vandalism",
            'summary':"You have been blocked for vandalism"
        },
        "uw-voablock": {
            'label':"Vandalism-only account",
            'summary':"You have been blocked for using a vandalism-only account"
        },
        "uw-dblock": {
            'label':"Delete block",
            'summary':"You have been blocked for deletion"
        },
        "uw-3block": {
            'label':"3RR block",
            'summary':"You have been blocked for violation of the [[WP:3RR|3RR]] rule"
        },
        "uw-ublock": {
            'label':"Username block",
            'summary':"You have been blocked for violation of the [[WP:U|username policy]]"
        },
        "uw-uhblock": {
            'label':"Username hard block",
            'summary':"You have been blocked for blatant violation of the [[WP:U|username policy]]"
        },
        "uw-lblock": {
            'label':"Legal Threat Block",
            'summary':"You have been blocked for [[Wikipedia:No legal threats|making legal threats]]"
        },
        "uw-hblock": {
            'label':"Harassment Block",
            'summary':"You have been blocked for attempting to [[Wikipedia:Harassment|harass]] other users"
        },
        "uw-npblock": {
            'label':"Creating Nonsense Pages Block",
            'summary':"You have been blocked for [[Wikipedia:Patent_nonsense|creating nonsense pages]]"
        }
    }
};
 
 
twinklewarn.callback.change_category = function twinklewarnCallbackChangeCategory(e) {
    var value = e.target.value;
    var sub_group = e.target.root.sub_group;
    var messages = twinklewarn.messages[ value ];
    sub_group.main_group = value;
    var old_subvalue = sub_group.value;
    if( old_subvalue ) {
        old_subvalue = old_subvalue.replace(/\d*(im)?$/, '' );
        var old_subvalue_re = new RegExp( RegExp.escape( old_subvalue ) + "(\\d*(?:im)?)$" );
    }
 
    while( sub_group.hasChildNodes() ){
        sub_group.removeChild( sub_group.firstChild );
    }
 
    for( var i in messages ) {
        var selected = false;
        if( old_subvalue && old_subvalue_re.test( i ) ) {
            selected = true;
        }
        var elem = new QuickForm.element( { type:'option', label:"[" + i + "]: " + messages[i].label, value:i, selected: selected } );
 
        sub_group.appendChild( elem.render() );
    }
 
    if( value == 'block' ) {
        var more = new QuickForm.element( {
                type: 'input',
                name: 'block_timer',
                label: 'Period of blocking: ',
                tooltip: 'The period the blocking is due for, for example 24 hours, 2 weeks, indefinite etc...'
            } );
        e.target.root.insertBefore( more.render(), e.target.root.lastChild );
        e.target.root.article.disabled = true;
    } else if( e.target.root.block_timer ) {
        e.target.root.removeChild( e.target.root.block_timer.parentNode );
        e.target.root.article.disabled = false;
    }
}
 
twinklewarn.callbacks = {
    main: function( self ) {
        var form = self.responseXML.getElementById( 'editform' );
        var text = form.wpTextbox1.value;
 
        var history_re = /\<\!\-\-\ Template\:(uw\-.*?)\ \-\-\>.*?(\d{1,2}:\d{1,2}, \d{1,2} \w+ \d{4}) \(UTC\)/g;
        var history = {};
        var latest = { date:new Date( 0 ), type:'' };
 
        var current;
 
 
        while( ( current = history_re.exec( text ) ) != undefined ) {
            var current_date = new Date( current[2] + ' UTC' );
            if( !( current[1] in history ) ||  history[ current[1] ] < current_date ) {
                history[ current[1] ] = current_date;
            }
            if( current_date > latest.date ) {
                latest.date = current_date;
                latest.type = current[1];
            }
        }
 
        var date = new Date();
 
        if( self.params.sub_group in history ) {
            var temp_time = new Date( history[ self.params.sub_group ] );
            temp_time.setUTCHours( temp_time.getUTCHours() + 24 );
 
            if( temp_time > date ) {
                Status.info( 'Info', "an identical " + self.params.sub_group + " has been issued in the last 24 hours" );
                if( !confirm( "Will you still add a warning/notice?" ) ) {
                    self.statelem.info( 'aborted per user request' );
                    return;
                }
            }
        }
 
        latest.date.setUTCMinutes( latest.date.getUTCMinutes() + 1 ); // after long debate, one minute is max
 
        if( latest.date > date ) {
            Status.info('Info', "a " + latest.type + " has been issued in the last minute" );
                if( !confirm( "Will you still add a warning/notice?" ) ) {
                    self.statelem.info( 'aborted per user request' );
                    return;
                }
        }
 
 
 
        var mainheaderRe = /==+\\s*Warnings\\s*==+/;
        var headerRe = new RegExp( "^==+\\s*(?:" + date.getUTCMonthName() + '|' + date.getUTCMonthNameAbbrev() +  ")\\s+" + date.getUTCFullYear() + "\\s*==+", 'm' );
 
        if( text.length > 0 ) {
            text += "\n";
        }
 
        if( !headerRe.exec( text ) ) {
            Status.info( 'Info', 'Will create a new level 2 heading for the date, as none was found for this month' );
            text += "== " + date.getUTCMonthName() + " " + date.getUTCFullYear() + " ==\n";
        }
        if( self.params.main_group == 'block' ) {
            var time = null;
            if( /te?mp|^\s*$|min/.exec( self.params.block_timer ) ) {
                time = '';
            } else if( /indef|\*|max/.exec( self.params.block_timer ) ) {
                time = '|indef=yes';
            } else {
                time = '|time=' + self.params.block_timer;
            }
 
            text += "\{\{subst:" + self.params.sub_group + time + (self.params.reason ? '|reason=' + self.params.reason : '' ) + "|sig=true\}\}";
        } else {
            text += "\{\{subst:" + self.params.sub_group + ( self.params.article ? '|' + self.params.article : '' ) + "\}\}" + (self.params.reason ? " ''" + self.params.reason + "'' ": ' ' ) + "\~\~\~";
        }
 
        if ( TwinkleConfig.showSharedIPNotice && isIPAddress( wgTitle ) ) {
            Status.info( 'Info', 'Adding a shared ip notice' );
            switch( QueryString.get( 'type' ) ) {
            case 'vand':
                text +=  "\n:''If this is a shared [[IP address]], and you didn't make any [[Wikipedia:vandalism|unconstructive]] edits, consider [[Wikipedia:Why create an account?|creating an account]] for yourself so you can avoid further irrelevant warnings.'' ";
                break;
            default:
                text +=  "\n:''If this is a shared [[IP address]], and you didn't make the edit, consider [[Wikipedia:Why create an account?|creating an account]] for yourself so you can avoid further irrelevant notices.'' ";
                break;
            }
        }
        var postData = {
            'wpMinoredit': form.wpMinoredit.checked ? 1 : undefined,
            'wpWatchthis': TwinkleConfig.watchWarnings ? 1 : form.wpWatchthis.checked ? 1 : undefined,
            'wpStarttime': form.wpStarttime.value,
            'wpEdittime': form.wpEdittime.value,
            'wpAutoSummary': form.wpAutoSummary.value,
            'wpEditToken': form.wpEditToken.value,
            'wpSummary': twinklewarn.messages[self.params.main_group][self.params.sub_group].summary + ( self.params.article ? ' on [[' + self.params.article + ']]'  : '' ) + '.' + TwinkleConfig.summaryAd,
            'wpTextbox1': text
        };
 
        self.post( postData );
    }
}
 
twinklewarn.callback.evaluate = function twinklewarnCallbackEvaluate(e) {
 
    // First, grab all the values provided by the form
 
    var params = {
        reason: e.target.reason.value,
        main_group: e.target.main_group.value,
        sub_group: e.target.sub_group.value,
        article: e.target.article.value.replace( /^(Image|Category):/i, ':$1:' ),
        block_timer: e.target.block_timer ? e.target.block_timer.value : null
    }
 
    Status.init( e.target );
 
    var query = { 
        'title': wgPageName, 
        'action': 'submit'
    };
    Wikipedia.actionCompleted.redirect = wgPageName;
    Wikipedia.actionCompleted.notice = "Warning complete, reloading talk page in some seconds";
    var wikipedia_wiki = new Wikipedia.wiki( 'User talk page modification', query, twinklewarn.callbacks.main );
    wikipedia_wiki.params = params;
    wikipedia_wiki.get();
}
 
// If TwinkleConfig aint exist.
if( typeof( TwinkleConfig ) == 'undefined' ) {
    TwinkleConfig = {};
}
 
/**
 TwinkleConfig.summaryAd (string)
 If ad should be added or not to summary, default [[WP:TWINKLE|TWINKLE]]
 */
if( typeof( TwinkleConfig.summaryAd ) == 'undefined' ) {
    TwinkleConfig.summaryAd = " using [[WP:TW|TW]]";
}
 
/**
 TwinkleConfig.markAIVReportAsMinor (boolean)
 Defines if a reports to AIV should be marked as minor, if false, default is applied as per preference.
 */
if( typeof( TwinkleConfig.markAIVReportAsMinor ) == 'undefined' ) {
    TwinkleConfig.markAIVReportAsMinor = true;
}
 
/**
 TwinkleConfig.confirmUsernameToAIV (boolean) (deprecated)
 Defines if a username reports to AIV should be confirmed before sent.
 */
if( typeof( TwinkleConfig.confirmUsernameToAIV ) == 'undefined' ) {
    TwinkleConfig.confirmUsernameToAIV = true;
}
 
/**
 TwinkleConfig.toolboxButtons (string)
 If id defined in this array, the button of the action is located inthe toolbox instead of in
 the actions bar.
 */
if( typeof( TwinkleConfig.toolboxButtons ) == 'undefined' ) {
    TwinkleConfig.toolboxButtons = [];
}
 
function getChecked( nodelist ) {
    if( !( nodelist instanceof NodeList ) ) {
        throw nodelist + " not instance of NodeList";
    }
    var result = [];
    for(var i  = 0; i < nodelist.length; ++i ) {
        if( nodelist[i].checked ) {
            result.push( nodelist[i].value );
        }
    }
    return result;
}
 
function getTexts( nodelist ) {
    if ( nodelist instanceof HTMLInputElement ) {
        return [ nodelist.value ];
    }
    if( !( nodelist instanceof NodeList ) ) {
        throw nodelist + " not instance of NodeList";
    }
    var result = [];
    for(var i = 0; i < nodelist.length; ++i ) {
        if( nodelist[i].type == 'text' && nodelist[i].value != '' ) {
            result.push( nodelist[i].value );
        }
    }
    return result;
}
 
function num2order( num ) {
    switch( num ) {
    case 1: return '';
    case 2: return '2nd';
    case 3: return '3rd';
    default: return num + 'th';
    }
}
 
addOnloadHook( twinklearv );
function twinklearv(){
    var username;
 
 
    if ( wgNamespaceNumber == 3 || wgNamespaceNumber == 2 || ( wgNamespaceNumber == -1 && wgTitle == "Contributions" )){
 
        // If we are on the contributions page, need to parse some then
        if( wgNamespaceNumber == -1 && wgTitle == "Contributions" ) {
            var href = document.evaluate( '//div[@id="contentSub"]//a/@href', document, null, XPathResult.STRING_TYPE, null).stringValue;
            var queryString = new QueryString( href.replace( /^.*\?/, '' ) );
            if( queryString.exists( 'title' ) ) {
                username =  queryString.get('title');
            } else {
                username = href.split( wgArticlePath.replace('$1','') )[1];
            }
        } else {
            username = wgTitle.split( '/' )[0].replace( /\"/, "\\\""); // only first part before any slashes
        }
 
        if( !username ) {
            // Something is fishy, there was no user? lets about everything
            throw "given username was " + username + " and thus makes no sense.";
        }
 
        username = username.replace( /^.*?\:/, '' );
 
        var name = isIPAddress( username ) ? 'Report IP' : 'Report';
        var title =  isIPAddress( username ) ? 'Report IP to Administators' : 'Report user to Administrators';
        if (twinkleConfigExists)
        {
            addPortletLink( 'p-cactions', "javascript:twinklearv.callback(\"" + username + "\")", "arv", "tw-arv", name, title );
        }
        else
        {
            addPortletLink('p-cactions', 'javascript:alert("Your account is too new to use Twinkle.");', 'arv', 'tw-arv', name, title);
        }
    }
}
 
twinklearv.callback = function twinklearvCallback( uid ) {
    if( uid == wgUserName ){
        alert( 'You don\'t want to report yourself , do you?' );
        return;
    }
 
    var Window = new SimpleWindow( 600, 400 );
    Window.setTitle( "Advance Reporting and Vetting" ); //Backronym
 
    var form = new QuickForm( twinklearv.callback.evaluate );
    var categories = form.append( {
            type: 'select',
            name: 'category',
            label: 'Select wanted type of report: ',
            event: twinklearv.callback.change_category
        } );
    categories.append( {
            type: 'option',
            label: 'Vandalism',
            value: 'aiv'
        } );
    categories.append( {
            type: 'option',
            label: 'Username',
            value: 'username'
        } );
    categories.append( {
            type: 'option',
            label: 'Sockpuppeter',
            value: 'sock'
        } );
 
    form.append( {
            type: 'field',
            label:'Work area',
            name: 'work_area'
        } );
    form.append( {
            type: 'hidden',
            name: 'uid',
            value: uid
        } );
 
    var result = form.render();
    Window.setContent( result );
    Window.display();
 
    // We must init the
    var evt = document.createEvent( "Event" );
    evt.initEvent( 'change', true, true );
    result.category.dispatchEvent( evt );
 
}
 
twinklearv.callback.change_category = function twinklearvCallbackChangeCategory(e) {
    var value = e.target.value;
    var root = e.target.form;
    var old_area;
    for( var i = 0; i < root.childNodes.length; ++i ) {
        var node = root.childNodes[i];
        if( 
            node instanceof Element &&
            node.getAttribute( 'name' ) == 'work_area' 
        ) {
            old_area = node;
            break;
        }
    }
    var work_area = null;
 
    switch( value ) {
    default:
    case 'aiv':
        work_area = new QuickForm.element( { 
                type: 'field',
                label: 'Report user for vandalism',
                name: 'work_area'
            } );
        work_area.append( {
                type: 'input',
                name: 'page',
                label: 'Primary linked page: ',
                tooltip: 'Leave blank for no linked page in report',
                value: QueryString.exists( 'vanarticle' ) ? QueryString.get( 'vanarticle' ) : '',
                event: function(e) {
                    var value = e.target.value;
                    var root = e.target.form;
                    if( value == '' ) {
                        root.badid.disabled = root.goodid.disabled = true;
                    } else {
                        root.badid.disabled = false;
                        root.goodid.disabled = root.badid.value == '';
                    }
                }
            } );
        work_area.append( {
                type: 'input',
                name: 'badid',
                label: 'Revision ID for target page when vandalised: ',
                tooltip: 'Leave blank for no diff link',
                value: QueryString.exists( 'vanarticlerevid' ) ? QueryString.get( 'vanarticlerevid' ) : '',
                disabled: !QueryString.exists( 'vanarticle' ),
                event: function(e) {
                    var value = e.target.value;
                    var root = e.target.form;
                    root.goodid.disabled = value == '';
                }
            } );
        work_area.append( {
                type: 'input',
                name: 'goodid',
                label: 'Last good revision ID before vandalism of target page: ',
                tooltip: 'Leave blank for diff link to previous revision',
                value: QueryString.exists( 'vanarticlegoodrevid' ) ? QueryString.get( 'vanarticlegoodrevid' ) : '',
                disabled: !QueryString.exists( 'vanarticle' ) || QueryString.exists( 'vanarticlerevid' )
            } );
        work_area.append( {
                type: 'checkbox',
                name: 'arvtype',
                list: [
                    { 
                        label: 'Vandalism after final warning given',
                        value: 'final'
                    },
                    { 
                        label: 'Vandalism after recent release of block',
                        value: 'postblock'
                    },
                    { 
                        label: 'Evidently vandalism only account',
                        value: 'vandalonly',
                        disabled: isIPAddress( root.uid.value )
                    },
                    { 
                        label: 'Account is evidently a spambot or a compromised account',
                        value: 'spambot'
                    }
                ]
            } );
        work_area.append( {
                type: 'textarea',
                name: 'reason',
                label: 'Comment: '
            } );
        work_area.append( { type:'submit' } );
        work_area = work_area.render();
        old_area.parentNode.replaceChild( work_area, old_area );
        break;
    case 'username':
        work_area = new QuickForm.element( { 
                type: 'field',
                label: 'Report username violation',
                name: 'work_area'
            } );
        var types = work_area.append( {
                type: 'field',
                label: 'Type of violation',
                tooltip: 'A valid report must include at least one of following types'
            } );
 
        types.append ( { 
                type:'header', 
                label:'Confusing usernames',
                tooltip: 'Confusing usernames that make it unduly difficult to identify users by their username'
            } );
        types.append( {
                type: 'checkbox',
                name: 'arvtype',
                list: [
                    { 
                        label: 'Confusing username',
                        value: 'confusing',
                        tooltip: 'Confusing usernames make it unnecessarily difficult to identify contributors'
                    },
                    {
                        label: 'Misleading username',
                        value: 'misleading',
                        tooltip: 'Misleading usernames imply relevant, misleading things about the user, such as falsely conveying authority or impersonating another user.'
                    },
                    { 
                        label: 'Promotional username',
                        value: 'promotional',
                        tooltip: 'Promotional usernames are used to promote a group or company on Wikipedia.'
                    },
                    { 
                        label: 'Offensive username',
                        value: 'offensive',
                        tooltip: 'Offensive usernames make harmonious editing difficult or impossible.'
                    },
                    { 
                        label: 'Disruptive username',
                        value: 'disruptive',
                        tooltip: 'Disruptive usernames that disrupt or misuse Wikipedia, or imply an intent to do so'
                    }
                ]
            } );
        work_area.append( {
                type: 'textarea',
                name: 'reason',
                label: 'Comment:'
            } );
        work_area.append( { type:'submit' } );
        work_area = work_area.render();
        old_area.parentNode.replaceChild( work_area, old_area );
        break;
 
    case 'sock':
        work_area = new QuickForm.element( { 
                type: 'field',
                label: 'Report suspected sockpuppeter',
                name: 'work_area'
            } );
        var sock_area = work_area.append( { type:'div' } );
        sock_area.append( {
                type: 'button',
                label: 'More socks',
                name: 'more_socks_button',
                event: function (e){
                    var area = e.target.parentNode.parentNode;
                    var new_node = new QuickForm.element( {
                            type: 'input',
                            label: 'Sockpuppet: ',
                            name: 'sockpuppet'
                        } );
                    if( area.childNodes.length > 1 ) {
                        new_node.append( {
                                type: 'button',
                                label: 'remove',
                                event: function (e){
                                    var node_to_remove = e.target.parentNode.parentNode;
                                    node_to_remove.parentNode.removeChild( node_to_remove );
                                }
                            } );
                    }
                    area.insertBefore( new_node.render(), area.lastChild );
                }
            } );
 
        work_area.append( {
                type: 'textarea',
                label: 'Evidence:',
                name: 'evidence'
            } );
        work_area.append( { type:'submit' } );
        work_area = work_area.render();
        old_area.parentNode.replaceChild( work_area, old_area );
 
        var evt = document.createEvent( "MouseEvent" );
        evt.initEvent( 'click', true, true );
        work_area.form.more_socks_button.dispatchEvent( evt );
        break;
    }
}
 
twinklearv.callbacks = {
    aiv: function( self ) {
        uid = self.params.uid;
        reason = self.params.reason;
        var form = self.responseXML.getElementById('editform');
 
        if( !form ) {
            self.statelem.error( 'Failed to retrieve edit form.' );
            return;
        }
        var text = form.wpTextbox1.value;
 
        var re = new RegExp( "\\{\\{\\s*(?:(?:[Ii][Pp])?[Vv]andal|[Uu]serlinks)\\s*\\|\\s*(?:1=)?\\s*" + RegExp.escape( uid, true ) + "\\s*\\}\\}" );
 
        var myArr;
        if( ( myArr = re.exec( text ) ) ) {
            self.statelem.info( 'Report already present, will not add a new one' );
            return;
        }
        self.statelem.status( 'Adding new report...' );
        var postData = {
            'wpMinoredit': TwinkleConfig.markAIVReportAsMinor ? '' : form.wpMinoredit.checked ? '' : undefined, 
            'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
            'wpStarttime': form.wpStarttime.value,
            'wpEdittime': form.wpEdittime.value,
            'wpAutoSummary': form.wpAutoSummary.value,
            'wpEditToken': form.wpEditToken.value,
            'wpSummary': 'Reporting [[Special:Contributions/' + uid + '|' + uid + ']].'+ TwinkleConfig.summaryAd,
            'wpTextbox1': text + '*\{\{' + ( isIPAddress( uid ) ? 'IPvandal' : 'vandal' ) + '|' + (/\=/.test( uid ) ? '1=' : '' ) + uid + '\}\} - ' + reason + ' ~~' + '~~'
        };
 
        self.post( postData );
    },
    username: function( self ) {
        uid = self.params.uid;
        reason = self.params.reason;
        var form = self.responseXML.getElementById('editform');
 
        if( !form ) {
            self.statelem.error( 'Failed to retrieve edit form.' );
            return;
        }
        var text = form.wpTextbox1.value;
 
        self.statelem.status( 'Adding new report...' );
        var postData = {
            'wpMinoredit': form.wpMinoredit.checked ? '' : undefined, 
            'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
            'wpStarttime': form.wpStarttime.value,
            'wpEdittime': form.wpEdittime.value,
            'wpAutoSummary': form.wpAutoSummary.value,
            'wpEditToken': form.wpEditToken.value,
            'wpSummary': 'Reporting [[Special:Contributions/' + uid + '|' + uid + ']].'+ TwinkleConfig.summaryAd,
            'wpTextbox1': text.replace( /-->/, "-->\n" + reason.replace( '\$', "$$$$" ) )
        };
        self.post( postData );
    },
    sock: {
        main: function( self ) { 
            var xmlDoc = self.responseXML;
            var titles = xmlDoc.evaluate( '//allpages/p/@title', xmlDoc, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
 
            var number = 0;
            for( var i = 0; i < titles.snapshotLength; ++i ) {
                var title = titles.snapshotItem(i).value;
                title = title.replace( /(first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth|eleventh)/, function(v) {
                        return {
                            'first': '1st',
                            'second': '2nd',
                            'third': '3rd',
                            'fourth': '4th',
                            'fifth': '5th',
                            'sixth': '6th',
                            'seventh': '7th',
                            'eighth': '8th',
                            'ninth': '9th',
                            'tenth': '10th',
                            'eleventh': '11th'
                        }[v];
                    } );
                var n = /\(\s*(\d+)(?:(?:th|nd|rd|st) nom(?:ination)?)?\s*\)\s*$/.exec( title );
                if( n && n[1] > number ) {
                    number = n[1];
                } else if( number == 0 ) {
                    number = 1;
                }
            }
 
            if( number == 0 ) {
                self.params.numbering = self.params.number = '';
                numbering = number = '';
            } else {
                self.params.number = num2order( parseInt( number ) + 1);
                self.params.numbering = ' (' + self.params.number + ' nomination)';
            }
            self.statelem.info( 'next in order is [[Wikipedia:Suspected sock puppets/' + self.params.uid + self.params.numbering + ']]');
 
            var query = {
                'title': 'Wikipedia:Suspected sock puppets/' +  self.params.uid + self.params.numbering,
                'action': 'submit'
            };
 
            var wikipedia_wiki = new Wikipedia.wiki( 'Creating discussion page', query, twinklearv.callbacks.sock.discussionPage );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
 
            var query = {
                'title': 'Wikipedia:Suspected sock puppets',
                'section': 3,
                'action': 'submit'
            };
 
            var wikipedia_wiki = new Wikipedia.wiki( 'Linking report to open cases', query, twinklearv.callbacks.sock.openCases );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
 
            var query = {
                'title': 'User talk:' + self.params.uid,
                'action': 'submit'
            };
 
            var wikipedia_wiki = new Wikipedia.wiki( 'Notifying suspected sockpuppeter', query, twinklearv.callbacks.sock.notifySock );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
 
            var query = {
                'title': 'User:' + self.params.uid,
                'action': 'submit'
            };
 
            var wikipedia_wiki = new Wikipedia.wiki( 'Tag suspected sockpuppeter', query, twinklearv.callbacks.sock.tagSockpuppeter );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
 
 
            var statusIndicator1 = new Status('Tagging suspected sockpuppets', '0%');
            var statusIndicator2 = new Status('Notifying suspected sockpuppets', '0%');
 
            var total = self.params.sockpuppets.length * 2;
 
            var onsuccess = function( self ) {
                var obj = self.params.obj;
                var total = self.params.total;
                var now = parseInt( 100 * ++(self.params.current)/total ) + '%';
                obj.update( now );
                self.statelem.unlink();
                if( self.params.current >= total ) {
                    obj.info( now + ' (completed)' );
                    Wikipedia.removeCheckpoint();
                }
            }
            var onloaded = onsuccess;
 
            var onloading = function( self ) {}
 
            Wikipedia.addCheckpoint();
 
            var params1 = clone( self.params );
            params1.total = total;
            params1.obj = statusIndicator1;
            params1.current =   0;
 
            var params2 = clone( self.params );
            params2.total = total;
            params2.obj = statusIndicator2;
            params2.current =   0;
 
            var socks = self.params.sockpuppets;
            for( var i = 0; i < socks.length; ++i ) {
                var query = {
                    'title': 'User:' + socks[i],
                    'action': 'submit'
                };
                var wikipedia_wiki = new Wikipedia.wiki( "Tagging of " +  socks[i], query, twinklearv.callbacks.sock.tagSockpuppet );
                wikipedia_wiki.params = params1;
                wikipedia_wiki.onloaded = onloaded;
                wikipedia_wiki.onsuccess = onsuccess;
                wikipedia_wiki.get();
                var query = {
                    'title': 'User talk:' + socks[i],
                    'action': 'submit'
                };
                var wikipedia_wiki = new Wikipedia.wiki( "Notification for " +  socks[i], query, twinklearv.callbacks.sock.notifySock );
                wikipedia_wiki.params = params2;
                wikipedia_wiki.onloaded = onloaded;
                wikipedia_wiki.onsuccess = onsuccess;
                wikipedia_wiki.get();
 
            }
        },
        discussionPage: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var text = 
                "===[[User:" + self.params.uid + "]]===\n" +
                ";Suspected sockpuppeteer\n" +
                ":\{\{user5|" + self.params.uid + "\}\}\n\n" +
                ";Suspected sockpuppets\n" + 
                self.params.sockpuppets.map( function(v) { return ":\{\{user5|" + v + "\}\}" } ).join( "\n" ) + "\n\n" +
                ";Report submission by\n" +
                "\~\~\~\n\n" +
                ";Evidence\n" +
                self.params.evidence + "\n\n" +
                ";Comments\n\n\n" +
                ";Conclusions\n\n\n" +
                "----\n</div>\n";
 
 
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Creating report for [[User:" +  self.params.uid + ']].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        },
        openCases: function( self ) {
            var form = self.responseXML.getElementById('editform');
            text = form.wpTextbox1.value.replace( /(<!-- ADD CASES TO THE TOP OF THIS LIST, JUST BELOW THIS LINE\. This tag indicates the top of the list\. -->)/, "$1\n\{\{Wikipedia:Suspected sock puppets/" + self.params.uid + self.params.numbering + "\}\}");
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Adding report for [[User:" +  self.params.uid + ']].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
 
            self.post( postData );
        },
        tagSockpuppeter: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var text = form.wpTextbox1.value;
            if( /\{\{sockpuppeteer.*?\}\}/.exec( text ) ) { // already marked as a sock, just ignore then
                self.onsuccess( self );
                Wikipedia.actionCompleted();
                return;
            }
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Adding suspected sockpuppeter tag." + TwinkleConfig.summaryAd,
                'wpTextbox1': "\{\{sockpuppeteer\}\}\n" + text
            };
 
            self.post( postData );
        },
        tagSockpuppet: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var text = form.wpTextbox1.value;
            if( /\{\{sockpuppet.*?\}\}/.exec( text ) ) { // already marked as a sock, just ignore then
                self.onsuccess( self );
                Wikipedia.actionCompleted();
                return;
            }
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Adding suspected sockpuppet tag for suspected sockpuppeter [[User:" +  self.params.uid + ']].' + TwinkleConfig.summaryAd,
                'wpTextbox1': "\{\{subst:sockpuppet|1=" + self.params.uid + "\}\}\n" + text
            };
 
            self.post( postData );
        },
 
        notifySock: function( self ) {
            var form = self.responseXML.getElementById('editform');
            text = form.wpTextbox1.value;
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Notifying about suspicion of sockpuppertering." + TwinkleConfig.summaryAd,
                'wpTextbox1': text + "\n\{\{subst:socksuspectnotice|1=" + self.params.uid + self.params.numbering + "\}\} \~\~\~"
            };
 
            self.post( postData );
        }
    }
}
 
twinklearv.callback.evaluate = function(e) {
    var form = e.target;
    var reason = "";
    if( form.reason ) {
        comment = form.reason.value;
    }
    var uid = form.uid.value;
    switch( form.category.value ) {
    default:
    case 'aiv':
        var types = getChecked( form.arvtype );
        if( types.length == 0 && comment == '' ) {
            alert( 'You must specify some reason' );
            return;
        }
 
        types = types.map( function(v) {
                switch(v) {
                case 'final':
                    return 'vandalism after final warning';
                    break;
                case 'postblock':
                    return 'vandalism directly after release of block';
                    break;
                case 'spambot':
                    return 'account is evidently a spambot or a compromised account';
                    break;
                case 'vandalonly':
                    return 'actions evidently indicate a vandalism only account';
                    break;
                }
            } ).join( ', ' );
 
 
        if( form.page.value != '' ) {
            reason += 'On [[' + form.page.value.replace( /^(Image|Category):/i, ':$1:' ) + ']]';
 
            if( form.badid.value != '' ) {
                var query = {
                    'title': form.page.value,
                    'diff': form.badid.value,
                    'oldid': form.goodid.value
                };
                reason += ' ([' +  wgServer + wgScriptPath + '/index.php?' + QueryString.create( query ) + ' diff])';
            }
            reason += ';';
        }
 
        if( types ) {
            reason += " " + types;
        }
        if (comment != '' ) {
            reason += ". " + comment + '.';
        }
        Status.init( form );
 
        var query = {
            'title': 'Wikipedia:Administrator intervention against vandalism',
            'action': 'submit',
            'section': 1
        };
        wikipedia_wiki = new Wikipedia.wiki( 'Processing AIV request', query, twinklearv.callbacks.aiv );
        wikipedia_wiki.params = { reason:reason, uid:uid };
        wikipedia_wiki.get();
        break;
    case 'username':
        var types = getChecked( form.arvtype );
        if( types.length == 0 ) {
            alert( 'You must specify at least one breached violation' );
            return;
        }
        types = types.map( function( v ) { return v.toLowerCaseFirstChar(); } );
 
        if( types.length <= 2 ) {
            types = types.join( ' and ' );
        } else {
            types = [ types.slice( 0, -1 ).join( ', ' ), types.slice( -1 ) ].join( ', and ' );
        }
        reason = "*\{\{user-uaa|1=" + uid + "\}\} &mdash; Violation of username policy because it's a " + types + " username; ";
        if (comment != '' ) {
            reason += "''" + comment.toUpperCaseFirstChar() + "''. ";
        }
        reason += "\~\~\~";
        Status.init( form );
 
        var query = {
            'title': 'Wikipedia:Usernames for administrator attention',
            'action': 'submit',
            'section': 1
        };
 
        wikipedia_wiki = new Wikipedia.wiki( 'Processing UAA request', query, twinklearv.callbacks.username );
        wikipedia_wiki.params = { reason:reason, uid:uid };
        wikipedia_wiki.get();
        break;
    case 'sock':
        var sockpuppets = getTexts( form.sockpuppet );
        var evidence = form.evidence.value;
        Status.init( form );
 
        var query = {
            'action': 'query',
            'list': 'allpages',
            'apprefix': 'Suspected sock puppets/' + uid,
            'apnamespace': 4,
            'apfilterredir': 'nonredirects',
            'aplimit': userIsInGroup( 'sysop' ) ? 5000 : 500
        };
 
        var wikipedia_api = new Wikipedia.api( 'Quering allpages', query, twinklearv.callbacks.sock.main );
        wikipedia_api.params = { uid:uid, sockpuppets:sockpuppets, evidence:evidence };
        wikipedia_api.post();
    }
}
 
// If TwinkleConfig aint exist.
if( typeof( TwinkleConfig ) == 'undefined' ) {
    TwinkleConfig = {};
}
 
/**
 TwinkleConfig.summaryAd (string)en.wikipedia.org
 If ad should be added or not to summary, default [[WP:TWINKLE|TWINKLE]]
 */
if( typeof( TwinkleConfig.summaryAd ) == 'undefined' ) {
    TwinkleConfig.summaryAd = " using [[WP:TW|TW]]";
}
 
/**
 TwinkleConfig.deletionSummaryAd (string)
 If ad should be added or not to deletion summary, default [[WP:TWINKLE|TWINKLE]]
 */
if( typeof( TwinkleConfig.deletionSummaryAd ) == 'undefined' ) {
    TwinkleConfig.deletionSummaryAd = " using [[WP:TW|TW]]";
}
 
 
/**
 TwinkleConfig.watchSpeedyPages (array)
 What types of actions that should result in forced addition to watchlist
 */
if( typeof( TwinkleConfig.watchSpeedyPages ) == 'undefined' ) {
    TwinkleConfig.watchSpeedyPages = [ 'g3', 'g5', 'g10', 'g11', 'g12' ];
}
 
/**
 TwinkleConfig.markSpeedyPagesAsMinor (boolean)
 If, when applying speedy template to page, to mark the edit as minor, default true
 */
if( typeof( TwinkleConfig.markSpeedyPagesAsMinor ) == 'undefined' ) {
    TwinkleConfig.markSpeedyPagesAsMinor = true;
}
 
/**
 TwinkleConfig.notifyUserOnSpeedyDeletionNomination (array)
 What types of actions that should result that the author of the page should be notified of nomination
 */
if( typeof( TwinkleConfig.notifyUserOnSpeedyDeletionNomination ) == 'undefined' ) {
    TwinkleConfig.notifyUserOnSpeedyDeletionNomination = [ 'g1', 'g2', 'g3', 'g4', 'g10', 'g11', 'g12', 'a1', 'a2', 'a3', 'a5', 'a7', 'i1', 'i2', 'i3', 'i4', 'i5', 'i6', 'i7', 'i8', 'i9', 'i10', 'u3', 't1', 'p2' ];
}
 
/**
 TwinkleConfig.userTalkPageMode may take arguments:
 'window': open a new window, remmenber the opened window
 'tab': opens in a new tab, if possible.
 'blank': force open in a new window, even if a such window exist
 */
if( typeof( TwinkleConfig.userTalkPageMode ) == 'undefined' ) {
    TwinkleConfig.userTalkPageMode = 'window';
}
 
/**
 TwinkleConfig.deleteTalkPageOnDelete
 If talk page if exists should also be deleted (CSD G8) when spedying a page (admin only)
 */
if( typeof( TwinkleConfig.deleteTalkPageOnDelete ) == 'undefined' ) {
    TwinkleConfig.deleteTalkPageOnDelete = false;
}
 
/**
 TwinkleConfig.toolboxButtons (string)
 If id defined in this array, the button of the action is located inthe toolbox instead of in
 the actions bar.
 */
if( typeof( TwinkleConfig.toolboxButtons ) == 'undefined' ) {
    TwinkleConfig.toolboxButtons = [];
}
 
/**
 TwinkleConfig.orphanNormalPagesOnSpeedyDelete (hash)
 Defines if all backlinks to a page should be removed.
 property 'exclude' defined actions not to orphan
 */
if( typeof( TwinkleConfig.orphanBacklinksOnSpeedyDelete ) == 'undefined' ) {
    TwinkleConfig.orphanBacklinksOnSpeedyDelete = { exclude: ['g6'], orphan:true };
}
 
function twinklespeedy() {
    if( wgNamespaceNumber < 0 || wgCurRevisionId == false ) {
        return;
    }
    if( userIsInGroup( 'sysop' ) ) {
        addPortletLink( 'p-cactions', "javascript:twinklespeedy.callback()", "csd", "tw-csd", "Speedy delete according to WP:CSD", "");
    } else if (twinkleConfigExists) {
        addPortletLink( 'p-cactions', "javascript:twinklespeedy.callback()", "csd", "tw-csd", "Request speedy deletion according to WP:CSD", "");
    }
    else
    {
        addPortletLink('p-cactions', 'javascript:alert("Your account is too new to use Twinkle.");', 'csd', 'tw-csd', 'Request speedy deletion according to WP:CSD', '');
    }
}
addOnloadHook(twinklespeedy);
 
twinklespeedy.callback = function twinklespeedyCallback() {
    var Window = new SimpleWindow( 800, 400 );
    Window.setTitle( "Choose criteria for speedy deletion" );
 
    var form = new QuickForm( userIsInGroup( 'sysop' ) ? twinklespeedy.callback.evaluateSysop : twinklespeedy.callback.evaluateUser, 'change' );
    if( userIsInGroup( 'sysop' ) ) {
        form.append( {
                type: 'checkbox',
                list: [
                    {
                        label: 'Tag page only, don\'t delete',
                        value: 'tag_only',
                        name: 'tag_only',
                        tooltip: 'If you just want to tag the page, instead of deleting it now',
                        event: function( event ) {
                            event.target.form.notify.disabled = ! event.target.checked;
                            event.stopPropagation();
                        }
                    },
                    {
                        label: 'Orphan backlinks',
                        value: 'orphan_backlinks',
                        name: 'orphan_backlinks',
                        tooltip: 'If you want to orphan all backlinks to current page, if checked, excludes will still apply.',
                        checked: TwinkleConfig.orphanBacklinksOnSpeedyDelete.orphan,
                        event: function( event ) {
                            TwinkleConfig.orphanBacklinksOnSpeedyDelete.orphan = event.target.checked;
                            event.stopPropagation();
                        }
                    }
                ]
            } );
    }
 
    form.append( {
            type: 'checkbox',
            list: [
                {
                    label: 'Notify if possible',
                    value: 'notify',
                    name: 'notify',
                    tooltip: 'If a notification if defined in the configuration, then notify if this is true, else no notify.',
                    checked: true,
                    disabled: userIsInGroup( 'sysop' ),
                    event: function( event ) {
                        event.stopPropagation();
                    }
                }
            ]
        }
    );
    if( wgNamespaceNumber ==  Namespace.IMAGE ) {
        form.append( {type:'header', label:'Images/Media' } );
        form.append ( {
                type: 'radio',
                name: 'csd',
                list: [
                    { 
                        label: 'I1: Redundant image',
                        value: 'redundantimage',
                        tooltip: 'Any image that is a redundant copy, in the same image file format and same or lower resolution, of something else on Wikipedia. Likewise, other media that is a redundant copy, in the same format and of the same or lower quality. This does not apply to images duplicated on Wikimedia Commons, because of licence issues; these should be tagged with \{\{subst:ncd|Image:newname.ext\}\} or \{\{subst:ncd\}\} instead' 
                    },
                    { 
                        label: 'I2: Corrupt or empty image',
                        value: 'noimage', 
                        tooltip: 'Before deleting this type of image, verify that the MediaWiki engine cannot read it by previewing a resized thumbnail of it. This also includes empty (i.e., no content) image description pages for Commons images' 
                    },
                    { 
                        label: 'I3: Improper license',
                        value: 'noncom',
                        tooltip: '"Images licensed as "for non-commercial use only", "non-derivative use" or "used with permission" that were uploaded on or after 2005-05-19, except where they have been shown to comply with the limited standards for the use of non-free content. This includes images licensed under a "Non-commercial Creative Commons License". Such images uploaded before 2005-05-19 may also be speedily deleted if they are not used in any articles'
                    },
                    {
                        label: 'I4: Lack of licensing information', 
                        value: 'unksource',
                        tooltip: 'Images in category "Images with unknown source", "Images with unknown copyright status", or "Images with no copyright tag" that have been tagged with a template that places them in the category for more than seven days, regardless of when uploaded. Note, users sometimes specify their source in the upload summary, so be sure to check the circumstances of the image'
                    },
                    {
                        label: 'I5: Unused unfree copyrighted images',
                        value: 'unfree',
                        tooltip: 'Images and other media that are not under a free license or in the public domain that are not used in any article and that have been tagged with a template that places them in a dated subcategory of Category:Orphaned fairuse images for more than seven days. Reasonable exceptions may be made for images uploaded for an upcoming article. Use \{\{subst:orfud\}\} to tag images for forthcoming deletion' 
                    },
                    {
                        label: 'I6: Missing fair-use rationale',
                        value: 'norat',
                        tooltip: 'Any image or media without a fair use rationale may be deleted seven days after it is uploaded. Boilerplate fair use templates do not constitute a fair use rationale. Images and other media uploaded before 2006-05-04 should not be deleted immediately; instead, the uploader should be notified that a fair-use rationale is needed. Images or other media uploaded after 2006-05-04 can be tagged with \{\{subst:nrd\}\}, and the uploader notified with \{\{subst:missing rationale|Image:image name\}\}. Such images can be found in the dated subcategories of Category:Images with no fair use rationale'
                    },
                    { 
                        label: 'I7: Invalid fair-use claim',
                        value: 'badfairuse', 
                        tooltip: 'Any image or media with a clearly invalid fair-use tag (such as a \{\{logo\}\} tag on a photograph of a mascot) may be deleted at any time. Media that fail any part of the non-free content criteria and were uploaded after 2006-07-13 may be deleted forty-eight hours after notification of the uploader. For media uploaded before 2006-07-13 or tagged with the \{\{Replaceable fair use\}\} template, the uploader will be given seven days to comply with this policy after being notified' 
                    },
                    {
                        label: 'I8: Images available as bit-for-bit identical copies on the Wikimedia Commons',
                        value: 'nowcommons',
                        tooltip: 'Provided the following conditions are met: 1: The image\'s license and source status is beyond reasonable doubt, and the license is undoubtedly accepted at Commons. 2: All information on the image description page is present on the Commons image description page. That includes the complete upload history with links to the uploader\'s local user pages. 3: The image is not protected, and the image description page does not contain a request not to move it to Commons. 4: The image has been marked with Template:NowCommons for at least one week. Waiting one week is not necessary if it was the uploader who moved the image and marked it. 5: If the image is available on Commons under a different name than locally, all local references to the image must be updated to point to the title used at Commons. 6: For \{\{c-uploaded\}\} images: They may be speedily deleted as soon as they are off the Main Page.'
                    },
                    {
                        label: 'I9: Blatant copyright infringement',
                        value: 'imgcopyvio',
                        tooltip: 'The image was copied from a website or other source that does not have a license compatible with Wikipedia, and the uploader does not assert that it is public domain, freely licensed, fair use, or used with permission. Sources that do not have a license compatible with Wikipedia include stock photo libraries such as Getty Images or Corbis. Non-blatant copyright infringements should be discussed at Wikipedia:Images and media for deletion.'
                    },
 {
                        label: 'I10: Unencyclopedic media file',
                        value: 'badfiletype',
                        tooltip: 'The media file is not an image, is not used in any articles and has no reasonable encyclopedic use.'
                    },
 
                ]
            } );
    }
 
    form.append( { type:'header', label:'General criteria' } );
    form.append( {
            type: 'radio',
            name: 'csd',
            list: [
                { 
                    label: 'G1: Nonsense', 
                    value: 'nonsense', 
                    tooltip: 'Patent nonsense and gibberish, an unsalvageably incoherent page with no meaningful content. This does not include: poor writing, partisan screeds, obscene remarks, vandalism, fictional material, material not in English, badly translated material, implausible theories, or hoaxes' },
                { 
                    label: 'G2: Test page',
                    value: 'test',
                    tooltip: 'e.g., "Can I really create a page here?"' 
                },
                { 
                    label: 'G3: Pure vandalism',
                    value: 'vandalism',
                    tooltip: 'Plain pure vandalism'
                },
                { 
                    label: 'G3: Pagemove', 
                    value: 'pagemove',
                    tooltip: 'Nonsense redirects that are created from the cleanup of page move vandalism.'
                },
                {
                    label: 'G4: Recreation of deleted material',
                    value: 'repost',
                    tooltip: 'A copy, by any title, of a page that was deleted via an XfD process or Deletion review, provided that the copy is substantially identical to the deleted version and that any revisions made clearly do not address the reasons for which the page was deleted. This clause does not apply to content that has been "userfied", to content undeleted as a result of Deletion review, or if the prior deletions were proposed or speedy deletions, although in this last case, the previous speedy criterion, or other speedy deletion criteria, may apply.'
                },
                {
                    label: 'G5: Banned user', 
                    value: 'banned',
                    tooltip: 'Pages created by banned users while they were banned'
                },
                {
                    label: 'G6: History merge', 
                    value: 'histmerge',
                    tooltip: 'Temporarily deleting a page in order to merge page histories' 
                },
                {
                    label: 'G6: Move', 
                    value: 'move',
                    tooltip: 'Making way for a noncontroversial move like reversing a redirect' 
                },
                {
                    label: 'G6: Afd',
                    value: 'afd',
                    tooltip: 'An admin has closed an Articles for deletion debate as a "delete".'
                },
                {
                    label: 'G6: Housekeeping',
                    value: 'g6',
                    tooltip: 'Other non-controversial "housekeeping" tasks'
                },
                {
                    label: 'G7: Author requests deletion',
                    value: 'author',
                    tooltip: 'Any page for which deletion is requested by the original author in good faith, provided the page\'s only substantial content was added by its author'
                },
                {
                    label: 'G7: Author blanked',
                    value: 'blanked',
                    tooltip: ' If the author blanks the page, this can be taken as a deletion request'
                },
                {
                    label: 'G8: Talk pages whose corresponding article does not exist',
                    value: 'talk',
                    tooltip: 'unless: It contains deletion discussion that is not logged elsewhere; It is a User Talk page; It is the Talk page for an image uploaded on the Wikimedia Commons; It is a Talk subpage (such as archived Talk pages) whose corresponding top-level article does exist'
                },
                { 
                    label: 'G10: Attack page',
                    value: 'attack', 
                    tooltip: 'Pages that serve no purpose but to disparage their subject or some other entity (e.g., "John Q. Doe is an imbecile"). This includes a biography of a living person that is negative in tone and unsourced, where there is no NPOV version in the history to revert to. Administrators deleting such pages should not quote the content of the page in the deletion summary!'
                },
                { 
                    label: 'G11: Blatant advertising',
                    value: 'spam', 
                    tooltip: 'Pages which exclusively promote a company, product, group, service, or person and which would need to be fundamentally rewritten in order to become encyclopedic. Note that simply having a company, product, group, service, or person as its subject does not qualify an article for this criterion; an article that is blatant advertising should have inappropriate content as well'
                },
                { 
                    label: 'G12: Blatant copyright infringement', 
                    value: 'copyvio', 
                    tooltip: 'Either, 1: Material was copied from another website that does not have a license compatible with Wikipedia, or is photography from a stock photo seller (such as Getty Images or Corbis) or other commercial content provider; 2: There is no non-infringing content in the page history worth saving; or 3: The infringement was introduced at once by a single person rather than created organically on wiki and then copied by another website such as one of the many Wikipedia mirrors' 
                }
            ]
        });
if( wgNamespaceNumber ==  0 || wgNamespaceNumber == 1 ) {
    form.append( { type:'header', label:'Articles' } );
    form.append( {
            type: 'radio',
            name: 'csd',
            list: [
                {
                    label: 'A1: Little or no context',
                    value: 'nocontext',
                    tooltip: 'Very short articles providing little or no context (e.g., "He is a funny man that has created Factory and the Hacienda. And, by the way, his wife is great."). Limited content is not in itself a reason to delete if there is enough context for the article to qualify as a valid stub'
                },
                {
                    label: 'A2: Foreign language articles that exist on another Wikimedia project',
                    value: 'foreign',
                    tooltip: 'If the article in question does not exist on another project, the template \{\{notenglish\}\} should be used instead. All articles in a non-English language that do not meet this criteria (and do not meet any other criteria for speedy deletion) should be listed at Pages Needing Translation (PNT) for review and possible translation'
                },
                {
                    label: 'A3: No content whatsoever',
                    value: 'nocontent',
                    tooltip: 'Any article consisting only of links elsewhere (including hyperlinks, category tags and "see also" sections), a rephrasing of the title, and/or attempts to correspond with the person or group named by its title. This does not include disambiguation pages'
                },
                {
                    label: 'A5: Transwikied articles',
                    value: 'transwiki',
                    tooltip: 'Any article that has been discussed at Articles for Deletion (et al), where the outcome was to transwiki, and where the transwikification has been properly performed and the author information recorded. Alternately, any article that consists of only a dictionary definition, where the transwikification has been properly performed and the author information recorded'
                },
                {
                    label: 'A7: Unremarkable people, groups, companies and web content',
                    value: 'bio',
                    tooltip: 'An article about a real person, group of people, band, club, company, or web content that does not assert the importance or significance of its subject. If controversial, or if there has been a previous AfD that resulted in the article being kept, the article should be nominated for AfD instead'
                },
                {
                    label: 'A7: Unremarkable band',
                    value: 'band',
                    tooltip: 'Article about a band, singer, musician, or musical ensemble that does not assert the importance or significance of the subject.'
                },
                {
                    label: 'A7: Unremarkable club',
                    value: 'club',
                    tooltip: 'Article about a club that does not assert the importance or significance of the subject.'
                },
                {
                    label: 'A7: Unremarkable company',
                    value: 'inc',
                    tooltip: 'Article about a company or corporation that does not assert the importance or significance of the subject.'
                },
                {
                    label: 'A7: Unremarkable website',
                    value: 'web',
                    tooltip: 'Article about a web site, blog, online forum, webcomic, podcast, or similar web content that does not assert the importance or significance of its subject.'
                }
            ]
        } );
}
    form.append( { type:'header', label: 'Redirects' } );
    form.append( {
            type: 'radio',
            name: 'csd',
            list: [
                { 
                    label: 'R1: Redirects to nonexistent pages',
                    value: 'redirnone'
                },
                { 
                    label: 'R2: Redirects to the Talk:, User: or User talk: namespace from the article space', 
                    value: 'rediruser', 
                    tooltip: '(this does not include the Wikipedia shortcut pseudo-namespaces). If this was the result of a page move, consider waiting a day or two before deleting the redirect'
                },
                { 
                    label: 'R3: Redirects as a result of an implausible typo that were recently created', 
                    value: 'redirtypo', 
                    tooltip: 'However, redirects from common misspellings or misnomers are generally useful, as are redirects in other languages'
                }
            ]
        } );
if( wgNamespaceNumber ==  14 || wgNamespaceNumber == 15 ) {
    form.append( { type:'header', label: 'Categories' } );
    form.append( {
            type: 'radio',
            name: 'csd',
            list: [
                { 
                    label: 'C1: Empty categories',
                    value: 'catempty',
                    tooltip: '(no articles or subcategories for at least four days) whose only content has consisted of links to parent categories. This does not apply to categories being discussed on WP:CFD or WP:SFD, or disambiguation categories. If the category isn\'t relatively new, it possibly contained articles earlier, and deeper investigation is needed'
                },
                {
                    label: 'C3: Template categories',
                    value: 'catfd',
                    tooltip: 'If a category is solely populated from a template (e.g. Category:Wikipedia cleanup from \{\{cleanup\}\}) and the template is deleted per deletion policy, the category can also be deleted without further discussion'
                }
            ]
        } );
} if( wgNamespaceNumber ==  2 || wgNamespaceNumber == 3 ) {
    form.append( { type:'header', label: 'User pages' } );
    form.append( {
            type: 'radio',
            name: 'csd',
            list: [
                {
                    label: 'U1: User request',
                    value: 'userreq',
                    tooltip: 'Personal subpages, upon request by their user. In some rare cases there may be administrative need to retain the page. Also, sometimes, main user pages may be deleted as well. See Wikipedia:User page for full instructions and guidelines'
                },
                {
                    label: 'U2: Nonexistent user',
                    value: 'nouser',
                    tooltip: 'User pages of users that do not exist (Check Special:Listusers)'
                },
                {
                    label: 'U3: Non-free galleries',
                    value: 'u3',
                    tooltip: 'Galleries in the userspace which consist mostly of "fair use" or non-free images. Wikipedia\'s non-free content policy forbids users from displaying non-free images, even ones they have uploaded themselves, in userspace. It is acceptable to have free images, GFDL-images, Creative Commons and similar licenses along with public domain material, but not "fair use" images'
                },
            ]
        } );
} if( wgNamespaceNumber ==  10 || wgNamespaceNumber == 11 ) {
    form.append( { type:'header', label: 'Templates' } );
    form.append( {
            type: 'radio',
            name: 'csd',
            list: [
 
                { 
                    label: 'T1: Templates that are divisive and inflammatory',
                    value: 'divisive'
                }
            ]
        } );
} if( wgNamespaceNumber ==  100 || wgNamespaceNumber == 101 ) {
    form.append( { type:'header', label: 'Portals' } );
    form.append( {
            type: 'radio',
            name: 'csd',
            list: [
                {
                    label: 'P2: Underpopulated portal',
                    value: 'emptyportal',
                    tooltip: 'Any Portal based on a topic for which there is not a non-stub header article, and at least three non-stub articles detailing subject matter that would be appropriate to discuss under the title of that Portal'
                }
            ]
        } ); }
 
    var result = form.render();
    Window.setContent( result );
    Window.display();
}
 
twinklespeedy.normalizeHash = {
    'nonsense': 'g1',
    'test': 'g2',
    'vandalism': 'g3',
    'pagemove': 'g3',
    'repost': 'g4',
    'banned': 'g5',
    'histmerge': 'g6',
    'move': 'g6',
    'afd': 'g6',
    'g6': 'g6',
    'author': 'g7',
    'blanked': 'g7',
    'talk': 'g8',
    'attack': 'g10',
    'spam': 'g11',
    'copyvio': 'g12',
    'nocontext': 'a1',
    'foreign': 'a2',
    'nocontent': 'a3', 
    'transwiki': 'a5',
    'bio': 'a7',
    'inc': 'a7',
    'web': 'a7',
    'band': 'a7',
    'club': 'a7',
    'redirnone': 'r1',
    'rediruser': 'r2',
    'redirtypo': 'r3',
    'redundantimage': 'i1',
    'noimage': 'i2',
    'noncom': 'i3',
    'unksource': 'i4',
    'unfree': 'i5',
    'norat': 'i6',
    'badfairuse': 'i7',
    'nowcommons': 'i8',
    'imgcopyvio': 'i9',
    'badfiletype': 'i10',
    'catempty': 'c1',
    'catfd': 'c3',
    'userreq': 'u1',
    'nouser': 'u2',
    'u3': 'u3',
    'divisive': 't1',
    'emptyportal': 'p2'
};
 
twinklespeedy.reasonHash = {
    'nonsense': 'was patent nonsense: an unsalvageably incoherent page with no meaningful content',
    'test': 'was a test page',
    'vandalism': 'was pure vandalism',
    'pagemove': 'was a redirect created during cleanup of page move vandalism',
    'repost': 'was a copy of material previously deleted per XfD',
    'banned': 'was a contribution was made by a banned user',
    'histmerge': 'temporary deletion in order to merge page histories',
    'move': 'making way for a non-controversial move',
    'afd': 'deleting page per result of AfD discussion',
    'g6': 'non-controversial housekeeping deletion',
    'author': 'only editor requested deletion',
    'blanked': 'only editor has blanked the page',
    'talk': 'was a talk page whose corresponding page does not exist',
    'attack': 'was a attack page intented to disparage its subject',
    'spam': 'was blatant advertising, used only to promote someone or something',
    'copyvio': 'was a blatant copyright infringement',
    'nocontext': 'was a very short article providing little or no context',
    'foreign': 'was a foreign language article that exists on another Wikimedia project',
    'nocontent': 'had no content whatsoever except possibly links elsewhere, a rephrasing of the title, and/or attempts to correspond', 
    'transwiki': 'was properly transwikified elsewhere',
    'bio': 'was an article about a real person, group of people, band, club, company, or web content that didn\'t assert the importance or significance of its subject',
    'web': 'was an article about a web site, blog, online forum, webcomic, podcast, or similar web content that didn\'t assert the importance or significance of its subject',
    'inc': 'was an article about a company or corporation that didn\'t assert the importance or significance of its subject',
    'club': 'was an article about a club that didn\'t assert the importance or significance of the subject',
    'band': 'was an article about a band, singer, musician, or musical ensemble that didn\'t assert the importance or significance of the subject',
    'redirnone': 'was a redirect to an non-existent page',
    'rediruser': 'was a redirect to the Talk:, User: or User talk: space',
    'redirtypo': 'was a redirect based on an implausible typo',
    'redundantimage': 'a same or better image exists on Wikipedia',
    'noimage': 'was a corrupt or empty image',
    'noncom': 'was licensed as "for non-commercial use only", "non-derivative use" or "used with permission", uploaded on or after May 19, 2005, and no assertion of fair use was provided',
    'unksource': 'was an image lacking sources or licensing information for more than seven days',
    'unfree': 'was an unfree image unused for more than seven days',
    'norat': 'was an image with fair use tag but no fair use rationale for more than seven days',
    'badfairuse': 'was an image with an invalid fair use rationale and the uploader was notified more than 48 hours ago',
    'nowcommons': 'was an image available as a bit-for-bit identical copy on the Wikimedia Commons',
    'imgcopyvio': 'was an image that was a suspected copyright infringement, and the uploader didn\'t assert public domain, fair use, or a free license',
    'catempty': 'was an empty category for at least four days',
    'catfd': 'was a category solely populated from a now deleted template',
    'userreq': 'was a user page whose user requested deletion',
    'nouser': 'was a user page of a user that did not exist',
    'u3': 'was a gallery in the user space which consisted mostly of fair use images',
    'divisive': 'was an divisive and inflammatory template',
    'emptyportal': 'was an underpopulated portal'
};
 
twinklespeedy.callbacks = {
    sysop: {
        main: function( self ) {
            var xmlDoc = self.responseXML;
            var normal = xmlDoc.evaluate( '//normalized/n/@to', xmlDoc, null, XPathResult.STRING_TYPE, null ).stringValue;
            if( normal ) {
                wgPageName = normal;
            }
            var exists = xmlDoc.evaluate( 'boolean(//pages/page[not(@missing)])', xmlDoc, null, XPathResult.BOOLEAN_TYPE, null ).booleanValue;
 
            if( ! exists ) {
                self.statelem.error( "It seems that the page doesn't exists, perhaps it has already been deleted" );
                return;
            }
            var query = { 
                'title': wgPageName, 
                'action': 'delete'
            };
 
            var wikipedia_wiki = new Wikipedia.wiki( 'Deleting page', query, twinklespeedy.callbacks.sysop.deletePage );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.followRedirect = false;
            wikipedia_wiki.get();
 
            if( 
                TwinkleConfig.deleteTalkPageOnDelete && 
                self.params.normalized != 'i8' &&
                wgNamespaceNumber % 2 == 0 && 
                document.getElementById( 'ca-talk' ).className != 'new' 
            ) {
                var talk_page = namespaces[ wgNamespaceNumber  + 1 ] + ':' + wgTitle;
                var query = query = {
                    'title': talk_page,
                    'action': 'delete'
                };
                var wikipedia_wiki = new Wikipedia.wiki( 'Deleting talk page', query, twinklespeedy.callbacks.sysop.deleteTalkPage );
                wikipedia_wiki.params = self.params;
                wikipedia_wiki.followRedirect = false;
                wikipedia_wiki.get();
            }
 
            if( wgNamespaceNumber == 6 && self.params.normalized != 'i8' ) {
                var query = {
                    'action': 'query',
                    'list': 'imageusage',
                    'titles': wgPageName,
                    'iulimit': userIsInGroup( 'sysop' ) ? 5000 : 500 // 500 is max for normal users, 5000 for bots and sysops
                };
                var wikipedia_api = new Wikipedia.api( 'Grabbing image links', query, twinklespeedy.callbacks.sysop.unlinkImageInstancesMain );
                wikipedia_api.params = self.params;
                wikipedia_api.post();
            }
            var doOrphan = TwinkleConfig.orphanBacklinksOnSpeedyDelete;
            if( 
                doOrphan.orphan && 
                doOrphan.exclude.indexOf( self.params.normalized.toLowerCase() ) == -1 
            ) {
                var query = {
                    'action': 'query',
                    'list': 'backlinks',
                    'blfilterredir': 'nonredirects',
                    'bltitle': wgPageName,
                    'bllimit': userIsInGroup( 'sysop' ) ? 5000 : 500, // 500 is max for normal users, 5000 for bots and sysops
                    'blnamespace': [0, 100] // Main namespace and portal namespace only, keep on talk pages.
                };
                var wikipedia_api = new Wikipedia.api( 'Grabbing backlinks', query, twinklespeedy.callbacks.sysop.unlinkBacklinksMain );
                wikipedia_api.params = self.params;
                wikipedia_api.post();
            }
            var query = {
                'action': 'query',
                'list': 'backlinks',
                'blfilterredir': 'redirects',
                'bltitle': wgPageName,
                'bllimit': userIsInGroup( 'sysop' ) ? 5000 : 500 // 500 is max for normal users, 5000 for bots and sysops
            };
            var wikipedia_api = new Wikipedia.api( 'Grabbing redirects', query, twinklespeedy.callbacks.sysop.deleteRedirectsMain );
            wikipedia_api.params = self.params;
            wikipedia_api.post();
 
        },
        unlinkBacklinksMain: function( self ) {
            var xmlDoc = self.responseXML;
            var snapshot = xmlDoc.evaluate('//backlinks/bl/@title', xmlDoc, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
 
            if( snapshot.snapshotLength == 0 ) {
                return;
            }
 
            var statusIndicator = new Status('Removing backlinks', '0%');
 
            var total = snapshot.snapshotLength * 2;
 
            var onsuccess = function( self ) {
                var obj = self.params.obj;
                var total = self.params.total;
                var now = parseInt( 100 * ++(self.params.current)/total ) + '%';
                obj.update( now );
                self.statelem.unlink();
                if( self.params.current >= total ) {
                    obj.info( now + ' (completed)' );
                    Wikipedia.removeCheckpoint();
                }
            }
            var onloaded = onsuccess;
 
            var onloading = function( self ) {}
 
 
            Wikipedia.addCheckpoint();
            if( snapshot.snapshotLength == 0 ) {
                statusIndicator.info( '100% (completed)' );
                Wikipedia.removeCheckpoint();
                return;
            }
 
            var params = clone( self.params );
            params.current = 0;
            params.total = total;
            params.obj = statusIndicator;
            params.page = wgPageName;
 
 
            for ( var i = 0; i < snapshot.snapshotLength; ++i ) {
                var title = snapshot.snapshotItem(i).value;
                var query = {
                    'title': title,
                    'action': 'submit'
                }
                var wikipedia_wiki = new Wikipedia.wiki( "Unlinking on " + title, query, twinklespeedy.callbacks.sysop.unlinkBacklinks );
                wikipedia_wiki.params = params;
                wikipedia_wiki.onloading = onloading;
                wikipedia_wiki.onloaded = onloaded;
                wikipedia_wiki.onsuccess = onsuccess;
                wikipedia_wiki.get();
            }
        },
        unlinkBacklinks: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var text = form.wpTextbox1.value;
            var old_text = text;
            var wikiPage = new Mediawiki.Page( text );
            wikiPage.removeLink( self.params.page );
 
            text = wikiPage.getText();
            if( text == old_text ) {
                // Nothing to do, return
                self.onsuccess( self );
                Wikipedia.actionCompleted( self );
                return;
            }
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': 'Removing backlinks to ' + self.params.page + " that has been speedily deleted per ([[WP:CSD#" + self.params.normalized.toUpperCase() + "|CSD " + self.params.normalized.toUpperCase() + "]])" + "; " + TwinkleConfig.deletionSummaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        },
        deleteRedirectsMain: function( self ) {
            var xmlDoc = self.responseXML;
            var snapshot = xmlDoc.evaluate('//backlinks/bl/@title', xmlDoc, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
 
            var total = snapshot.snapshotLength * 2;
 
            if( snapshot.snapshotLength == 0 ) {
                return;
            }
 
            var statusIndicator = new Status('Deleting redirects', '0%');
 
            var onsuccess = function( self ) {
                var obj = self.params.obj;
                var total = self.params.total;
                var now = parseInt( 100 * ++(self.params.current)/total ) + '%';
                obj.update( now );
                self.statelem.unlink();
                if( self.params.current >= total ) {
                    obj.info( now + ' (completed)' );
                    Wikipedia.removeCheckpoint();
                }
            }
            var onloaded = onsuccess;
 
            var onloading = function( self ) {}
 
 
            Wikipedia.addCheckpoint();
            if( snapshot.snapshotLength == 0 ) {
                statusIndicator.info( '100% (completed)' );
                Wikipedia.removeCheckpoint();
                return;
            }
 
            var params = clone( self.params );
            params.current = 0;
            params.total = total;
            params.obj = statusIndicator;
 
 
            for ( var i = 0; i < snapshot.snapshotLength; ++i ) {
                var title = snapshot.snapshotItem(i).value;
                var query = {
                    'title': title,
                    'action': 'delete'
                }
                var wikipedia_wiki = new Wikipedia.wiki( "Deleting " + title, query, twinklespeedy.callbacks.sysop.deleteRedirects );
                wikipedia_wiki.params = params;
                wikipedia_wiki.onloading = onloading;
                wikipedia_wiki.onloaded = onloaded;
                wikipedia_wiki.onsuccess = onsuccess;
                wikipedia_wiki.followRedirect = false;
                wikipedia_wiki.get();
            }
        },
        deleteRedirects: function( self ) {
            var form = this.responseXML.getElementById( 'deleteconfirm' );
            if( ! form ) { // Hell, image deletion is b0rked :(
                form = this.responseXML.getElementsByTagName( 'form' )[0];
                var postData = {
                    'wpDeleteReasonList': 'other',
                    'wpReason': "Speedy deleted per ([[WP:CSD#R1|CSD R1]]), Redirect to deleted page \"" + wgPageName + "\"." + TwinkleConfig.deletionSummaryAd,
                    'wpEditToken': form.wpEditToken.value
                }
            } else {
 
                var postData = {
                    'wpWatch': form.wpWatch.checked ? '' : undefined,
                    'wpDeleteReasonList': 'other',
                    'wpReason': "Speedy deleted per ([[WP:CSD#R1|CSD R1]]), Redirect to deleted page \"" + wgPageName + "\"." + TwinkleConfig.deletionSummaryAd,
                    'wpEditToken': form.wpEditToken.value
                }
            }
            self.post( postData );
        },
        unlinkImageInstancesMain: function( self ) {
            var xmlDoc = self.responseXML;
            var snapshot = xmlDoc.evaluate('//imageusage/iu/@title', xmlDoc, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
 
            if( snapshot.snapshotLength == 0 ) {
                return;
            }
 
            var statusIndicator = new Status('Unlinking instances image', '0%');
 
            var total = snapshot.snapshotLength * 2;
 
            var onsuccess = function( self ) {
                var obj = self.params.obj;
                var total = self.params.total;
                var now = parseInt( 100 * ++(self.params.current)/total ) + '%';
                obj.update( now );
                self.statelem.unlink();
                if( self.params.current >= total ) {
                    obj.info( now + ' (completed)' );
                    Wikipedia.removeCheckpoint();
                }
            }
            var onloaded = onsuccess;
 
            var onloading = function( self ) {}
 
 
            Wikipedia.addCheckpoint();
            if( snapshot.snapshotLength == 0 ) {
                    statusIndicator.info( '100% (completed)' );
                    Wikipedia.removeCheckpoint();
                    return;
            }
 
            var params = clone( self.params );
            params.current = 0;
            params.total = total;
            params.obj = statusIndicator;
            params.image = wgTitle;
 
            for ( var i = 0; i < snapshot.snapshotLength; ++i ) {
                var title = snapshot.snapshotItem(i).value;
                var query = {
                    'title': title,
                    'action': 'submit'
                }
                var wikipedia_wiki = new Wikipedia.wiki( "Unlinking on " + title, query, twinklespeedy.callbacks.sysop.unlinkImageInstances );
                wikipedia_wiki.params = params;
                wikipedia_wiki.onloading = onloading;
                wikipedia_wiki.onloaded = onloaded;
                wikipedia_wiki.onsuccess = onsuccess;
                wikipedia_wiki.get();
            }
        },
        unlinkImageInstances: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var text = form.wpTextbox1.value;
            var old_text = text;
            var wikiPage = new Mediawiki.Page( text );
            wikiPage.commentOutImage( self.params.image, 'Commented out because image was deleted' );
 
            text = wikiPage.getText();
            if( text == old_text ) {
                // Nothing to do, return
                self.onsuccess( self );
                Wikipedia.actionCompleted( self );
                return;
            }
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': 'Removing instance of image ' + self.params.image + " that has been speedily deleted per ([[WP:CSD#" + self.params.normalized.toUpperCase() + "|CSD " + self.params.normalized.toUpperCase() + "]])" + "; " + TwinkleConfig.deletionSummaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        },
        deletePage: function( self ) {
            var form = this.responseXML.getElementById( 'deleteconfirm' );
            if( ! form ) { // Hell, image deletion is b0rked :(
                form = this.responseXML.getElementsByTagName( 'form' )[0];
                var postData = {
                    'wpDeleteReasonList': 'other',
                    'wpReason': "Speedy deleted per ([[WP:CSD#" + self.params.normalized.toUpperCase() + "|CSD " + self.params.normalized.toUpperCase() + "]]), " + self.params.reason + "." + TwinkleConfig.deletionSummaryAd,
                    'wpEditToken': form.wpEditToken.value
                }
                self.post( postData );
            } else {
 
                var postData = {
                    'wpWatch': self.params.watch || form.wpWatch.checked ? '' : undefined,
                    'wpDeleteReasonList': 'other',
                    'wpReason': "Speedy deleted per ([[WP:CSD#" + self.params.normalized.toUpperCase() + "|CSD " + self.params.normalized.toUpperCase() + "]]), " + self.params.reason + "." + TwinkleConfig.deletionSummaryAd,
                    'wpEditToken': form.wpEditToken.value
                }
                self.post( postData );
            }
        },
        deleteTalkPage: function( self ) {
            form = this.responseXML.getElementById( 'deleteconfirm' );
 
            var postData = {
                'wpWatch': self.params.watch || form.wpWatch.checked ? '' : undefined,
                'wpDeleteReasonList': 'other',
                'wpReason': "Speedy deleted per ([[WP:CSD#g8|CSD g8]]), was a talk page of deleted page." + TwinkleConfig.deletionSummaryAd,
                'wpEditToken': form.wpEditToken.value
            }
            self.post( postData );
        }
    },
    user: {
        main: function( self ) {
            var xmlDoc = self.responseXML;
 
            var exists = xmlDoc.evaluate( 'boolean(//pages/page[not(@missing)])', xmlDoc, null, XPathResult.BOOLEAN_TYPE, null ).booleanValue;
 
            if( ! exists ) {
                self.statelem.error( "It seems that the page doesn't exists, perhaps it has already been deleted" );
                return;
            }
            var query = { 
                'title': wgPageName, 
                'action': 'submit'
            };
 
            var wikipedia_wiki = new Wikipedia.wiki( 'Tagging page', query, twinklespeedy.callbacks.user.tagPage );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.followRedirect = false;
            wikipedia_wiki.get();
        },
        tagPage: function( self ) {
            form = this.responseXML.getElementById( 'editform' );
 
            var text = form.wpTextbox1.value;
 
            self.statelem.status( 'Checking for tags on the page...' );
 
            var tag = /(\{\{(?:db-?|delete)\|?.*?\}\})/.exec( text );
 
            if( tag ) {
                self.statelem.error( [ htmlNode( 'strong', tag[0] ) , " is already placed on the page." ] )
                return;
            }
 
            var xfd = /(\{\{(?:[rsaitcm]fd|md1)[^{}]*?\}\})/i.exec( text );
 
            if( xfd && !confirm( "The deletion related template " + xfd[0] + " is already present on the page, do you still want to apply CSD template?" ) ) {
                return;
            }
            var code;
            switch( self.params.normalized ) {
            case 'i8':
                var date = new Date();
                var code = "\{\{NowCommons|month=" + date.getUTCMonthName() + "|day=" + date.getUTCDate() + "|year=" + date.getUTCFullYear() + "|1=" + wgPageName.replace( '_', ' ' ) + "\}\}";
                break;
            case 'g12':
                var url = prompt( 'please enter url if available, including the http://' );
                if( url == null ) {
                    return;
                }
                code = "\{\{db-" +  self.params.value + "|url=" + url + "\}\}";
                break;
            case 'i1':
                var img = prompt( 'enter the image this is redundant to, excluding the Image: prefix' );
                if( img == null ) {
                    return;
                }
                code = "\{\{db-" +  self.params.value + "|1=" + img + "\}\}";
                break;
            default:
                code = "\{\{db-" +  self.params.value + "\}\}";
                break;
            }
 
            // Notification to first contributor
            var query = {
                'action': 'query',
                'prop': 'revisions',
                'titles': wgPageName,
                'rvlimit': 1,
                'rvprop': 'user',
                'rvdir': 'newer'
            }
            var callback = function( self ) {
                var xmlDoc = self.responseXML;
                var user = xmlDoc.evaluate( '//rev/@user', xmlDoc, null, XPathResult.STRING_TYPE, null ).stringValue;
                var query = {
                    'title': 'User talk:' + user,
                    'action': 'submit'
                };
                var wikipedia_wiki = new Wikipedia.wiki( 'Notifying of initial contributor (' + user + ')', query, twinklespeedy.callbacks.user.userNotification );
                wikipedia_wiki.params = self.params;
                wikipedia_wiki.get();
            }
 
            if( self.params.usertalk ) {
                var wikipedia_api = new Wikipedia.api( 'Grabbing data of initial contributor', query, callback );
                wikipedia_api.params = self.params;
                wikipedia_api.post();
            }
 
            var postData = {
                'wpMinoredit': TwinkleConfig.markSpeedyPagesAsMinor ? '' : undefined,
                'wpWatchthis': self.params.watch ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Requesting speedy deletion ([[WP:CSD#" + self.params.normalized.toUpperCase() + "|CSD " + self.params.normalized.toUpperCase() + "]])." + TwinkleConfig.summaryAd,
                'wpTextbox1': code + "\n" + text
            };
            self.post( postData );
        },
        userNotification: function( self ) {
            var form = self.responseXML.getElementById( 'editform' );
            var text = form.wpTextbox1.value;
            text += "\n\{\{subst:db-csd-notice-custom|1=" + wgPageName + "|2=" + self.params.value + "\}\}";
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': 'Notification: Speedy deletion nomination of \[\[' + wgPageName + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        }
    }
}
 
twinklespeedy.callback.evaluateSysop = function twinklespeedyCallbackEvaluateSysop(e) {
 
    wgPageName = wgPageName.replace( /_/g, ' ' ); // for queen/king/whatever and country!
 
    var tag_only = e.target.form.tag_only;
    if( tag_only && tag_only.checked ) {
        return twinklespeedy.callback.evaluateUser(e);
    }
 
    var value = e.target.value;
    var normalized = twinklespeedy.normalizeHash[ value ];
 
    var params = {
        value: value,
        normalized: normalized,
        watch: TwinkleConfig.watchSpeedyPages.indexOf( normalized ) != -1,
        reason: twinklespeedy.reasonHash[ value ]
    };
    Status.init( e.target.form );
 
    var query = {
        'action': 'query',
        'titles': wgPageName
    }
    var wikipedia_api = new Wikipedia.api( 'Checking if page exists', query, twinklespeedy.callbacks.sysop.main );
    wikipedia_api.params = params;
    wikipedia_api.post();
}
 
 
 
twinklespeedy.callback.evaluateUser = function twinklespeedyCallbackEvaluateUser(e) {
    wgPageName = wgPageName.replace( /_/g, ' ' ); // for queen/king/whatever and country!
    var value = e.target.value;
    var normalized = twinklespeedy.normalizeHash[ value ];
 
    var params = {
        value: value,
        normalized: normalized,
        watch: TwinkleConfig.watchSpeedyPages.indexOf( normalized ) != -1,
        usertalk: TwinkleConfig.notifyUserOnSpeedyDeletionNomination.indexOf( normalized ) != -1 && e.target.form.notify.checked
    };
 
    Status.init( e.target.form );
 
    Wikipedia.actionCompleted.redirect = wgPageName;
    Wikipedia.actionCompleted.notice = "Tagging complete";
 
    var query = {
        'action': 'query',
        'titles': wgPageName
    }
 
    var wikipedia_api = new Wikipedia.api( 'Checking if page exists', query, twinklespeedy.callbacks.user.main );
    wikipedia_api.params = params;
    wikipedia_api.post();
 
}
 
// If TwinkleConfig aint exist.
if( typeof( TwinkleConfig ) == 'undefined' ) {
    TwinkleConfig = function() {};
}
 
/**
 TwinkleConfig.summaryAd (string)
 If ad should be added or not to summary, default [[WP:TWINKLE|TWINKLE]]
 */
if( typeof( TwinkleConfig.summaryAd ) == 'undefined' ) {
    TwinkleConfig.summaryAd = " using [[WP:TW|TW]]";
}
 
function num2order( num ) {
    switch( num ) {
    case 1: return '';
    case 2: return '2nd';
    case 3: return '3rd';
    default: return num + 'th';
    }
}
function twinklexfd() {
    if( wgNamespaceNumber < 0 || wgCurRevisionId == false ) {
        return;
    }
    if (twinkleConfigExists)
    {
        addPortletLink( 'p-cactions', "javascript:twinklexfd.callback()", "xfd", "tw-xfd", "Anything for deletion", "");
    }
    else
    {
        addPortletLink('p-cactions', 'javascript:alert("Your account is too new to use Twinkle.");', 'xfd', 'tw-xfd', 'Anything for deletion', '');
    }
}
addOnloadHook(twinklexfd);
 
twinklexfd.callback = function twinklexfdCallback() {
 
    var Window = new SimpleWindow( 600, 300 );
    Window.setTitle( "Anything for deletion" );
    var form = new QuickForm( twinklexfd.callback.evaluate );
    var categories = form.append( {
            type: 'select',
            name: 'category',
            label: 'Select wanted type of category: ',
            tooltip: 'When activated, a default choice is choosen, based on what namespace you are in. This default should be the most appropriate',
            event: twinklexfd.callback.change_category
        } );
    categories.append( {
            type: 'option',
            label: 'Afd',
            selected: wgNamespaceNumber == Namespace.MAIN,
            value: 'afd'
        } );
    categories.append( {
            type: 'option',
            label: 'Tfd',
            selected: wgNamespaceNumber == Namespace.TEMPLATE,
            value: 'tfd'
        } );
    categories.append( {
            type: 'option',
            label: 'Ifd/PUI',
            selected: wgNamespaceNumber == Namespace.IMAGE,
            value: 'ifd'
        } );
    categories.append( {
            type: 'option',
            label: 'Cfd',
            selected: wgNamespaceNumber == Namespace.CATEGORY,
            value: 'cfd'
        } );
    categories.append( {
            type: 'option',
            label: 'Mfd',
            selected: [ Namespace.IMAGE, Namespace.MAIN, Namespace.TEMPLATE, Namespace.CATEGORY ].indexOf( wgNamespaceNumber ) == -1 ,
            value: 'mfd'
        } );
    categories.append( {
            type: 'option',
            label: 'Rfd',
            selected: QueryString.equals('redirect', 'no'),
            value: 'rfd'
        } );
    categories.append( {
            type: 'option',
            label: 'Sfd',
            disabled: true,
            value: 'sfd'
        } );
 
    form.append( {
            type: 'field',
            label:'Work area',
            name: 'work_area'
        } );
 
    var result = form.render();
    Window.setContent( result );
    Window.display();
 
    // We must init the
    var evt = document.createEvent( "Event" );
    evt.initEvent( 'change', true, true );
    result.category.dispatchEvent( evt );
 
}
 
twinklexfd.callback.change_category = function twinklexfdCallbackChangeCategory(e) {
    var value = e.target.value;
    var root = e.target.form;
    var old_area;
    var childNodes = root.childNodes;
    for( var i = 0; i < childNodes.length; ++i ) {
        var node = childNodes[i];
        if( 
            node instanceof Element &&
            node.getAttribute( 'name' ) == 'work_area' 
        ) {
            old_area = node;
            break;
        }
    }
    var work_area = null;
 
    switch( value ) {
    case 'afd':
        work_area = new QuickForm.element( { 
                type: 'field',
                label: 'Articles for deletion',
                name: 'work_area'
            } );
        var afd_category = work_area.append( { 
                type:'select',
                name:'xfdcat',
                label:'Choose what category this nomination belongs in' 
            } );
 
        afd_category.append( { type:'option', label:'Unknown', value:'?', selected:true } );
        afd_category.append( { type:'option', label:'Media and music', value:'M' } );
        afd_category.append( { type:'option', label:'Organisation, corporation, or product', value:'O' } );
        afd_category.append( { type:'option', label:'Biographical', value:'B' } );
        afd_category.append( { type:'option', label:'Society topics', value:'S' } );
        afd_category.append( { type:'option', label:'Web or internet', value:'W' } );
        afd_category.append( { type:'option', label:'Games or sports', value:'G' } );
        afd_category.append( { type:'option', label:'Science and technology', value:'T' } );
        afd_category.append( { type:'option', label:'Fiction and the arts', value:'F' } );
        afd_category.append( { type:'option', label:'Places and transportation', value:'P' } );
        afd_category.append( { type:'option', label:'Indiscernible or unclassifiable topic', value:'I' } );
        afd_category.append( { type:'option', label:'Debate not yet sorted', value:'U' } );
 
        work_area.append( {
                type: 'textarea',
                name: 'xfdreason',
                label: 'Reason: '
            } );
        work_area.append( { type:'submit' } );
        work_area = work_area.render();
        old_area.parentNode.replaceChild( work_area, old_area );
        break;
    case 'tfd':
        work_area = new QuickForm.element( { 
                type: 'field',
                label: 'Templates for deletion',
                name: 'work_area'
            } );
        work_area.append( {
                type: 'textarea',
                name: 'xfdreason',
                label: 'Reason: '
            } );
        work_area.append( { type:'submit' } );
        work_area = work_area.render();
        old_area.parentNode.replaceChild( work_area, old_area );
        break;
    case 'mfd':
        work_area = new QuickForm.element( { 
                type: 'field',
                label: 'Miscellany for deletion',
                name: 'work_area'
            } );
        work_area.append( {
                type: 'textarea',
                name: 'xfdreason',
                label: 'Reason: '
            } );
        work_area.append( { type:'submit' } );
        work_area = work_area.render();
        old_area.parentNode.replaceChild( work_area, old_area );
        break;
    case 'ifd':
        work_area = new QuickForm.element( { 
                type: 'field',
                label: 'Images for deletion',
                name: 'work_area'
            } );
        work_area.append( {
                type: 'checkbox',
                name: 'pui',
                list: [
                    {
                        label: 'Possible unfree image',
                        value: 'pui',
                        tooltip: 'Image have disputed source or licensing information'
                    }
                ]
            } );
        work_area.append( {
                type: 'textarea',
                name: 'xfdreason',
                label: 'Reason: '
            } );
        work_area.append( { type:'submit' } );
        work_area = work_area.render();
        old_area.parentNode.replaceChild( work_area, old_area );
        break;
    case 'cfd':
        work_area = new QuickForm.element( { 
                type: 'field',
                label: 'Categories for discussion',
                name: 'work_area'
            } );
        var cfd_category = work_area.append( {
                type: 'select',
                label: 'Choose type of action wanted: ',
                name: 'xfdcat',
                event: function(e) {
                    var value = e.target.value;
                    var target = e.target.form.xfdtarget;
                    if( value == 'cfd' ) {
                        target.disabled = true;
                    } else {
                        target.disabled = false;
                    }
                }
            } );
        cfd_category.append( { type:'option', label: 'Deletion', value: 'cfd', selected:true } );
        cfd_category.append( { type:'option', label:'Merge', value:'cfm' } );
        cfd_category.append( { type:'option', label:'Renaming', value:'cfr' } );
        cfd_category.append( { type:'option', label:'Convert into article', value:'cfc' } );
 
        work_area.append( {
                type: 'input',
                name: 'xfdtarget',
                label: 'Target page: ',
                disabled: true,
                value: ''
            } );
        work_area.append( {
                type: 'textarea',
                name: 'xfdreason',
                label: 'Reason: '
            } );
        work_area.append( { type:'submit' } );
        work_area = work_area.render();
        old_area.parentNode.replaceChild( work_area, old_area );
        break;
    case 'rfd':
        work_area = new QuickForm.element( { 
                type: 'field',
                label: 'Redirects for discussion',
                name: 'work_area'
            } );
        work_area.append( {
                type: 'textarea',
                name: 'xfdreason',
                label: 'Reason: '
            } );
        work_area.append( { type:'submit' } );
        work_area = work_area.render();
        old_area.parentNode.replaceChild( work_area, old_area );
        break;
    default:
        work_area = new QuickForm.element( { 
                type: 'field',
                label: 'Nothing for anything',
                name: 'work_area'
            } );
        work_area = work_area.render();
        old_area.parentNode.replaceChild( work_area, old_area );
        break;
    }
}
 
twinklexfd.callbacks = {
    afd: {
        main: function ( self ) {
            var xmlDoc = self.responseXML;
            var titles = xmlDoc.evaluate( '//allpages/p/@title', xmlDoc, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
 
            // There has been no earlier entries with this prefix, just go on.
            if( titles.snapshotLength <= 0 ) {
                self.params.numbering = self.params.number = '';
                numbering = number = '';
            } else {
                var number = 0;
                for( var i = 0; i < titles.snapshotLength; ++i ) {
                    var title = titles.snapshotItem(i).value;
 
                    // First, simple test, is there an instance with this exact name?
                    if( title == 'Wikipedia:Articles for deletion/' + wgPageName ) {
                        number = Math.max( number, 1 );
                        continue;
                    }
 
                    var order_re = new RegExp( '^' +
                            RegExp.escape( 'Wikipedia:Articles for deletion/' + wgPageName, true ) +
                            '\\s*\\(\\s*(\\d+)(?:(?:th|nd|rd|st) nom(?:ination)?)?\\s*\\)\\s*$'
                    );
                    var match = order_re.exec( title );
 
                    // No match; A non-good value
                    if( match == null ) {
                        continue;
                    }
 
                    // A match, set number to the max of current
                    number = Math.max( number, Number(match[1]) );
                }
                self.params.number = num2order( parseInt( number ) + 1);
                self.params.numbering = number > 0 ? ' (' + self.params.number + ' nomination)' : '';
            }
 
            Status.info( 'Next discussion page","[[Wikipedia:Articles for deletion/' + wgPageName + self.params.numbering + ']]' );
 
            // Tagging article
            var query = {
                'title': wgPageName,
                'action': 'submit'
            };
            var wikipedia_wiki = new Wikipedia.wiki( 'Tagging article with deletion tag', query, twinklexfd.callbacks.afd.article );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
 
            // Discussion page
            query = {
                'title': 'Wikipedia:Articles for deletion/' + wgPageName + self.params.numbering,
                'action': 'submit'
            };
 
            // Updating data for the action completed event
            Wikipedia.actionCompleted.redirect = query['title'];
            Wikipedia.actionCompleted.notice = "Nomination completed, redirecting now to the discussion page";
 
            var wikipedia_wiki = new Wikipedia.wiki( 'Creating article deletion discussion page', query, twinklexfd.callbacks.afd.discussionPage );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
 
            // Todays list
            var date = new Date();
 
            query = {
                'title': 'Wikipedia:Articles for deletion/Log/' + date.getUTCFullYear() + ' ' + date.getUTCMonthName() + ' ' + date.getUTCDate(),
                'action': 'submit'
            };
 
            var wikipedia_wiki = new Wikipedia.wiki( 'Adding discussion to todays list', query, twinklexfd.callbacks.afd.todaysList );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
 
            // Notification to first contributor
 
            var query = {
                'action': 'query',
                'prop': 'revisions',
                'titles': wgPageName,
                'rvlimit': 1,
                'rvprop': 'user',
                'rvdir': 'newer'
            }
            var callback = function( self ) {
                var xmlDoc = self.responseXML;
                var user = xmlDoc.evaluate( '//rev/@user', xmlDoc, null, XPathResult.STRING_TYPE, null ).stringValue;
                var query = {
                    'title': 'User talk:' + user,
                    'action': 'submit'
                };
                var wikipedia_wiki = new Wikipedia.wiki( 'Notifying of initial contributor (' + user + ')', query, twinklexfd.callbacks.afd.userNotification );
                wikipedia_wiki.params = self.params;
                wikipedia_wiki.get();
            }
            var wikipedia_api = new Wikipedia.api( 'Grabbing data of initial contributor', query, callback );
            wikipedia_api.params = self.params;
            wikipedia_api.post();
        },
        article: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var postData = {
                'wpMinoredit': undefined, // Per memo
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Nominated for deletion; see [[Wikipedia:Articles for deletion/" + wgPageName + self.params.numbering + ']].'+ TwinkleConfig.summaryAd,
                'wpTextbox1': "\{\{" + ( self.params.number == '' ? "subst:afd\}\}\n" : 'subst:afdx|' + self.params.number + "}}\n" ) + form.wpTextbox1.value
            };
            self.post( postData );
        },
        discussionPage: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Creating deletion discussion page for \[\[" + wgPageName + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': "\{\{subst:afd2|pg=" + wgPageName + "|cat=" + self.params.xfdcat + "|text=" + self.params.reason + " \~\~\~\}\}\n"
            };
            self.post( postData );
        },
        todaysList: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var old_text = form.wpTextbox1.value;
 
            var text = old_text.replace( /(<\!-- Add new entries to the TOP of the following list -->\n+)/, "$1\{\{subst:afd3|pg=" + wgPageName + self.params.numbering + "\}\}\n");
            if( text == old_text ) {
                self.statelem.error( 'failed to find target spot to add the discussion to.' );
                return;
            }
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Adding \[\[Wikipedia:Articles for deletion/" + wgPageName + self.params.numbering + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        },
        userNotification: function( self ) {
            var form = self.responseXML.getElementById( 'editform' );
            var text = form.wpTextbox1.value;
            text += "\n\{\{subst:AFDWarning|1=" + wgPageName + ( self.params.numbering != '' ? '|order=&#32;' + self.params.numbering : '' ) + "\}\} \~\~\~";
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': 'AfD nomination of \[\[' + wgPageName + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        }
    },
    tfd: {
        taggingTemplate: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var postData = {
                'wpMinoredit': undefined, // Per memo
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Nominated for deletion; see \[\[Wikipedia:Templates for deletion#" + wgPageName + '\]\].'+ TwinkleConfig.summaryAd,
                'wpTextbox1': "<noinclude>\{\{tfd|" + wgTitle + "\}\}\n</noinclude>" + form.wpTextbox1.value
            };
            self.post( postData );
        },
        todaysList: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var old_text = form.wpTextbox1.value;
            text = old_text.replace( '-->', "-->\n\{\{subst:tfd2|" + wgTitle + "|text=" + self.params.reason + ". \~\~\~\}\}");
            if( text == old_text ) {
                self.statelem.error( 'failed to find target spot to add the discussion to.' );
                return;
            }
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Adding [[Template:" + wgTitle + ']].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        },
        userNotification: function( self ) {
            var form = self.responseXML.getElementById( 'editform' );
            var text = form.wpTextbox1.value;
            text += "\n\{\{subst:tfdnotice|1=" + wgTitle + "\}\} \~\~\~";
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': 'TfD nomination of \[\[Template:' + wgTitle + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        }
    },
    mfd: {
        main: function( self ) {
            var xmlDoc = self.responseXML;
            var titles = xmlDoc.evaluate( '//allpages/p/@title', xmlDoc, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
 
            // There has been no earlier entries with this prefix, just go on.
            if( titles.snapshotLength <= 0 ) {
                self.params.numbering = self.params.number = '';
                numbering = number = '';
            } else {
                var number = 0;
                for( var i = 0; i < titles.snapshotLength; ++i ) {
                    var title = titles.snapshotItem(i).value;
 
                    // First, simple test, is there an instance with this exact name?
                    if( title == 'Wikipedia:Articles for deletion/' + wgPageName ) {
                        number = Math.max( number, 1 );
                        continue;
                    }
 
                    var order_re = new RegExp( '^' +
                            RegExp.escape( 'Wikipedia:Miscellany for deletion/' + wgPageName, true ) +
                            '\\s*\\(\\s*(\\d+)(?:(?:th|nd|rd|st) nom(?:ination)?)?\\s*\\)\\s*$'
                    );
                    var match = order_re.exec( title );
 
                    // No match; A non-good value
                    if( match == null ) {
                        continue;
                    }
 
                    // A match, set number to the max of current
                    number = Math.max( number, Number(match[1]) );
                }
                self.params.number = num2order( parseInt( number ) + 1);
                self.params.numbering = number > 0 ? ' (' + self.params.number + ' nomination)' : '';
            }
 
 
            self.statelem.info( 'next in order is [[Wikipedia:Miscellany for deletion/' + wgPageName + self.params.numbering + ']]');
 
            // Tagging article
            var query = {
                'title': wgPageName,
                'action': 'submit'
            };
 
            var wikipedia_wiki = new Wikipedia.wiki( 'Tagging page with deletion tag', query, twinklexfd.callbacks.mfd.taggingPage );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
 
            // Discussion page
            var query = {
                'title': 'Wikipedia:Miscellany for deletion/' + wgPageName + this.params.numbering,
                'action': 'submit'
            };
 
            // Updating data for the action completed event
            Wikipedia.actionCompleted.redirect = query['title'];
            Wikipedia.actionCompleted.notice = "Nomination completed, redirecting now to the discussion page";
 
            wikipedia_wiki = new Wikipedia.wiki( 'Creating page deletion discussion page', query, twinklexfd.callbacks.mfd.discussionPage );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
 
            // Todays list
            var query = {
                'title': 'Wikipedia:Miscellany for deletion',
                'action': 'submit',
                'section': 2
            };
 
            wikipedia_wiki = new Wikipedia.wiki( 'Adding deletion discussion to todays list', query, twinklexfd.callbacks.mfd.todaysList );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
 
            // Notification to first contributor
            var query = {
                'action': 'query',
                'prop': 'revisions',
                'titles': wgPageName,
                'rvlimit': 1,
                'rvprop': 'user',
                'rvdir': 'newer'
            }
            var callback = function( self ) {
                var xmlDoc = self.responseXML;
                var user = xmlDoc.evaluate( '//rev/@user', xmlDoc, null, XPathResult.STRING_TYPE, null ).stringValue;
                var query = {
                    'title': 'User talk:' + user,
                    'action': 'submit'
                };
                var wikipedia_wiki = new Wikipedia.wiki( 'Notifying of initial contributor (' + user + ')', query, twinklexfd.callbacks.mfd.userNotification );
                wikipedia_wiki.params = self.params;
                wikipedia_wiki.get();
            }
            var wikipedia_api = new Wikipedia.api( 'Grabbing data of initial contributor', query, callback );
            wikipedia_api.params = self.params;
            wikipedia_api.post();
        },
        taggingPage: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var postData = {
                'wpMinoredit': undefined, // Per memo
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Nominated for deletion; see [[Wikipedia:Miscellany for deletion/" + wgPageName + self.params.numbering + ']].'+ TwinkleConfig.summaryAd,
                'wpTextbox1': "\{\{" + ( self.params.number == '' ? "subst:mfd\}\}\n" : 'subst:mfdx|' + self.params.number + "}}\n" ) + form.wpTextbox1.value
            };
            self.post( postData );
        },
        discussionPage: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Creating deletion discussion page for \[\[" + wgPageName + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': "\{\{subst:mfd2|pg=" + wgPageName + "|text=" + self.params.reason + " \~\~\~\}\}\n"
            };
            self.post( postData );
        },
        todaysList: function( self ) {
            var form = self.responseXML.getElementById('editform');
 
            var text = form.wpTextbox1.value;
            var date = new Date();
 
            var month =  new Number( date.getUTCMonth() + 1 );
            var day =  new Number( date.getUTCDate() );
            var year = new Number( date.getUTCFullYear() );
            var today_date = year.zeroFill( 4 ) + '-' + month.zeroFill( 2 ) + '-' + day.zeroFill( 2 );
            var today_regex = new RegExp( "(\\=\\=\\=\\[\\[" + RegExp.escape( today_date ) + "\\]\\]\\=\\=\\=)" );
            var new_data = "\n\{\{subst:mfd3|pg=" + wgPageName + self.params.numbering + "\}\}";
 
            if( today_regex.test( text ) ) { // we have a section allready
                self.statelem.info( 'Found todays section, proceeding to add new entry' );
                text = text.replace( today_regex, "$1\n" + new_data );
            } else { // we need to create a new section
                self.statelem.info( 'No section for today found, proceeding to create one' );
                var old_text = text;
                text = text.replace( '-->', "-->\n===\[\[" + today_date + "\]\]===\n" + new_data );
                if( text == old_text ) {
                    self.statelem.error( 'failed to find target spot to add the discussion to' );
                    return;
                }
            }
 
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Adding \[\[Wikipedia:Miscellany for deletion/" + wgPageName + self.params.numbering + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        },
        userNotification: function( self ) {
            var form = self.responseXML.getElementById( 'editform' );
            var text = form.wpTextbox1.value;
            text += "\n\{\{subst:MFDWarning|1=" + wgPageName + ( self.params.numbering != '' ? '|order=&#32;' + this.params.numbering : '' ) + "\}\} \~\~\~";
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': 'MfD nomination of \[\[' + wgPageName + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        }
    },
    ifd: {
        main: function( self ) {
            var xmlDoc = self.responseXML;
            var user = xmlDoc.evaluate( '//rev/@user', xmlDoc, null, XPathResult.STRING_TYPE, null ).stringValue;
            self.params.uploader = user;
            var query = {
                'title': 'Wikipedia:Images and media for deletion/' + self.params.date,
                'action': 'submit'
            };
 
            wikipedia_wiki = new Wikipedia.wiki( 'Adding deletion discussion to todays list', query, twinklexfd.callbacks.ifd.todaysList );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
 
            // Updating data for the action completed event
            Wikipedia.actionCompleted.redirect = query['title'];
            Wikipedia.actionCompleted.notice = "Nomination completed, redirecting now to the discussion page";
 
            // Notification to first contributor
 
            var query = {
                'title': 'User talk:' + self.params.uploader,
                'action': 'submit'
            };
            wikipedia_wiki = new Wikipedia.wiki( 'Notifying of initial contributor (' + self.params.uploader + ')', query, twinklexfd.callbacks.ifd.userNotification );
            wikipedia_wiki.get();
        },
        taggingImage: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var postData = {
                'wpMinoredit': undefined, // Per 
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "This image is being considered for deletion in accordance with Wikipedia's [[Wikipedia:Deletion policy|Deletion policy]]; See \[\[Wikipedia:Images for deletion#" + wgPageName + '\]\].'+ TwinkleConfig.summaryAd,
                'wpTextbox1': "\{\{ifd|log=" + self.params.date + "\}\}\n" + form.wpTextbox1.value
            };
            self.post( postData );
        },
        todaysList: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Adding discussion for \[\[:" + wgPageName + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': form.wpTextbox1.value + "\n\{\{subst:ifd2|1=" + wgTitle + "|Uploader=" + self.params.uploader + "|Reason=" + self.params.reason + "\}\} \~\~\~"
            };
            self.post( postData );
        },
        userNotification: function( self ) {
            var form = self.responseXML.getElementById( 'editform' );
            var text = form.wpTextbox1.value;
            text += "\n\{\{subst:idw|1=" + wgPageName + "\}\}";
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': 'Notification: IfD nomination of \[\[' + wgPageName + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        },
        tagInstancesMain: function( self ) {
            var xmlDoc = self.responseXML;
            var nsResolver = xmlDoc.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
            var snapshot = xmlDoc.evaluate('//imageusage/iu/@title', xmlDoc, nsResolver, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
 
            if( snapshot.snapshotLength == 0 ) {
                return;
            }
 
            var statusIndicator = new Status('Tagging instances image', '0%');
            var total = snapshot.snapshotLength * 2;
 
            var date = new Date();
            var dateString = date.getUTCFullYear() + ' ' + date.getUTCMonthName() + ' ' + date.getUTCDate();
 
            imageTaggingCounter = 0;
            var onsuccess = function( self ) {
                var obj = self.params.obj;
                var total = self.params.total;
                var now = parseInt( 100 * ++imageTaggingCounter/total ) + '%';
                obj.update( now );
                self.statelem.unlink();
                if( imageTaggingCounter == total ) {
                    obj.info( now + ' (completed)' );
                    Wikipedia.removeCheckpoint();
                }
            }
 
            var onloaded = onsuccess;
 
            var onloading = function( self ) {}
 
 
            Wikipedia.addCheckpoint();
            for ( var i = 0; i < snapshot.snapshotLength; ++i ) {
                var title = snapshot.snapshotItem(i).value;
                var query = {
                    'title': title,
                    'action': 'submit'
                }
                var wikipedia_wiki = new Wikipedia.wiki( "Tagging of " + title, query, twinklexfd.callbacks.ifd.tagInstances );
                wikipedia_wiki.params = { title:title, total:total, obj:statusIndicator, date:dateString };
                wikipedia_wiki.onloading = onloading;
                wikipedia_wiki.onloaded = onloaded;
                wikipedia_wiki.onsuccess = onsuccess;
                wikipedia_wiki.get();
            }
        },
        tagInstances: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var text = form.wpTextbox1.value;
            var old_text = text;
            var wikiPage = new Mediawiki.Page( text );
 
            var tag = "\{\{ifdc|1=Image:" + wgTitle + "|log=" + self.params.date + "\}\}";
            wikiPage.addToImageComment( wgTitle, tag );
 
            text = wikiPage.getText();
            if( text == old_text ) {
                // Nothing to do, return
                self.onsuccess( self );
                Wikipedia.actionCompleted();
                return;
            }
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': 'Tagging [[:Image:' + wgTitle + "]] which is up for deletion at [[WP:IFD|Images for deletion]]" + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        }
    },
    pui: {
        taggingImage: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var postData = {
                'wpMinoredit': undefined, // Per 
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "This image has been listed on [[Wikipedia:Possibly unfree images]] because the information on its source or copyright status is disputed; See \[\[Wikipedia:Possibly unfree images#" + wgPageName + '\]\].'+ TwinkleConfig.summaryAd,
                'wpTextbox1': "\{\{pui|log=" + self.params.date + "\}\}\n" + form.wpTextbox1.value
            };
            self.post( postData );
        },
        todaysList: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Adding discussion for \[\[:" + wgPageName + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': form.wpTextbox1.value + "\n\{\{subst:pui2|image=" + wgTitle + "|reason=" + self.params.reason + "\}\} \~\~\~"
            };
            self.post( postData );
        },
        userNotification: function( self ) {
            var form = self.responseXML.getElementById( 'editform' );
            var text = form.wpTextbox1.value;
            text += "\n\{\{subst:idw-pui|1=" + wgPageName + "\}\} --\~\~\~";
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': 'Notification: PUI posting of \[\[' + wgPageName + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        },
        tagInstancesMain: function( self ) {
            var xmlDoc = self.responseXML;
            var nsResolver = xmlDoc.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
            var snapshot = xmlDoc.evaluate('//imageusage/iu/@title', xmlDoc, nsResolver, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
 
            if( snapshot.snapshotLength == 0 ) {
                return;
            }
            var statusIndicator = new Status('Tagging instances image', '0%');
            var total = snapshot.snapshotLength * 2;
 
            var date = new Date();
            var dateString = date.getUTCFullYear() + ' ' + date.getUTCMonthName() + ' ' + date.getUTCDate();
 
            imageTaggingCounter = 0;
            var onsuccess = function( self ) {
                var obj = self.params.obj;
                var total = self.params.total;
                var now = parseInt( 100 * ++imageTaggingCounter/total ) + '%';
                obj.update( now );
                self.statelem.unlink();
                if( imageTaggingCounter == total ) {
                    obj.info( now + ' (completed)' );
                    Wikipedia.removeCheckpoint();
                }
            }
            var onloaded = onsuccess;
 
            var onloading = function( wikipedia_wiki ) {}
 
 
            Wikipedia.addCheckpoint();
            for ( var i = 0; i < snapshot.snapshotLength; ++i ) {
                var title = snapshot.snapshotItem(i).value;
                var query = {
                    'title': title,
                    'action': 'submit'
                }
                var wikipedia_wiki = new Wikipedia.wiki( "Tagging " + title, query, twinklexfd.callbacks.pui.tagInstances );
                wikipedia_wiki.params = { title:title, total:total, obj:statusIndicator, date:dateString };
                wikipedia_wiki.onloading = onloading;
                wikipedia_wiki.onloaded = onloaded;
                wikipedia_wiki.onsuccess = onsuccess;
                wikipedia_wiki.get();
            }
        },
        tagInstances: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var text = form.wpTextbox1.value;
            var old_text = text;
            var wikiPage = new Mediawiki.Page( text );
 
            var tag = "\{\{puic|1=Image:" + wgTitle + "|log=" + self.params.date + "\}\}";
            wikiPage.addToImageComment( wgTitle, tag );
 
            text = wikiPage.getText();
            if( text == old_text ) {
                // Nothing to do, return
                self.onsuccess( self );
                Wikipedia.actionCompleted();
                return;
            }
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': 'Tagging [[:Image:' + wgTitle + "]] which have been listed on [[WP:PUI|Possible unfree images]]" + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        }
 
    },
    cfd: {
        taggingCategory: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var added_data = "";
            var summary = "";
            switch( self.params.xfdcat ) {
            case 'cfd':
                added_data = "\{\{subst:cfd\}\}";
                summary = "This category is being considered for deletion in accordance with [[WP:CDP|CDP]];" + TwinkleConfig.summaryAd;
                break;
            case 'cfm':
                added_data = "\{\{subst:cfm|" + self.params.target.replace('Category:','') + "\}\}";
                summary = "This category is being considered for merging in accordance with [[WP:CDP|CDP]];" + TwinkleConfig.summaryAd;
                break;
            case 'cfr':
                added_data = "\{\{subst:cfr|" + self.params.target.replace('Category:','') + "\}\}";
                summary = "This category is being considered for renaming in accordance with [[WP:CDP|CDP]];" + TwinkleConfig.summaryAd;
                break;
            case 'cfc':
                added_data = "\{\{subst:cfc|" + self.params.target + "\}\}";
                summary = "This category is being considered for conversion in accordance with [[WP:CDP|CDP]];" + TwinkleConfig.summaryAd;
                break;
            }
            var postData = {
                'wpMinoredit': undefined, // Per the cabal
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': summary,
                'wpTextbox1': added_data + "\n" + form.wpTextbox1.value
            };
            self.post( postData );
        },
        todaysList: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var added_data = "";
            var summary = "";
            switch( this.params.xfdcat ) {
            case 'cfd':
                added_data = "\{\{subst:cfd2|1=" + wgTitle + "|text=" + self.params.reason + " \~\~\~\}\}";
                summary = "Added delete nomination of [[:" + wgPageName + "]];" + TwinkleConfig.summaryAd;
                break;
            case 'cfm':
                added_data = "\{\{subst:cfm2|1=" + wgTitle + "|2=" + self.params.target + "|text=" + self.params.reason + " \~\~\~\}\}";
                summary = "Added merge nomination of [[:" + wgPageName + "]];" + TwinkleConfig.summaryAd;
                break;
            case 'cfr':
                added_data = "\{\{subst:cfr2|1=" + wgTitle + "|2=" + self.params.target + "|text=" + self.params.reason + " \~\~\~\}\}";
                summary = "Added rename nomination of [[:" + wgPageName + "]];" + TwinkleConfig.summaryAd;
                break;
            case 'cfc':
                added_data = "\{\{subst:cfc2|1=" + wgTitle + "|2=" + self.params.target + "|text=" + self.params.reason + " \~\~\~\}\}";
                summary = "Added convert nomination of [[:" + wgPageName + "]];" + TwinkleConfig.summaryAd;
                break;
            }
            var old_text = form.wpTextbox1.value;
 
            text = old_text.replace( '-->', "-->\n" + added_data );
            if( text == old_text ) {
                self.statelem.error( 'failed to find target spot to add the discussion to' );
                return;
            }
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': summary,
                'wpTextbox1': text
            };
            self.post( postData );
        },
        userNotification: function( self ) {
            var form = self.responseXML.getElementById( 'editform' );
            var text = form.wpTextbox1.value;
            var intext = "";
            switch( self.params.xfdcat ) {
            case 'cfd':
                intext = 'for deletion';
                break;
            case 'cfm':
                intext = 'for merging into \{\{lc|' + self.params.target + "\}\}" ;
                break;
            case 'cfr':
                intext = 'for renaming to \{\{lc|' + self.params.target + "\}\}" ;
                break;
            case 'cfc':
                intext = 'for converting into an article named \{\{lc|' + self.params.target + "\}\}" ;
                break;
            }
            text += "\n==CfD nomination of [[:" + wgPageName + "]]==\nI have nominated \{\{lc|" + wgTitle + "\}\} " + intext + ". Your opinions on the matter are welcome; please participate in the discussion by adding your comments at [[" + self.params.todaysPage + "#" + wgPageName + "|the discussion page]]. Thank you. \~\~\~";
 
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': 'Notification: CfD nomination of \[\[:' + wgPageName + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        }
    },
    rfd: {
        main: function( self ) {
            var xmlDoc = self.responseXML;
            var target = xmlDoc.evaluate( '//redirects/r/@to', xmlDoc, null, XPathResult.STRING_TYPE, null ).stringValue;
            if( !target ) {
                self.statelem.error( 'no target of this redirect, aborting' );
                return;
            }
            self.params.target = target;
 
            // Tagging redirect
            var query = {
                'title': wgPageName,
                'action': 'submit'
            };
 
            wikipedia_wiki = new Wikipedia.wiki( 'Tagging redirect with rfd tag', query, twinklexfd.callbacks.rfd.taggingRedirect );
            wikipedia_wiki.followRedirect = false;
            wikipedia_wiki.get();
 
            var date = new Date();
            var today = date.getUTCFullYear() + ' ' + date.getUTCMonthName() + ' ' + date.getUTCDate();
            var query = {
                'title': 'Wikipedia:Redirects for discussion/Log/' + today,
                'action': 'submit'
            };
 
            wikipedia_wiki = new Wikipedia.wiki( 'Adding deletion discussion to todays list', query, twinklexfd.callbacks.rfd.todaysList );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
 
            // Updating data for the action completed event
            Wikipedia.actionCompleted.redirect = query['title'];
            Wikipedia.actionCompleted.notice = "Nomination completed, redirecting now to the discussion page";
 
            self.params.todaysPage = query['title'];
 
            // Notifying initial contributor
            var query = {
                'action': 'query',
                'prop': 'revisions',
                'titles': wgPageName,
                'rvlimit': 1,
                'rvprop': 'user',
                'rvdir': 'newer'
            }
            var callback = function( self ) {
                var xmlDoc = self.responseXML;
                var user = xmlDoc.evaluate( '//rev/@user', xmlDoc, null, XPathResult.STRING_TYPE, null ).stringValue;
                var query = {
                    'title': 'User talk:' + user,
                    'action': 'submit'
                };
                var wikipedia_wiki = new Wikipedia.wiki( 'Notifying of initial contributor (' + user + ')', query, twinklexfd.callbacks.rfd.userNotification );
                wikipedia_wiki.params = self.params;
                wikipedia_wiki.get();
            }
            var wikipedia_api = new Wikipedia.api( 'Grabbing data of initial contributor', query, callback );
            wikipedia_api.params = self.params;
            wikipedia_api.post();
 
        },
        taggingRedirect: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var postData = {
                'wpMinoredit': undefined, // Per 
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "This redirect has been listed on [[Wikipedia:Redirects for discussion]]\]\]." + TwinkleConfig.summaryAd,
                'wpTextbox1': "\{\{rfd\}\}\n" + form.wpTextbox1.value
            };
            self.post( postData );
        },
        todaysList: function( self ) {
            var form = self.responseXML.getElementById('editform');
            var old_text = form.wpTextbox1.value;
            var text = old_text.replace( /(<\!-- Add new entries directly below this line -->\n+)/, "$1\{\{subst:rfd2|redirect="+ wgPageName + "|target=" + self.params.target + "|text=" + self.params.reason.toUpperCaseFirstChar() +"\}\} \~\~\~\n" );
            if( text == old_text ) {
                self.statelem.error( 'failed to find target spot to add the discussion to.' );
                return;
            }
 
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': "Adding [[" + wgPageName + ']].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        },
        userNotification: function( self ) {
            var form = self.responseXML.getElementById( 'editform' );
            var text = form.wpTextbox1.value;
            text += "\n==RfD nomination of [[:" + wgPageName + "]]==\nI have nominated " + ln( wgNamespaceNumber, wgTitle ) + " for discussion. Your opinions on the matter are welcome; please participate in the discussion by adding your comments at [[" + self.params.todaysPage + "#" + wgPageName + "|the discussion page]]. Thank you. \~\~\~";
            var postData = {
                'wpMinoredit': form.wpMinoredit.checked ? '' : undefined,
                'wpWatchthis': form.wpWatchthis.checked ? '' : undefined,
                'wpStarttime': form.wpStarttime.value,
                'wpEdittime': form.wpEdittime.value,
                'wpAutoSummary': form.wpAutoSummary.value,
                'wpEditToken': form.wpEditToken.value,
                'wpSummary': 'Notification: RFD posting of \[\[' + wgPageName + '\]\].' + TwinkleConfig.summaryAd,
                'wpTextbox1': text
            };
            self.post( postData );
        }
    }
}
 
twinklexfd.callback.evaluate = function(e) {
 
    wgPageName = wgPageName.replace( /_/g, ' ' ); // for queen/king/whatever and country!
 
    var type =  e.target.category.value;
    var reason = e.target.xfdreason.value;
    if( type in {'afd':'','cfd':''} ) {
        var xfdcat = e.target.xfdcat.value;
    }
    if( type == 'ifd' ) {
        var pui = e.target.pui.checked;
    }
 
    Status.init( e.target );
 
    if( type == null ) {
        Status.error( 'Error', 'no action given' );
        return;
    }
 
    switch( type ) {
    case 'afd': // AFD
        var query = {
            'action': 'query',
            'list': 'allpages',
            'apprefix': 'Articles for deletion/' + wgPageName,
            'apnamespace': 4,
            'apfilterredir': 'nonredirects',
            'aplimit': userIsInGroup( 'sysop' ) ? 5000 : 500
        };
        var wikipedia_api = new Wikipedia.api( 'Tagging article with deletion tag', query, twinklexfd.callbacks.afd.main );
        wikipedia_api.params = { reason:reason, xfdcat:xfdcat };
        wikipedia_api.post();
        break;
    case 'tfd': // TFD
 
        Wikipedia.addCheckpoint();
        // Tagging article
        var query = {
            'title': wgPageName,
            'action': 'submit'
        };
        wikipedia_wiki = new Wikipedia.wiki( 'Tagging template with deletion tag', query, twinklexfd.callbacks.tfd.taggingTemplate );
        wikipedia_wiki.get();
 
        // Adding discussion
        var date = new Date();
 
        query = {
            'title': 'Wikipedia:Templates for deletion/Log/' + date.getUTCFullYear() + ' ' + date.getUTCMonthName() + ' ' + date.getUTCDate(),
            'action': 'submit',
            'section': 1
        };
 
        // Updating data for the action completed event
        Wikipedia.actionCompleted.redirect = query['title'];
        Wikipedia.actionCompleted.notice = "Nomination completed, redirecting now to the list of today";
 
        wikipedia_wiki = new Wikipedia.wiki( 'Adding discussion to todays list', query, twinklexfd.callbacks.tfd.todaysList );
        wikipedia_wiki.params = { reason:reason };
        wikipedia_wiki.get();
 
        var query = {
            'action': 'query',
            'prop': 'revisions',
            'titles': wgPageName,
            'rvlimit': 1,
            'rvprop': 'user',
            'rvdir': 'newer'
        }
        var callback = function( self ) {
            var xmlDoc = self.responseXML;
            var user = xmlDoc.evaluate( '//rev/@user', xmlDoc, null, XPathResult.STRING_TYPE, null ).stringValue;
            var query = {
                'title': 'User talk:' + user,
                'action': 'submit'
            };
            var wikipedia_wiki = new Wikipedia.wiki( 'Notifying of initial contributor (' + user + ')', query, twinklexfd.callbacks.tfd.userNotification );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
        }
        var wikipedia_api = new Wikipedia.api( 'Grabbing data of initial contributor', query, callback );
        wikipedia_api.params = self.params;
        wikipedia_api.post();
 
        Wikipedia.removeCheckpoint();
        break;
    case 'mfd': // MFD
 
        var query = {
            'action': 'query',
            'list': 'allpages',
            'apprefix': 'Miscellany for deletion/' + wgPageName,
            'apnamespace': 4,
            'apfilterredir': 'nonredirects',
            'aplimit': userIsInGroup( 'sysop' ) ? 5000 : 500
        };
        var wikipedia_api = new Wikipedia.api( 'Quering allpages', query, twinklexfd.callbacks.mfd.main );
        wikipedia_api.params = { reason:reason, xfdcat:xfdcat };
        wikipedia_api.post();
        break;
    case 'ifd': // IFD
 
        var date = new Date();
        var dateString = date.getUTCFullYear() + ' ' + date.getUTCMonthName() + ' ' + date.getUTCDate();
        var params = { reason: reason, date: dateString };
 
        Wikipedia.addCheckpoint();
        if( pui ) {
            // Tagging image
            var query = {
                'title': wgPageName,
                'action': 'submit'
            };
 
            var wikipedia_wiki = new Wikipedia.wiki( 'Tagging image with PUI tag', query, twinklexfd.callbacks.pui.taggingImage );
            wikipedia_wiki.params = params;
            wikipedia_wiki.get();
            // Adding discussion
 
            query = {
                'title': 'Wikipedia:Possibly unfree images/' + dateString,
                'action': 'submit'
            };
 
            // Updating data for the action completed event
            Wikipedia.actionCompleted.redirect = query['title'];
            Wikipedia.actionCompleted.notice = "Nomination completed, redirecting now to the list of today";
 
            wikipedia_wiki = new Wikipedia.wiki( 'Adding discussion to todays list', query, twinklexfd.callbacks.pui.todaysList );
            wikipedia_wiki.params = params;
            wikipedia_wiki.get();
 
            var query = {
                'action': 'query',
                'prop': 'revisions',
                'titles': wgPageName,
                'rvlimit': 1,
                'rvprop': 'user',
                'rvdir': 'newer'
            }
            var callback = function( self ) {
                var xmlDoc = self.responseXML;
                var user = xmlDoc.evaluate( '//rev/@user', xmlDoc, null, XPathResult.STRING_TYPE, null ).stringValue;
                var query = {
                    'title': 'User talk:' + user,
                    'action': 'submit'
                };
                var wikipedia_wiki = new Wikipedia.wiki( 'Notifying of initial contributor (' + user + ')', query, twinklexfd.callbacks.pui.userNotification );
                wikipedia_wiki.params = self.params;
                wikipedia_wiki.get();
            }
            var wikipedia_api = new Wikipedia.api( 'Grabbing data of initial contributor', query, callback );
            wikipedia_api.params = params;
            wikipedia_api.post();
 
            Wikipedia.removeCheckpoint();
 
            // adding tag to captions
            var query = {
                'action': 'query',
                'list': 'imageusage',
                'titles': wgPageName,
                'iulimit': userIsInGroup( 'sysop' ) ? 5000 : 500 // 500 is max for normal users, 5000 for bots and sysops
            };
 
            var wikipedia_api = new Wikipedia.api( 'Grabbing image links', query, twinklexfd.callbacks.pui.tagInstancesMain );
            wikipedia_api.post();
 
        } else {
            // Tagging image
            var query = {
                'title': wgPageName,
                'action': 'submit'
            };
 
            var wikipedia_wiki = new Wikipedia.wiki( 'Tagging image with deletion tag', query, twinklexfd.callbacks.ifd.taggingImage );
            wikipedia_wiki.params = params;
            wikipedia_wiki.get();
 
            // Contributor specific edits
            var query = {
                'action': 'query',
                'prop': 'revisions',
                'titles': wgPageName,
                'rvlimit': 1,
                'rvprop': 'user',
                'rvdir': 'newer'
            }
            var wikipedia_api = new Wikipedia.api( 'Grabbing data of initial contributor', query, twinklexfd.callbacks.ifd.main );
            wikipedia_api.params = params;
            wikipedia_api.post();
 
            // adding tag to captions
            var query = {
                'action': 'query',
                'list': 'imageusage',
                'titles': wgPageName,
                'iulimit': userIsInGroup( 'sysop' ) ? 5000 : 500 // 500 is max for normal users, 5000 for bots and sysops
            };
 
            var wikipedia_api = new Wikipedia.api( 'Grabbing image links', query, twinklexfd.callbacks.ifd.tagInstancesMain );
            wikipedia_api.post();
        }
        Wikipedia.removeCheckpoint();
        break;
    case 'cfd':
        Wikipedia.addCheckpoint();
        if( e.target.xfdtarget ) {
            var target = e.target.xfdtarget.value.replace( /^\:?Category\:/, '' );
        } else {
            var target = '';
        }
 
        var date = new Date();
        var todaysPage = 'Wikipedia:Categories for discussion/Log/' + date.getUTCFullYear() + ' ' + date.getUTCMonthName() + ' ' + date.getUTCDate();
 
        // Updating data for the action completed event
        Wikipedia.actionCompleted.redirect = todaysPage;
        Wikipedia.actionCompleted.notice = "Nomination completed, redirecting now to the discussion page";
 
        // Tagging category
 
        var query = {
            'title': wgPageName,
            'action': 'submit'
        };
        var params = { reason:reason, xfdcat:xfdcat, target:target };
 
        var wikipedia_wiki = new Wikipedia.wiki( 'Tagging category with tag', query, twinklexfd.callbacks.cfd.taggingCategory );
        wikipedia_wiki.params = params;
        wikipedia_wiki.get();
 
        // Todays list
        var query = {
            'title': todaysPage,
            'action': 'submit',
            'section': 2
        };
 
        var wikipedia_wiki = new Wikipedia.wiki( 'Adding discussion to todays list', query, twinklexfd.callbacks.cfd.todaysList );
        wikipedia_wiki.params = params;
        wikipedia_wiki.get();
 
        // Notification to first contributor
        var query = {
            'action': 'query',
            'prop': 'revisions',
            'titles': wgPageName,
            'rvlimit': 1,
            'rvprop': 'user',
            'rvdir': 'newer'
        }
        var callback = function( self ) {
            var xmlDoc = self.responseXML;
            var user = xmlDoc.evaluate( '//rev/@user', xmlDoc, null, XPathResult.STRING_TYPE, null ).stringValue;
            var query = {
                'title': 'User talk:' + user,
                'action': 'submit'
            };
            var wikipedia_wiki = new Wikipedia.wiki( 'Notifying of initial contributor (' + user + ')', query, twinklexfd.callbacks.cfd.userNotification );
            wikipedia_wiki.params = self.params;
            wikipedia_wiki.get();
        }
        var wikipedia_api = new Wikipedia.api( 'Grabbing data of initial contributor', query, callback );
        wikipedia_api.params = { xfdcat:xfdcat, target:target, todaysPage:todaysPage };
        wikipedia_api.post();
        Wikipedia.removeCheckpoint();
        break;
    case 'rfd':
        var query = {
            'action': 'query',
            'titles': wgPageName,
            'redirects': true
        };
        var wikipedia_api = new Wikipedia.api( 'Quering redirect', query, twinklexfd.callbacks.rfd.main );
        wikipedia_api.params = { reason:reason };
        wikipedia_api.post();
        break;
    }
}