mw.loader.using().then(function() {
function userIsInGroup(group) {
  return mw.config.get('wgUserGroups').indexOf(group) > -1;
}
// 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 ]
 */
if( typeof( TwinkleConfig.summaryAd ) == 'undefined' ) {
	TwinkleConfig.summaryAd = " usando ]";
}
 
/**
 TwinkleConfig.deletionSummaryAd (string)
 If ad should be added or not to deletion summary, default ]
 */
if( typeof( TwinkleConfig.deletionSummaryAd ) == 'undefined' ) {
	TwinkleConfig.deletionSummaryAd = " usando ]";
}
 
 
/**
 TwinkleConfig.watchSpeedyPages (array)
 What types of actions that should result in forced addition to watchlist
 */
if( typeof( TwinkleConfig.watchSpeedyPages ) == 'undefined' ) {
	TwinkleConfig.watchSpeedyPages = ;
}
 
/**
 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 = ;
}
 
/**
 TwinkleConfig.userTalkPageMode may take arguments:
 'window': open a new window, remember 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 (BR 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: , orphan:false };
}
 
function twinklespeedy() {
	if( mw.config.get('wgNamespaceNumber') < 0 || mw.config.get('wgCurRevisionId') == false ) {
		return;
	}
	if( userIsInGroup( 'sysop' ) ) {
		mw.util.addPortletLink( 'p-cactions', "javascript:twinklespeedy.callback()", "br", "tw-BR", "Borrar esta página", "");
	} else if (twinkleConfigExists) {
		mw.util.addPortletLink( 'p-cactions', "javascript:twinklespeedy.callback()", "br", "tw-BR", "Marcar para borrado esta página", "");
	}
	else
	{
		mw.util.addPortletLink('p-cactions', 'javascript:alert("Tu cuenta es muy nueva para usar Twinkle.");', 'BR', 'tw-BR', 'Destruir', '');
	}
}
$(twinklespeedy);
 
twinklespeedy.callback = function twinklespeedyCallback() {
	var Window = new SimpleWindow( 800, 400 );
	Window.setTitle( "Borrado de artículos" );
 
	var form = new QuickForm( userIsInGroup( 'sysop' ) ? twinklespeedy.callback.evaluateSysop : twinklespeedy.callback.evaluateUser, 'change' );
	if( userIsInGroup( 'sysop' ) ) {
		form.append( {
				type: 'checkbox',
				list: [
					{
						label: 'Marcar página, no borrar',
						value: 'tag_only',
						name: 'tag_only',
						tooltip: 'Si solo deseas marcar la página para su borrado',
						event: function( event ) {
							event.target.form.notify.disabled = ! event.target.checked;
							event.stopPropagation();
						}
					},
					{
						label: 'Quitar enlaces',
						value: 'orphan_backlinks',
						name: 'orphan_backlinks',
						tooltip: 'Si deseas quitar los enlaces a esta página',
						checked: TwinkleConfig.orphanBacklinksOnSpeedyDelete.orphan,
						event: function( event ) {
							TwinkleConfig.orphanBacklinksOnSpeedyDelete.orphan = event.target.checked;
							event.stopPropagation();
						}
					}
				]
			} );
	}
 
	form.append( {
			type: 'checkbox',
			list: [
				{
					label: 'Aviso al autor',
					value: 'notify',
					name: 'notify',
                                        tooltip: 'Notifica al autor del artículo',
					checked: true,
					disabled: userIsInGroup( 'sysop' ),
					event: function( event ) {
						event.stopPropagation();
					}
				}
			]
		}
	);
	form.append( { type:'header', label:'Criterio general' } );
	form.append( {
			type: 'radio',
			name: 'br',
			list: [
				{ 
					label: 'No enciclopédico', 
					value: 'No enciclopédico', 
					tooltip: 'Artículos de personas, grupos musicales, páginas web o empresas, entre otros, que claramente no cuentan con relevancia enciclopédica.' },
				{ 
					label: 'Página de pruebas',
					value: 'Página de pruebas',
					tooltip: 'Páginas que evidentemente fueron una prueba de edición.' 
				},

				{
					label: 'Recreación de material borrado',
					value: 'Recreación de material borrado',
					tooltip: 'Páginas borradas anteriormente tras una consulta de borrado y recreadas por el autor en contra del criterio de borrado que llevó a su eliminación.'
				},
				{
					label: 'A petición del autor',
					value: 'A petición del autor',
					tooltip: 'A petición del único autor del artículo, siempre que no haya más ediciones en el historial si este desea fusionar el texto en otro artículo o publicarlo de otra forma. Téngase en cuenta que muchos usuarios novatos que desconocen este sistema, tratan de borrarlo blanqueando la página.'
				},
				{ 
					label: 'Vandalismo',
					value: 'Vandalismo', 
					tooltip: 'Vandalismo hecho y derecho.'
				},
				{ 
					label: 'Infraesbozo', 
					value: 'Infraesbozo', 
					tooltip: 'Artículos demasiado reducidos.' 
				},
				{ 
					label: 'Promocional', 
					value: 'Promocional', 
					tooltip: 'Artículos promocionales.' 
				},
				{ 
					label: 'Otros', 
					value: 'Otros', 
					tooltip: 'Elige un motivo personalizado que no encaje con los motivos anteriores.' 
				}
			]
		} ); 
if( mw.config.get('wgNamespaceNumber') ==  0 || mw.config.get('wgNamespaceNumber') == 1 ) {
	form.append( { type:'header', label:'Artículos' } );
	form.append( {
			type: 'radio',
			name: 'br',
			list: [
				{
					label: 'Demasiado corto',
					value: 'Demasiado corto',
					tooltip: 'Artículos muy pequeños.'
				},
				{
					label: 'No traducido',
					value: 'No traducido',
					tooltip: 'Si el artículo esta en su totalidad en otro idioma que no es español'
				},
				{
					label: 'Sin contenido',
					value: 'Sin contenido',
					tooltip: 'Artículos vacíos en su totalidad'
				},
				{
					label: 'Biografía sin relevancia',
					value: 'Biografía sin relevancia',
					tooltip: 'Biografía de una persona sin relevancia enciclopedica'
				},
				{ 
					label: 'Plagio', 
					value: 'Violación de derechos de autor', 
					tooltip: 'Páginas que obviamente son un plagio de otra página.' 
				},
				{ 
					label: 'Copyvio', 
					value: 'Copyvio', 
					tooltip: 'Artículos que podrían suponer una infracción al copyright.' 
				},
				{ 
					label: 'Otros', 
					value: 'Otros', 
					tooltip: 'Elige un motivo personalizado que no encaje con los motivos anteriores.' 
				}
			]
		} );
}
	form.append( { type:'header', label: 'Redirecciones' } );
	form.append( {
			type: 'radio',
			name: 'br',
			list: [
				{ 
					label: 'Redirecciones a páginas no existentes',
					value: 'Redirecciones a páginas no existentes'
				}
			]
		} );
if( mw.config.get('wgNamespaceNumber') ==  2 || mw.config.get('wgNamespaceNumber') == 3 ) {
	form.append( { type:'header', label: 'Páginas de usuario' } );
	form.append( {
			type: 'radio',
			name: 'br',
			list: [
				{
					label: 'A petición de autor',
					value: 'A petición de autor',
					tooltip: 'Subpáginas que el autor desea nominar para su borrado'
				},
				{
					label: 'Usuario no existente',
					value: 'Usuario no existente',
					tooltip: 'Páginas de usuarios que no existen'
				},
			]
		} );
	form.append( { type:'header', label: 'Violaciones a derechos de autor' } );
	form.append( {
			type: 'radio',
			name: 'br',
			list: [
				{ 
					label: 'Plagio', 
					value: 'Violación de derechos de autor', 
					tooltip: 'Páginas que obviamente son un plagio de otra página.' 
				},
				{ 
					label: 'Copyvio', 
					value: 'Copyvio', 
					tooltip: 'Artículos que podrían suponer una infracción al copyright.' 
				}
			]
		} ); 
	form.append( { type:'header', label: 'Otras razones' } );
	form.append( {
			type: 'radio',
			name: 'br',
			list: [
				{ 
					label: 'Otra opción', 
					value: 'Otros', 
					tooltip: 'Elige un motivo personalizado que no encaje con los motivos anteriores.' 
				}
			]
		} ); }
	var result = form.render();
	Window.setContent( result );
	Window.display();
}
 
twinklespeedy.normalizeHash = {
	'Otros': 'g15',
	'Página de pruebas': 'g2',
	'No relevancia': 'g3',
	'Recreación de material borrado': 'g4',
	'A petición del autor': 'g7',
	'Vandalismo': 'g1',
	'Promocional': 'i2',
	'Violación de derechos de autor': 'g12',
	'Copyvio': 'g13',
	'Demasiado corto': 'a1',
	'No traducido': 'a2',
	'Sin contenido': 'a3', 
	'Biografía sin relevancia': 'a5',
	'Redirecciones a páginas no existentes': 'r1',
	'A petición de autor': 'u1',
	'Usuario no existente': 'u2',
	'No enciclopédico': 'i5',
};
 
twinklespeedy.reasonHash = {
	'Otros': 'Página con ediciones vandálicas',
	'Página de pruebas': 'Pruebas',
	'No relevancia': 'Irrelevante',
	'Recreación de material borrado': 'Recreación de material borrado',
	'A petición del autor': 'A petición del autor',
	'Vandalismo': 'Vandalismos varios',
	'Promocional': 'Promocional',
	'Violación de derechos de autor': 'Plagio',
	'Copyvio': 'Violación de derechos de autor',
	'Demasiado corto': 'Demasiado corto',
	'No traducido': 'No traducido',
	'Sin contenido': 'Sin contenido', 
	'Biografía sin relevancia': 'Biografía sin relevancia',
	'Redirecciones a páginas no existentes': 'Redirecciones a páginas no existentes',
	'A petición de autor': 'A petición de autor',
	'Usuario no existente': 'Usuario no existente',
	'No enciclopédico': 'Sin relevancia enciclopédica',
};
 
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)', xmlDoc, null, XPathResult.BOOLEAN_TYPE, null ).booleanValue;
 
			if( ! exists ) {
				self.statelem.error( "Parece que la página ya fue borrada" );
				return;
			}
			var query = { 
				'title': mw.config.get('wgPageName'), 
				'action': 'delete'
			};
 
			var wikipedia_wiki = new Wikipedia.wiki( 'Borrando página', query, twinklespeedy.callbacks.sysop.deletePage );
			wikipedia_wiki.params = self.params;
			wikipedia_wiki.followRedirect = false;
			wikipedia_wiki.get();
 
			if( 
				TwinkleConfig.deleteTalkPageOnDelete && 
				mw.config.get('wgNamespaceNumber') % 2 == 0 && 
				document.getElementById( 'ca-talk' ).className != 'new' 
			) {
				var talk_page = namespaces + ':' + mw.config.get('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( mw.config.get('wgNamespaceNumber') == 6 && self.params.normalized != 'i8' ) {
				var query = {
					'action': 'query',
					'list': 'imageusage',
					'titles': mw.config.get('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': mw.config.get('wgPageName'),
					'bllimit': userIsInGroup( 'sysop' ) ? 5000 : 500, // 500 is max for normal users, 5000 for bots and sysops
					'blnamespace':  // 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': mw.config.get('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 + ' (terminado)' );
					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 = mw.config.get('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,
				'wpSection': '',
				'wpSummary': 'Quitando enlaces hacia ' + self.params.page + " que fue borrado" + "; " + 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 + ' (terminado)' );
					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( "Borrando " + 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' );
				var postData = {
					'wpDeleteReasonList': 'other',
					'wpReason': "Borrado exprés por (]), redirección inválida \"" + mw.config.get('wgPageName') + "\"." + TwinkleConfig.deletionSummaryAd,
					'wpEditToken': form.wpEditToken.value
				}
			} else {
 
				var postData = {
					'wpWatch': form.wpWatch.checked ? '' : undefined,
					'wpDeleteReasonList': 'other',
					'wpReason': "Borrado exprés por (]), Redirect to deleted page \"" + mw.config.get('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 = mw.config.get('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,
				'wpSection': '',
				'wpSummary': 'Removing instance of image ' + self.params.image + " that has been speedily deleted per (])" + "; " + 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' );
				var postData = {
					'wpDeleteReasonList': 'other',
					'wpReason': "Borrado exprés por (]), " + 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': "Borrado Express: " + 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': "Borrado exprés por (]), 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)', 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': mw.config.get('wgPageName'), 
				'action': 'submit'
			};
 
			var wikipedia_wiki = new Wikipedia.wiki( 'Nominando página', 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( 'Checando por plantillas existentes...' );
 
			var tag = /(\{\{(destruir\|?|destruir)\|?.*?\}\})/.exec( text );
 
			if( tag ) {
				self.statelem.error(  ) , " ya está colocada en el artículo." ] )
				return;
			}
 
			var xfd = /(\{\{(destruir|destruir)*?\}\})/i.exec( text );
 
			if( xfd && !confirm( "Ya se ha colocado la plantilla " + xfd + " , deseas continuar?" ) ) {
				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=" + mw.config.get('wgPageName').replace( '_', ' ' ) + "\}\}";
				break;
			case 'g12':
				var url = prompt( 'Inserta una URL si hay, incluyendo el http://' );
				if( url == null ) {
					return;
				}
				code = "\{\{plagio\|1=" + url + "|2=\~\~\~\~\}\}";
				break;
			case 'g13':
				var url = prompt( 'Inserta una URL si hay, incluyendo el http://' );
				if( url == null ) {
					return;
				}
				code = "\{\{Copyvio\|1=" + url + "|2=\~\~\~\~|3=\{\{subst:CURRENTDAY\}\}|4=\{\{subst:CURRENTMONTHNAME\}\}\}\}";
				break;
			case 'g15':
				var url = prompt( 'Razón para su borrado:' );
				if( url == null ) {
					return;
				}
				code = "\{\{destruir\|" + url + "\}\}";
				break;
			case 'i1':
				var img = prompt( 'enter the image this is redundant to, excluding the Image: prefix' );
				if( img == null ) {
					return;
				}
				code = "\{\{destruir\|" +  self.params.value + "|1=" + img + "\}\}";
				break;
			default:
				code = "\{\{destruir\|" +  self.params.value + "\}\}";
				break;
			}
 
			// Notification to first contributor
			var query = {
				'action': 'query',
				'prop': 'revisions',
				'titles': mw.config.get('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': 'Usuario discusión:' + user,
					'action': 'submit'
				};
				var wikipedia_wiki = new Wikipedia.wiki( 'Notificando al usuario (' + 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,
				'wpSection': '',
				'wpSummary': "Marcando página para destruir " + 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:Usuario:TwinkleUser/Aviso BR|1=" + mw.config.get('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,
				'wpSection': '',
				'wpSummary': 'Notificación: Borrado de \\].' + TwinkleConfig.summaryAd,
				'wpTextbox1': text
			};
			self.post( postData );
		}
	}
}
 
twinklespeedy.callback.evaluateSysop = function twinklespeedyCallbackEvaluateSysop(e) {
 
	wgPageName = mw.config.get('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;
 
	var params = {
		value: value,
		normalized: normalized,
		watch: TwinkleConfig.watchSpeedyPages.indexOf( normalized ) != -1,
		reason: twinklespeedy.reasonHash
	};
	Status.init( e.target.form );
 
	var query = {
		'action': 'query',
		'titles': mw.config.get('wgPageName')
	}
	var wikipedia_api = new Wikipedia.api( 'Viendo si la página existe', query, twinklespeedy.callbacks.sysop.main );
	wikipedia_api.params = params;
	wikipedia_api.post();
}
 
 
 
twinklespeedy.callback.evaluateUser = function twinklespeedyCallbackEvaluateUser(e) {
	wgPageName = mw.config.get('wgPageName').replace( /_/g, ' ' ); // for queen/king/whatever and country!
	var value = e.target.value;
	var normalized = twinklespeedy.normalizeHash;
 
	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 = mw.config.get('wgPageName');
	Wikipedia.actionCompleted.notice = "Terminado";
 
	var query = {
		'action': 'query',
		'titles': mw.config.get('wgPageName')
	}
 
	var wikipedia_api = new Wikipedia.api( 'Viendo si la página existe', query, twinklespeedy.callbacks.user.main );
	wikipedia_api.params = params;
	wikipedia_api.post();
 
}
} );