Usuário(a):Alchimista/er.js

Origem: Wikipédia, a enciclopédia livre.

Nota: Depois de publicar, poderá ter de contornar a cache do seu navegador para ver as alterações.

  • Firefox / Safari: Pressione Shift enquanto clica Recarregar, ou pressione Ctrl-F5 ou Ctrl-R (⌘-R no Mac)
  • Google Chrome: Pressione Ctrl-Shift-R (⌘-Shift-R no Mac)
  • Internet Explorer / Edge: Pressione Ctrl enquanto clica Recarregar, ou pressione Ctrl-F5
  • Opera: Pressione Ctrl-F5.
// 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 = " usando [[en:WP:TWINKLE|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 = " usando [[en:WP:TWINKLE|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.openUserTalkPageOnSpeedyDelete (array)
 What types of actions that should result user talk page to be opened
 */
if( typeof( TwinkleConfig.openUserTalkPageOnSpeedyDelete ) == 'undefined' ) {
	TwinkleConfig.openUserTalkPageOnSpeedyDelete = [ '1', 'g2', 'g10', 'g11', 'g12', 'a1', 'a7', 'i3', 'i4', 'i5', 'i6', 'i7', 'u3', 't1' ];
}

/**
 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 = [];
}


function twinkleSpeedyDelete() {
	if( wgNamespaceNumber < 0 || wgCurRevisionId == false ) {
		return;
	}
	if( userIsInGroup( 'sysop' ) ) {
		mw.util.addPortletLink( 'p-cactions', "javascript:twinklespeedy()", "ER", "tw-csd", "Speedy delete according to WP:CSD", "");
	} else {
		mw.util.addPortletLink( 'p-cactions', "javascript:twinklespeedy()", "ER", "tw-csd", "Request speedy deletion according to WP:CSD", "");
	}	
}
$(twinkleSpeedyDelete);

function twinklespeedy() {
	twinklespeedy.Window = new SimpleWindow( 800, 450 );
	twinklespeedy.Window.setTitle( "Escolha a regra de eliminação rápida" );

	var form = new QuickForm( userIsInGroup( 'sysop' ) ? twinklespeedy.csdSysopCallback : twinklespeedy.csdUserCallback, 'change' );
	if( userIsInGroup( 'sysop' ) ) {
		form.append( {
				type: 'checkbox',
				name: 'tag_only',
				list: [
					{
						label: 'Colocar apenas para eliminar, não eliminar',
						value: 'tag_only',
						tooltip: 'Se quiser apenas colocar para eliminar, em vez de eliminar agora'
					}
				]
			} );
	}
	if( wgNamespaceNumber ==  6 ) {
		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.'
					},
				]
			} );
	}

	form.append( { type:'header', label:'Lista das regras de eliminação rápida' } );
	form.append( {
			type: 'radio',
			name: 'csd',
			list: [
				{ 
					label: '1: Subpáginas do próprio usuário ',
					value: '1',
					tooltip: 'Subpáginas do próprio usuário (Exemplo: uma eventual página Usuário:Jorge/testes).' 
				},
				{ 
					label: '2: Páginas com endereços de websites no título',
					value: '2',
					tooltip: 'Páginas criadas com endereços de websites no título, desde que não se trate de algum site relevante cujo nome coincide com o endereço web tal como "Americanas.com"'
				},
				{ 
					label: '3: Páginas com títulos absurdos, ou palavras que não o são', 
					value: '3',
					tooltip: 'Só deverão ser eliminadas se ocorrerem as três condições: 1- A página não tem artigos afluentes, ou o artigo afluente também contém lixo; 2- Uma busca no Google pelo termo não produz resultados verossímeis; 3- Não é um engano credível, capaz de servir como redirect'
				},
				{
					label: '4: Páginas com títulos absurdos em termos enciclopédicos',
					value: '4',
					tooltip: 'Páginas com títulos absurdos em termos enciclopédicos, como por exemplo A Pessoa do Professor Enquanto Profissional Educador - por Semíramis Alencar, ou uma eventual página chamada Tou triste e sozinha, me liga, vai; desde que não se trate do título de alguma obra relevante'
				},
				{
					label: '5: Páginas de aparecimento recorrente', 
					value: '5',
					tooltip: 'Páginas de aparecimento recorrente que a comunidade decide eliminar sempre que reaparece. Porém, em casos de dúvidas deve-se colocar novamente para eliminação do modo tradicional'
				},
				{
					label: '6: Páginas em que o título é evidentemente SPAM', 
					value: '6',
					tooltip: 'Páginas cujo título ou único conteúdo é um anúncio, por exemplo, a um "casino online". Só deverá ser colocada para ER se combinar as duas condições: 1- A página não tem artigos afluentes, ou o artigo afluente também contém lixo; 2- O título não seja apenas o nome de uma empresa, marca ou campanha publicitária relevante' 
				},
				{
					label: '7: Páginas em que o próprio criador reconhece que se enganou', 
					value: '7',
					tooltip: 'Só deverão ser eliminadas se ocorrerem as três condições: 1- A página não seja eliminada pelo próprio; 2- A página a eliminar não seja um erro ortográfico comum; 3- A página a eliminar não seja uma entrada válida' 
				},
				{
					label: '8: Eliminações temporárias sem perda de histórico para resolver problemas técnicos.', 
					value: '8',
					tooltip: 'Eliminações temporárias sem perda de histórico para resolver problemas técnicos.' 
				},
				{
					label: '9: Eliminação de redirects se a página a eliminar não tiver um histórico relevante', 
					value: '9',
					tooltip: 'Eliminação de redirects se a página a eliminar não tiver um histórico relevante. Eliminação de um redirect com título X para que a página de destino possa ser movida para o título X. Desta forma o histórico da página de destino não se perde' 
				},
				{
					label: '10: Namespaces (Domínios) que não existem', 
					value: '10',
					tooltip: 'e.g.: Wikipédia: Desde que: 1- O conteúdo válido seja movido para o local adequado; 2- A página não tenha afluentes' 
				},
				{
					label: '11: Páginas com erros devidos à má configuração do teclado ou codificação incorreta do sistema ', 
					value: '11',
					tooltip: 'Como por exemplo: Japão, Santos (São Paulo), Discussão:Página principal. A codificação padrão da Wikipédia é UTF-8' 
				},
				{
					label: '12: Imagens, quando o pedido for feito por quem carregou a imagem e desde que esta não esteja a ser utilizada por um artigo', 
					value: '12',
					tooltip: '' 
				},
				{
					label: '13: Páginas sem histórico relevante que são violações flagrantes de direitos autorais de outras páginas na internet', 
					value: '13',
					tooltip: 'Por histórico relevante entende-se qualquer contribuição ao artigo que não se limite a redirecionamentos, intelinks, categorias e wikificação' 
				},
				{
					label: '14: Eliminação de ficheiros (arquivos) duplicados', 
					value: '14',
					tooltip: 'Regras: 1- Ficheiros iguais que estão sobre nomes diferentes; 2- Ficheiros que já estão no Wikimedia Commons; 3- No motivo da eliminação deve constar o atalho para o ficheiro já existente; 4- Os afluentes devem ser corrigidos: 5- Arquivos iguais que estão sob outra extensão, mantendo-se o formato JPG para fotografias, GIF para animações, PNG para outras imagens, e OGG para som e vídeo' 
				},
				{
					label: '15: Páginas com o título mal formatado', 
					value: '15',
					tooltip: 'Só deverá ser eliminada se ocorrerem as duas condições: 1- Se tenha movido o conteúdo para um título formatado de acordo com o livro de estilo; 2- Não seja o proponente a eliminar a página' 
				},
				{
					label: '16: Artigos que resultam de uma fusão, cujo título não se enquadre nas convenções do Livro de Estilo', 
					value: '16',
					tooltip: 'Artigos que resultam de uma fusão, cujo título não se enquadre nas convenções do Livro de Estilo. Exemplo: ero ortográfico. Só deverá ser eliminada se ocorrerem as duas condições: 1- Desde que não seja o proponente; 2- Desde que os afluentes tenham sido corrigidos' 
				},
				{
					label: '17: Títulos que são redirects do namespace principal para outro', 
					value: '17',
					tooltip: 'Só deverá ser eliminada desde que não seja o proponente' 
				},
				{
					label: '18: Páginas de discussão cujos artigos não existem (para todos os domínios)', 
					value: '18',
					tooltip: '' 
				},
				{
					label: '19: Todos os ficheiros carregados (domínio Imagem:) que não são som, imagem ou vídeo', 
					value: '19',
					tooltip: '' 
				},
				{ 
					label: '20: Lixo ou impróprio', 
					value: '20', 
					tooltip: ':Podem ser eliminados por Eliminação rápida os artigos que encaixam no perfil de lixo e impróprio' },
                                {
					label: '21: Página de renomeação', 
					value: '21',
					tooltip: 'Uma página já votada em WP:PE e mantida só pode tornar a ser nomeada para eliminação após um prazo de seis meses a contar da última nomeação. Caso uma renomeação seja feita antes deste prazo, a nova página de votação iniciada pode ser eliminada' 
				},
			]
		});

	twinklespeedy.rendered = form.render();
	twinklespeedy.Window.setContent( twinklespeedy.rendered );
	twinklespeedy.Window.display();
}

twinklespeedy.normalizeHash = {
	'1': '1',
	'2': '2',
	'3': '3',
	'4': '4',
	'5': '5',
	'6': '6',
	'7': '7',
	'8': '8',
	'9': '9',
	'10': '10',
	'11': '11',
	'12': '12',
	'13': '13',
	'14': '14',
	'15': '15',
	'16': '16',
	'17': '17',
	'18': '18',
	'19': '19',
	'20': '20',
	'21': '21',
	'redundantimage': 'i1',
	'noimage': 'i2',
	'noncom': 'i3',
	'unksource': 'i4',
	'unfree': 'i5',
	'norat': 'i6',
	'badfairuse': 'i7',
	'nowcommons': 'i8',
	'catempty': 'c1',
	'catfd': 'c3',
	'userreq': 'u1',
	'nouser': 'u2',
	'u3': 'u3',
	'divisive': 't1',
	'emptyportal': 'p2'
};

twinklespeedy.reasonHash = {
	'20': 'lixo ou impróprio',
	'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 that wasn\'t been used 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',
	'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.csdSysopCallback = function(e) {

	if( e.target.value == 'tag_only' ) {
		return;
	}
	var tag_only = e.target.form.tag_only.checked;
	if( tag_only ) {
		return twinklespeedy.csdUserCallback(e);
	}


	var value = e.target.value;
	var normalized = twinklespeedy.normalizeHash[ value ];
	twinklespeedy.normalized = normalized;
	twinklespeedy.watch = TwinkleConfig.watchSpeedyPages.indexOf( normalized ) != -1;
	twinklespeedy.usertalk = TwinkleConfig.openUserTalkPageOnSpeedyDelete.indexOf( normalized ) != -1;

	var reason = twinklespeedy.reasonHash[ value ];

	twinklespeedy.summary = " ([[WP:ER" + "|Regra " + normalized + "]]), " + reason + "." + TwinkleConfig.deletionSummaryAd;
	Status.init( twinklespeedy.rendered );

	Status.status( 'Obtendo página' );

	xmlhttp = sajax_init_object();
	xmlhttp.query = { 
		'title': wgPageName, 
		'action': 'delete'
	};

	xmlhttp.overrideMimeType('text/xml');
	xmlhttp.open( 'GET' , wgServer + wgScriptPath + '/index.php?' + QueryString.create( xmlhttp.query ), true );
	xmlhttp.onload = function() {

		if( this.responseText.indexOf( 'var wgCurRevisionId = false;' ) != -1 ) {
			Status.error( "It seems that the page doesn't exists, perhaps it has already been deleted" );
			return;
		}

		Status.status( 'Eliminando página...' );

		form = this.responseXML.getElementById( 'deleteconfirm' );

		var postData = {
			'wpWatch': twinklespeedy.watch ? '' : form.wpWatch.checked ? '' : undefined,
			'wpReason': twinklespeedy.summary,
			'wpEditToken': form.wpEditToken.value
		}

		var xmlhttp = sajax_init_object();
		xmlhttp.overrideMimeType('text/xml');
		xmlhttp.open( 'POST' , wgServer + wgScriptPath + '/index.php?' + QueryString.create( this.query ), true);
		xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		xmlhttp.onload = function() { Status.info( 'Page/Image deleted, remember to wait until it\'s all done.' ) };
		xmlhttp.send( QueryString.create( postData ) );


		// Deleting talk page if requested
		if( TwinkleConfig.deleteTalkPageOnDelete && wgNamespaceNumber % 2 == 0 && document.getElementById( 'ca-talk' ).className != 'new' ) {
			Status.status( 'Deleting talk page' );
			var talk_page = namespaces[ wgNamespaceNumber  + 1 ] + ':' + wgTitle;
			xmlhttp = sajax_init_object();
			xmlhttp.query = {
				'title': talk_page,
				'action': 'delete'
			};
			xmlhttp.overrideMimeType('text/xml');
			xmlhttp.open( 'GET' , wgServer + wgScriptPath + '/index.php?' + QueryString.create( xmlhttp.query ),  true );
			xmlhttp.onload = function(e) {

				var form = this.responseXML.getElementById( 'deleteconfirm' );
				if( form ) {
					var postData = {
						'wpWatch': twinklespeedy.watch ? '' : form.wpWatch.checked ? '' : undefined,
						'wpReason': "Speedy deleted per ([[WP:CSD#g8|CSD g8]]), was a talk page of deleted page." + TwinkleConfig.deletionSummaryAd,
						'wpEditToken': form.wpEditToken.value
					}

					xmlhttp = sajax_init_object();
					xmlhttp.overrideMimeType('text/xml');
					xmlhttp.open( 'POST' , wgServer + wgScriptPath + '/index.php?' + QueryString.create( this.query ), false);
					xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
					xmlhttp.onload = function()  { Status.info( "Talkpage deleted") }
					xmlhttp.send( QueryString.create( postData ) );

				} else {
					Status.warn( 'No delete form for talk page found, won\'t try to delete talk page' );
				}
			}
			xmlhttp.send( null );
		}

		// Open user talk page if requested
		if( twinklespeedy.usertalk ) {
			Status.status( 'Obtendo dados sobre o primeiro editor' );
			var query = {
				'action': 'query',
				'prop': 'revisions',
				'titles': wgPageName,
				'rvlimit': 1,
				'rvprop': 'user',
				'rvdir': 'newer',
				'format': 'xml'
			}
			xmlhttp = sajax_init_object();
			xmlhttp.overrideMimeType('text/xml');
			xmlhttp.open( 'GET' , wgServer + wgScriptPath + '/api.php?' + QueryString.create( query ), true );
			xmlhttp.onload = function() {
				var user = this.responseXML.documentElement.getElementsByTagName('rev')[0].getAttribute('user'); // TODO -> xpath

				Status.status( 'Opening user talk page' );

				var query = {
					'title': 'User talk:' + user,
					'action': 'edit',
					'vanarticle': wgPageName.replace(/_/g, ' ')
				};
				switch( TwinkleConfig.userTalkPageMode ) {
				case 'tab':
					window.open( wgServer + wgScriptPath + '/index.php?' + QueryString.create( query ), '_tab' );
					break;
				case 'blank':
					window.open( wgServer + wgScriptPath + '/index.php?' + QueryString.create( query ), '_blank', 'location=no,toolbar=no,status=no,directories=no,scrollbars=yes,width=1200,height=800' );
					break;
				case 'window':
					default :
					window.open( wgServer + wgScriptPath + '/index.php?' + QueryString.create( query ), 'twinklewarnwindow', 'location=no,toolbar=no,status=no,directories=no,scrollbars=yes,width=1200,height=800' );
					break;
				}
			}
			xmlhttp.send( null );
		}

		if( wgNamespaceNumber == 6 && twinklespeedy.normalized != 'i8' ) {

			var statusIndicator = document.createElement( 'div' );
			Status.status( [ statusIndicator ] );
			statusIndicator.appendChild( document.createTextNode( 'Removing usage of image, status: ' ) );
			statusIndicator.appendChild( document.createTextNode( '0%' ) );
			// removing instances of the image
			var xmlhttp = sajax_init_object();
			xmlhttp.statusIndicator = statusIndicator;
			xmlhttp.query = {
				'action': 'query',
				'list': 'imageusage',
				'titles': wgPageName,
				'iulimit': 500, 
				'format': 'xml'
			};
			xmlhttp.overrideMimeType('text/xml');		
			xmlhttp.open( 'GET' , wgServer + wgScriptPath + '/api.php?' + QueryString.create( xmlhttp.query ), true);
			xmlhttp.onload = function() {

				var xmlDoc = this.responseXML;
				var nsResolver = xmlDoc.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
				var count = xmlDoc.evaluate( 'count(//imageusage/iu)', xmlDoc, nsResolver, XPathResult.ANY_TYPE, null );

				var nofnodes = count.numberValue * 2;

				counter = 0;
				updateCounter = function(obj, total) {
					obj.replaceChild( document.createTextNode( parseInt( 100 * ++counter/total ) + '%' ), obj.lastChild );
					if( counter == total ) {
						Status.info( 'removal of instances completed.' );

					}
				}

				var snapshot = xmlDoc.evaluate('//imageusage/iu/@title', xmlDoc, nsResolver, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );

				for ( var i = 0; i < snapshot.snapshotLength; ++i ) {
					(function(title, total, obj) {
							var xmlhttp = sajax_init_object();
							xmlhttp.query = {
								'title': title,
								'action': 'submit'
							};
							xmlhttp.overrideMimeType('text/xml');
							xmlhttp.open( 'GET' , wgServer + wgScriptPath + '/index.php?' + QueryString.create( xmlhttp.query ), true);
							xmlhttp.onload = function() {

								var form = this.responseXML.getElementById('editform');
								var text = form.wpTextbox1.value;
								var old_text = text;
								var wikiPage = new Mediawiki.Page( text );
								wikiPage.commentOutImage( wgTitle, 'Commented out because image was deleted' );

								text = wikiPage.getText();
								updateCounter( obj, total );
								if( text == old_text ) {
									// Nothing to do, return
									updateCounter( obj, total );
									return;
								} else {
									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 ' + wgTitle + " that has been speedied deleted per ([[WP:CSD#" + twinklespeedy.normalized.toUpperCase() + "|CSD " + twinklespeedy.normalized.toUpperCase() + "]])" + "; " + TwinkleConfig.deletionSummaryAd,
										'wpTextbox1': text
									};
									var xmlhttp = sajax_init_object();
									xmlhttp.overrideMimeType('text/xml');
									xmlhttp.open( 'POST' , wgServer + wgScriptPath + '/index.php?' + QueryString.create( this.query ), true);
									xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
									xmlhttp.onload = function() {
										updateCounter( obj, total );
									}
									xmlhttp.send( QueryString.create( postData ) );

								}


							}				
							xmlhttp.send( null );
						})( snapshot.snapshotItem(i).value, nofnodes, this.statusIndicator );

				}

			}
			xmlhttp.send( null );
		}
	};
	xmlhttp.send( null );
}



twinklespeedy.csdUserCallback = function(e) {

	var value = e.target.value;
	var normalized = twinklespeedy.normalizeHash[ value ];
	twinklespeedy.watch = TwinkleConfig.watchSpeedyPages.indexOf( normalized ) != -1;
	twinklespeedy.usertalk = TwinkleConfig.openUserTalkPageOnSpeedyDelete.indexOf( normalized ) != -1;

	var reason = twinklespeedy.reasonHash[ value ];

	twinklespeedy.summary = "Colocando para eliminação rápida ([[WP:ER" + "|Regra " + normalized + "]])." + TwinkleConfig.summaryAd;
	switch( normalized ) {
	case 'i8':
		var date = new Date();
		twinklespeedy.code = "\{\{NowCommons|month=" + date.getUTCMonthName() + "|day=" + date.getUTCDate() + "|year=" + date.getUTCFullYear() + "|1=" + wgPageName.replace( '_', ' ' ) + "\}\}";
		break;
	case 'g12':
		url = prompt( 'please enter url if available, including the http://' );
		if( url == null ) {
			return;
		}
		twinklespeedy.code = "\{\{db-" +  value + "|url=" + url + "\}\}";
		break;
	case 'i1':
		img = prompt( 'enter the image this is redundant to, excluding the Image: prefix' );
		if( img == null ) {
			return;
		}
		twinklespeedy.code = "\{\{db-" +  value + "|1=" + img + "\}\}";
		break;
	default:
		twinklespeedy.code = "\{\{ER|" +  value + "|2=\~\~\~\~" + "\}\}";
		break;
	}

	Status.init( twinklespeedy.rendered );

	Status.status( 'Updating the page' );

	xmlhttp = sajax_init_object();
	xmlhttp.query = {
		'title': wgPageName,
		'action': 'submit'
	}
	xmlhttp.overrideMimeType('text/xml');
	xmlhttp.open( 'GET' , wgServer + wgScriptPath + '/index.php?' + QueryString.create( xmlhttp.query ), true);
	xmlhttp.onload = function() {

		if( this.responseText.indexOf( 'var wgCurRevisionId = false;' ) != -1 ) {
			Status.error( "It seems that the page doesn't exists, perhaps it has already been deleted" );
			return;
		}
		form = this.responseXML.getElementById( 'editform' );

		var text = form.wpTextbox1.value;

		Status.status( 'Checking for tags on the page...' );

		var tag = /(\{\{(?:db-?|delete)\|?.*?\}\})/.exec( text );

		if( tag ) {
			Status.warn( [ htmlNode( 'strong', tag[0] ) , " is alread 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;
		}

		Status.status( 'Actualizando a página...' );
		var postData = {
			'wpMinoredit': TwinkleConfig.markSpeedyPagesAsMinor ? true : form.wpMinoredit.checked ? '' : undefined,
			'wpWatchthis': twinklespeedy.watch ? true : form.wpWatchthis.checked ? '' : undefined,
			'wpStarttime': form.wpStarttime.value,
			'wpEdittime': form.wpEdittime.value,
			'wpAutoSummary': form.wpAutoSummary.value,
			'wpEditToken': form.wpEditToken.value,
			'wpSummary': twinklespeedy.summary,
			'wpTextbox1': twinklespeedy.code + "\n" + text
		};
		var xmlhttp = sajax_init_object();
		xmlhttp.overrideMimeType('text/xml');
		xmlhttp.open( 'POST' , wgServer + wgScriptPath + '/index.php?' + QueryString.create( this.query ), true);
		xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		xmlhttp.onload = function() { Status.info( 'Page tagged' ) };
		xmlhttp.send( QueryString.create( postData ) );
	}
	xmlhttp.send( null );

	// Open user talk page if requested
	if( twinklespeedy.usertalk ) {
		Status.status( 'Obtendo dados sobre o primeiro editor' );
		var query = {
			'action': 'query',
			'prop': 'revisions',
			'titles': wgPageName,
			'rvlimit': 1,
			'rvprop': 'user',
			'rvdir': 'newer',
			'format': 'xml'
		}
		xmlhttp = sajax_init_object();
		xmlhttp.overrideMimeType('text/xml');
		xmlhttp.open( 'GET' , wgServer + wgScriptPath + '/api.php?' + QueryString.create( query ), true );
		xmlhttp.onload = function() {
			var user = this.responseXML.documentElement.getElementsByTagName('rev')[0].getAttribute('user'); // TODO -> xpath

			Status.status( 'Abrindo página de discussão do usuário' );

			var query = {
				'title': 'User talk:' + user,
				'action': 'edit',
				'vanarticle': wgPageName.replace(/_/g, ' ')
			}
			switch( TwinkleConfig.userTalkPageMode ) {
			case 'tab':
				window.open( wgServer + wgScriptPath + '/index.php?' + QueryString.create( query ), '_tab' );
				break;
			case 'blank':
				window.open( wgServer + wgScriptPath + '/index.php?' + QueryString.create( query ), '_blank', 'location=no,toolbar=no,status=no,directories=no,scrollbars=yes,width=1200,height=800' );
				break;
			case 'window':
				default :
				window.open( wgServer + wgScriptPath + '/index.php?' + QueryString.create( query ), 'twinklewarnwindow', 'location=no,toolbar=no,status=no,directories=no,scrollbars=yes,width=1200,height=800' );
				break;
			}
		}
		xmlhttp.send( null );
	}
}