MediaWiki:Gadget-fastbuttons.js: diferenças entre revisões

Origem: Wikipédia, a enciclopédia livre.
Conteúdo apagado Conteúdo adicionado
Rjclaudio (discussão | contribs)
pedido no PA/O: correção de bug
pedido nos PAs
Linha 8: Linha 8:
/*jslint browser: true, white: true, devel: true, plusplus: true, continue: true */
/*jslint browser: true, white: true, devel: true, plusplus: true, continue: true */
/*global jQuery, mediaWiki */
/*global jQuery, mediaWiki */
( function ( $, mw /* , undefined */ ) {
( function ( $, mw ) {
'use strict';
'use strict';

var fb = {
var fb = {
// Replace this string by 5~ before saving:
// Replace this string by 5~ before saving:
version: '15h02min de 10 de julho de 2012 (UTC)',
version: '17h16min de 11 de julho de 2012 (UTC)',
ns: mw.config.get('wgNamespaceNumber'),
ns: mw.config.get( 'wgNamespaceNumber' ),
title: mw.config.get('wgTitle'),
title: mw.config.get( 'wgTitle' ),
submenu: {},
submenu: {},
$menu: $( '<div id="fb-menu"></div>' ),
$menu: $( '<div id="fb-menu" />' ),
$submenu: $( '<div id="fb-submenu"></div>' )
$submenu: $( '<div id="fb-submenu" />' )
},
};
// FIXME: Move these variables to the scope where they are really needed
esbText = '',
esbText2 = '';


/* Create new button links
/* Create new button links
Linha 34: Linha 32:
*/
*/
fb.addButton = function ( $target, buttons ) {
fb.addButton = function ( $target, buttons ) {
var comment, props, button, i,
var comment, props, button, i,
doNothing = function(e){
doNothing = function( event ) {
e.preventDefault();
event.preventDefault();
},
},
buttonClick = function( btn ){
return function(e){
buttonClick = function( btn ){
return function( event ){
var question = typeof btn.action === 'string'
&& btn.action.substr(0,2) === 'ER'
var question = typeof btn.action === 'string'
&& btn.action.substr( 0, 2 ) === 'ER'
? 'Se necessário, coloque uma observação.'
? 'Se necessário, coloque uma observação.'
: btn.prompt, promptCallback;
: btn.prompt, promptCallback;
e.preventDefault();
promptCallback = function ( comment ){
event.preventDefault();
if( $.isFunction( btn.action ) ) {
btn.action();
promptCallback = function( comment ){
} else {
if ( $.isFunction( btn.action ) ) {
fb.run( btn.action, comment);
btn.action();
}
} else {
fb.run( btn.action, comment);
}
};
if ( question ) {
comment = fb.nicePrompt( question, btn.label, promptCallback );
} else {
promptCallback ( comment );
}
};
};
};
if ( question ) {
if ( !$target.jquery ) {
comment = fb.nicePrompt( question, btn.label, promptCallback );
// if $target is not an instance of jQuery, use it as 'buttons'
} else {
promptCallback ( comment );
buttons = $target;
$target = fb.$menu;
}
if ( !$.isArray( buttons ) ){
buttons = [ buttons ];
}
for ( i = 0; i < buttons.length; i++ ) {
button = buttons[ i ];
props = {
title: button.title,
text: button.text
};

if ( button.disable ) {
props[ 'class' ] = 'fb-button fb-disabled-button',
props.click = doNothing;
} else {
props[ 'class' ] = $.isFunction( button.action )
? 'fb-button fb-menu-button'
: 'fb-button fb-action-button',
props.click = buttonClick( button );
}
}
};
$( '<a />', props ).appendTo( $target ).after( ' ' );
};
}
if ( !$target.jquery ) {
// if $target is not an instance of jQuery, use it as 'buttons'
return true;
buttons = $target;
$target = fb.$menu;
}
if ( !$.isArray( buttons ) ){
buttons = [ buttons ];
}
for(i=0; i<buttons.length; i++ ){
button = buttons[i];
props = {
title: button.title,
text: button.text
};
if( button.disable ){
props['class'] = 'fb-button fb-disabled-button';
props.click = doNothing;
} else {
props['class'] = $.isFunction( button.action )
? 'fb-button fb-menu-button'
: 'fb-button fb-action-button';
props.click = buttonClick( button );
}
$( '<a></a>', props ).appendTo( $target ).after(' ');
}
return true;
};
};


fb.catScanOptions = function(){
fb.catScanOptions = function(){
var i, catScanUrl, list;
var i, catScanUrl, list;
list = [
list = [ {
{
text: 'sem fontes',
text: 'sem fontes',
desc: 'Procurar páginas desta categoria que precisam de fontes',
desc: 'Procurar páginas desta categoria que precisam de fontes',
url: 'ts&templates=Sem-fontes'
url: 'ts&templates=Sem-fontes'
}, {
},
text: 'revisão',
{
desc: 'Procurar páginas desta categoria que precisam de revisão',
text: 'revisão',
url: 'ts&templates=Revis%C3%A3o'
desc: 'Procurar páginas desta categoria que precisam de revisão',
}, {
url: 'ts&templates=Revis%C3%A3o'
text: 'wikificação',
},
desc: 'Procurar páginas desta categoria que precisam de wikificação',
{
url: 'ts&templates=Wikifica%C3%A7%C3%A3o'
text: 'wikificação',
}, {
desc: 'Procurar páginas desta categoria que precisam de wikificação',
text: 'menos de 1 000 bytes ou 4 links',
url: 'ts&templates=Wikifica%C3%A7%C3%A3o'
desc: 'Procurar páginas desta categoria que possuem menos de 1 000 bytes ou 4 links',
},
url: 'ss&size=1000&stubop=or&links=4'
{
}, {
text: 'menos de 1 000 bytes ou 4 links',
desc: 'Procurar páginas desta categoria que possuem menos de 1 000 bytes ou 4 links',
text: 'menos de 500 bytes ou 2 links',
desc: 'Procurar páginas desta categoria que possuem menos de 500 bytes ou 2 links',
url: 'ss&size=1000&stubop=or&links=4'
url: 'ss&size=500&stubop=or&links=2'
},
} ];
{
text: 'menos de 500 bytes ou 2 links',
desc: 'Procurar páginas desta categoria que possuem menos de 500 bytes ou 2 links',
url: 'ss&size=500&stubop=or&links=2'
}
];


catScanUrl = '//toolserver.org/~daniel/WikiSense/CategoryIntersect.php?' +
catScanUrl = '//toolserver.org/~daniel/WikiSense/CategoryIntersect.php?' +
$.param( {
$.param( {
wikilang: mw.config.get('wgContentLanguage'),
wikilang: mw.config.get( 'wgContentLanguage' ),
wikifam: '.wikipedia.org',
wikifam: '.wikipedia.org',
userlang: mw.config.get('wgUserLanguage'),
userlang: mw.config.get( 'wgUserLanguage' ),
basecat: mw.config.get('wgTitle'),
basecat: mw.config.get( 'wgTitle' ),
basedeep: '1',
basedeep: '1',
go: 'Examinar',
go: 'Examinar',
format: 'html',
format: 'html',
mode: ''
mode: ''
} );
} );
fb.$submenu.append( 'Procurar nesta categoria:' );
fb.$submenu.append( 'Procurar nesta categoria:' );
for(i=0; i<list.length; i++){
fb.$submenu.append( ' ', $('<a></a>', {
for( i = 0; i < list.length; i++ ){
'class': 'fb-button',
fb.$submenu.append( ' ', $('<a></a>', {
'href': catScanUrl + list[i].url,
'class': 'fb-button',
'text': list[i].text,
'href': catScanUrl + list[ i ].url,
'title': list[i].desc
'text': list[ i ].text,
}) );
'title': list[ i ].desc
}
}) );
}
};
};


fb.addSearchOptions = function(){
fb.addSearchOptions = function(){
var i,
var i,
$searchOptions = $('<span class="plainlinks"></span>'),
$searchOptions = $('<span class="plainlinks"></span>'),
search = encodeURIComponent(
search = encodeURIComponent(
fb.title.indexOf( ' ' ) > -1
fb.title.indexOf( ' ' ) > -1
? '"' + fb.title + '"'
? '"' + fb.title + '"'
: fb.title
: fb.title
),
),
list = [ {
list = [ {
text: 'Google',
text: 'Google',
desc: 'Pesquisar o título desta página no Google',
desc: 'Pesquisar o título desta página no Google',
url: '//www.google.com/search?&as_eq=wikipedia&as_epq=',
url: '//www.google.com/search?&as_eq=wikipedia&as_epq=',
after: ' — '
after: ' — '
},
}, {
{
text: 'notícias',
text: 'notícias',
desc: 'Pesquisar o título desta página no Google Notícias',
desc: 'Pesquisar o título desta página no Google Notícias',
url: '//news.google.com/archivesearch?&as_src=-newswire+-wire+-presswire+-PR+-press+-release&as_epq=',
url: '//news.google.com/archivesearch?&as_src=-newswire+-wire+-presswire+-PR+-press+-release&as_epq=',
after: ', '
after: ', '
}, {
}, {
text: 'livros',
text: 'livros',
desc: 'Pesquisar o título desta página no Google Livros',
desc: 'Pesquisar o título desta página no Google Livros',
url: '//books.google.com/books?&as_brr=0&as_epq=',
url: '//books.google.com/books?&as_brr=0&as_epq=',
after: ', '
after: ', '
}, {
}, {
text: 'acadêmico',
text: 'acadêmico',
desc: 'Pesquisar o título desta página no Google Acadêmico',
desc: 'Pesquisar o título desta página no Google Acadêmico',
url: '//scholar.google.com/scholar?as_epq=',
url: '//scholar.google.com/scholar?as_epq=',
after: ' — '
after: ' — '
}, {
}, {
text: 'Scirus',
text: 'Scirus',
desc: 'Pesquisar o título desta página no Scirus',
desc: 'Pesquisar o título desta página no Scirus',
url: '//www.scirus.com/srsapp/search?t=all&sort=0&g=s&q='
url: '//www.scirus.com/srsapp/search?t=all&sort=0&g=s&q='
} ];
} ];
for(i=0; i<list.length; i++){
for ( i = 0; i < list.length; i++ ) {
$searchOptions.append( $('<a></a>', {
$searchOptions.append( $( '<a></a>', {
'class': 'external text',
'class': 'external text',
'href': list[i].url + search,
'text': list[i].text,
'href': list[ i ].url + search,
'title': list[i].desc
'text': list[ i ].text,
'title': list[ i ].desc
}) );
}) );
if( list[i].after ){
$searchOptions.append( list[i].after );
if ( list[ i ].after ) {
}
$searchOptions.append( list[ i ].after );
}
}
fb.$submenu.append( $searchOptions );
}
fb.$submenu.append( $searchOptions );
};
};


fb.addFieldForOtherESROptions = function(){
fb.addFieldForOtherESROptions = function(){
var $otherInput, $okButton;
var $otherInput, $okButton;


$otherInput = $('<input type="text" id="fb-esr-input" size=55/>')
$otherInput = $( '<input type="text" id="fb-esr-input" size=55/>')
.keypress( function(evt){
.keypress( function( event ) {
fb.ok(evt, 'ESR');
fb.ok( event, 'ESR' );
} );
} );
$okButton = $('<input type="button" value="OK"/>')
$okButton = $( '<input type="button" value="OK"/>' )
.mousedown( function (){
.mousedown( function(){
fb.ok('ok', 'ESR');
fb.ok( 'ok', 'ESR' );
} );
} );


fb.$submenu.append( 'outra: ', $otherInput, $okButton );
fb.$submenu.append( 'outra: ', $otherInput, $okButton );
};
};


fb.addFieldForStubs = function(){
fb.addFieldForStubs = function(){
var $stubInput, $okButton;
var $stubInput, $okButton;


$stubInput = $('<input id="fb-esb-input" size=14/>')
$stubInput = $( '<input id="fb-esb-input" size=14/>' )
.keyup( function(){
.keyup( function(){
fb.callAPI('esb');
fb.callAPI( 'esb' );
} )
} )
.keypress( function(evt){
.keypress( function( event ){
fb.ok(evt, 'esb');
fb.ok( event, 'esb' );
} );
} );
$okButton = $('<input type="button" value="OK"/>')
$okButton = $('<input type="button" value="OK"/>')
.mousedown( function (){
.mousedown( function () {
fb.ok('ok', 'esb');
fb.ok( 'ok', 'esb' );
} );
} );


fb.$submenu.append( ' esboço-', $stubInput, $okButton );
fb.$submenu.append( ' esboço-', $stubInput, $okButton );
};
};


/*** Submenu [ER] ***/
/*** Submenu [ER] ***/
fb.submenu.ER = [
fb.submenu.ER = [ {
action: 'ER|1',
{
action: 'ER|1',
text: '1',
title: '???',
text: '1',
disable: true
title: '???',
}, {
disable: true
action: 'ER|5',
},
text: '5',
{
title: 'Aparecimento recorrente (se o conteúdo for igual ao eliminado por votação)'
action: 'ER|5',
}, {
text: '5',
action: 'ER|6',
title: 'Aparecimento recorrente (se o conteúdo for igual ao eliminado por votação)'
text: '6',
},
title: 'Título é SPAM',
{
disable: $.inArray( fb.ns, [ 0, 102 ] ) === -1
action: 'ER|6',
}, {
text: '6',
action: 'ER|7',
title: 'Título é SPAM',
text: '7',
disable: $.inArray(fb.ns, [0, 102]) === -1
title: 'Próprio criador reconhece que se enganou'
},
}, {
{
action: 'ER|7',
action: 'ER|8',
text: '7',
text: '8',
title: 'Eliminações temporárias sem perda de histórico para resolver problemas técnicos',
title: 'Próprio criador reconhece que se enganou'
disable: $.inArray('sysop', mw.config.get('wgUserGroups')) === -1
},
}, {
{
action: 'ER|8',
action: 'ER|9',
text: '8',
text: '9',
title: 'Eliminar redirect, página sem histórico relevante' +
title: 'Eliminações temporárias sem perda de histórico para resolver problemas técnicos',
' (mover página redirecionada para cá)'
disable: $.inArray('sysop', mw.config.get('wgUserGroups')) === -1
}, {
},
action: 'ER|10',
{
text: '10',
action: 'ER|9',
title: 'Namespaces que não existem (WikipÉdia, AjUda)',
text: '9',
disable: fb.ns !== 0
title: 'Eliminar redirect, página sem histórico relevante' +
}, {
' (mover página redirecionada para cá)'
action: 'ER|11',
},
text: '11',
{
title: 'Má configuração do teclado (Página, Usuário:Sicrano)'
action: 'ER|10',
}, {
text: '10',
action: 'ER|12',
title: 'Namespaces que não existem (WikipÉdia, AjUda)',
text: '12',
disable: fb.ns !== 0
title: 'Imagens, somente por quem a carregou',
},
disable: fb.ns !== 6
{
}, {
action: 'ER|11',
action: 'ER|13',
text: '11',
text: '13',
title: 'Má configuração do teclado (Página, Usuário:Sicrano)'
title: 'Páginas sem histórico relevante que são violações flagrantes de' +
},
' direitos autorais de outras páginas na internet.',
{
disable: $.inArray( fb.ns, [ 0, 102 ] ) === -1
action: 'ER|12',
}, {
text: '12',
action: 'ER|14',
title: 'Imagens, somente por quem a carregou',
text: '14',
disable: fb.ns !== 6
title: 'Ficheiros (arquivos) duplicados',
},
disable: fb.ns !== 6
{
}, {
action: 'ER|13',
action: 'ER|17',
text: '13',
text: '17',
title: 'Páginas sem histórico relevante que são violações flagrantes de' +
title: 'Salto de domínio'
' direitos autorais de outras páginas na internet.',
}, {
disable: $.inArray(fb.ns, [0, 102]) === -1
action: 'ER|18',
},
text: '18',
{
title: 'Discussão cujos artigos não existem',
action: 'ER|14',
disable: fb.ns !== 1
text: '14',
}, {
title: 'Ficheiros (arquivos) duplicados',
action: 'ER|19',
disable: fb.ns !== 6
text: '19',
},
title: 'Ficheiros (domínio Ficheiro:) que não são som, imagem ou vídeo',
{
disable: fb.ns !== 6
action: 'ER|17',
}, {
text: '17',
action: 'ER|20',
title: 'Salto de domínio'
text: '20',
},
title: 'Impróprio'
{
}, {
action: 'ER|18',
action: 'ER|21',
text: '18',
text: '21',
title: 'Discussão cujos artigos não existem',
title: 'Página de eliminação de um artigo antes de passados 6 meses da última votação',
disable: fb.ns !== 1
disable: mw.config.get( 'wgPageName' ).indexOf( 'Wikipédia:Páginas_para_eliminar/' ) !== 0
},
}, {
{
action: 'ER|19',
action: 'ER|A1',
text: '19',
text: 'A1',
title: 'Páginas com o título malformatado, absurdo, com palavras que não' +
title: 'Ficheiros (domínio Ficheiro:) que não são som, imagem ou vídeo',
' o são, com erros devidos à má configuração do teclado, com codificação' +
disable: fb.ns !== 6
' incorreta do sistema ou que expressem domínios que não existem.',
},
disable: $.inArray( fb.ns, [ 0, 102 ] ) === -1
{
}, {
action: 'ER|20',
action: 'ER|C1',
text: '20',
text: 'C1',
title: 'Impróprio'
title: 'Categorias vazias, desnecessárias ou substituídas',
},
disable: fb.ns !== 14
{
}, {
action: 'ER|21',
action: 'ER|D1',
text: '21',
text: 'D1',
title: 'Página de eliminação de um artigo antes de passados 6 meses da última votação',
title: 'Discussões de páginas inexistentes',
disable: mw.config.get('wgPageName').indexOf('Wikipédia:Páginas_para_eliminar/') !== 0
disable: fb.ns % 2 === 0
},
}, {
{
action: 'ER|A1',
action: 'ER|D2',
text: 'A1',
text: 'D2',
title: 'Discussões de páginas para eliminação ou com histórico irrelevante',
title: 'Páginas com o título malformatado, absurdo, com palavras que não' +
disable: fb.ns % 2 === 0
' o são, com erros devidos à má configuração do teclado, com codificação' +
}, {
' incorreta do sistema ou que expressem domínios que não existem.',
action: 'ER|U1',
disable: $.inArray(fb.ns, [0, 102]) === -1
text: 'U1',
},
title: 'Uso impróprio da página de usuário',
{
disable: $.inArray( fb.ns, [ 2, 3 ] ) === -1
action: 'ER|C1',
}, {
text: 'C1',
action: 'ER|U2',
title: 'Categorias vazias, desnecessárias ou substituídas',
text: 'U2',
disable: fb.ns !== 14
title: 'Página de usuário criada por outro usuário',
},
disable: fb.ns !== 2
{
}, {
action: 'ER|D1',
action: 'ER|P1',
text: 'D1',
text: 'P1',
title: 'Discussões de páginas inexistentes',
title: 'Predefinições vazias, desnecessárias ou substituídas',
disable: fb.ns % 2 === 0
disable: fb.ns !== 10
},
}, {
{
action: 'ER|D2',
action: 'ER|R1',
text: 'D2',
text: 'R1',
title: 'Redirecionamento indevido, desnecessário, sem afluentes,' +
title: 'Discussões de páginas para eliminação ou com histórico irrelevante',
' para páginas inexistente ou eliminadas'
disable: fb.ns % 2 === 0
}, {
},
action: 'ER|R2',
{
text: 'R2',
action: 'ER|U1',
title: 'Redirecionamento de página de discussão sem afluentes',
text: 'U1',
disable: fb.ns % 2 === 0
title: 'Uso impróprio da página de usuário',
}
disable: $.inArray(fb.ns, [2, 3]) === -1
},
{
action: 'ER|U2',
text: 'U2',
title: 'Página de usuário criada por outro usuário',
disable: fb.ns !== 2
},
{
action: 'ER|P1',
text: 'P1',
title: 'Predefinições vazias, desnecessárias ou substituídas',
disable: fb.ns !== 10
},
{
action: 'ER|R1',
text: 'R1',
title: 'Redirecionamento indevido, desnecessário, sem afluentes,' +
' para páginas inexistente ou eliminadas'
},
{
action: 'ER|R2',
text: 'R2',
title: 'Redirecionamento de página de discussão sem afluentes',
disable: fb.ns % 2 === 0
}
];
];


/*** Submenu [ESR] ***/
/*** Submenu [ESR] ***/
fb.submenu.ESR = [
fb.submenu.ESR = [ {
action: 'subst:ESR-banda|1=~~' + '~~',
{
text: 'banda',
action: 'subst:ESR-banda|1=~~' + '~~',
title: 'Artigo sobre banda sem fontes e sem notoriedade'
text: 'banda',
}, {
title: 'Artigo sobre banda sem fontes e sem notoriedade'
action: 'subst:ESR-bio|1=~~' + '~~',
},
text: 'biografia',
{
title: 'Biografia sem fontes e sem notoriedade'
action: 'subst:ESR-bio|1=~~' + '~~',
}, {
text: 'biografia',
action: 'subst:ESR-empresa|1=~~' + '~~',
title: 'Biografia sem fontes e sem notoriedade'
text: 'empresa',
},
title: 'Empresa sem fontes e sem notoriedade'
{
},
action: 'subst:ESR-empresa|1=~~' + '~~',
text: 'empresa',
fb.addFieldForOtherESROptions
title: 'Empresa sem fontes e sem notoriedade'
},
fb.addFieldForOtherESROptions
];
];


/*** Submenu [esboço] ***/
/*** Submenu [esboço] ***/
fb.submenu.esb = [
fb.submenu.esb = [ {
action: 'mínimo',
{
action: 'mínimo',
text: 'mínimo',
title: 'Artigo com apenas uma frase'
text: 'mínimo',
}, {
title: 'Artigo com apenas uma frase'
action: 'esboço',
},
text: 'esboço',
{
title: 'Artigo ainda pouco desenvolvido'
action: 'esboço',
},
text: 'esboço',
title: 'Artigo ainda pouco desenvolvido'
fb.addFieldForStubs
},
fb.addFieldForStubs
];
];


/*** Submenu [manuteção] ***/
/*** Submenu [manuteção] ***/
fb.submenu.man = [
fb.submenu.man = [ {
action: 'subst:wkf',
{
text: 'wikificar',
action: 'subst:wkf',
title: 'Não está formatado de acordo com o livro de estilo'
text: 'wikificar',
}, {
title: 'Não está formatado de acordo com o livro de estilo'
action: 'subst:s-fontes',
},
text: 'sem fontes',
{
title: 'Página não cita nenhuma fonte ou referência'
action: 'subst:s-fontes',
}, {
text: 'sem fontes',
action: 'subst:s-cat',
title: 'Página não cita nenhuma fonte ou referência'
text: 'sem cat',
},
title: 'Página não está em nenhuma categoria'
{
}, {
action: 'subst:s-cat',
action: 'subst:rec',
text: 'sem cat',
text: 'reciclagem',
title: 'Página não está em nenhuma categoria'
title: 'Página precisa ser reciclada de acordo com o livro de estilo'
},
}, {
{
action: 'subst:rec',
action: 'parcial',
text: 'reciclagem',
text: 'parcial',
title: 'Artigo possui passagens que não respeitam o princípio da imparcialidade'
title: 'Página precisa ser reciclada de acordo com o livro de estilo'
}, {
},
action: 'subst:ctx',
{
text: 'contexto',
action: 'parcial',
title: 'Página carece de contexto'
text: 'parcial',
}, {
title: 'Artigo possui passagens que não respeitam o princípio da imparcialidade'
action: 'controverso|artigo',
},
text: 'controverso',
{
title: 'controverso devido às disputas sobre o seu conteúdo'
action: 'subst:ctx',
}, {
text: 'contexto',
action: 'subst:f-referências',
title: 'Página carece de contexto'
text: 'formatar referências',
},
title: 'Artigo contém referências que necessitam de formatação'
{
}, {
action: 'controverso|artigo',
action: 'subst:m-notas',
text: 'controverso',
text: 'mais notas',
title: 'controverso devido às disputas sobre o seu conteúdo'
title: 'Página cita fontes fiáveis, mas não cobre todo o texto'
},
}, {
{
action: 'subst:f-referências',
action: 'subst:s-notas',
text: 'formatar referências',
text: 'sem notas',
title: 'Existem fontes no final da página, mas não são citadas no corpo do artigo'
title: 'Artigo contém referências que necessitam de formatação'
}, {
},
action: 'subst:s-fontes-bpv',
{
text: 'bpv sem fontes',
action: 'subst:m-notas',
title: 'Biografia de pessoa viva que não cita nenhuma fonte'
text: 'mais notas',
}, {
title: 'Página cita fontes fiáveis, mas não cobre todo o texto'
action: 'subst:fpr',
},
text: 'fonte primária',
{
title: 'Artigo necessita de fontes secundárias fiáveis publicadas por terceiros'
action: 'subst:s-notas',
}, {
text: 'sem notas',
action: 'subst:fu',
title: 'Existem fontes no final da página, mas não são citadas no corpo do artigo'
text: 'fusão',
},
title: 'Artigo necessita de fusão',
{
prompt: 'Com qual página esta deve ser feita fusão?',
action: 'subst:s-fontes-bpv',
label: 'Página:'
text: 'bpv sem fontes',
}, {
title: 'Biografia de pessoa viva que não cita nenhuma fonte'
action: 'subst:f-de',
},
text: 'fusão de',
{
title: 'Artigo necessita de fusão',
action: 'subst:fpr',
prompt: 'De qual página esta deve ser feita fusão?',
text: 'fonte primária',
label: 'Página:'
title: 'Artigo necessita de fontes secundárias fiáveis publicadas por terceiros'
}, {
},
action: 'subst:f-com',
{
text: 'fusão com',
action: 'subst:fu',
text: 'fusão',
title: 'Artigo necessita de fusão',
prompt: 'Com qual página esta deve ser feita fusão?',
title: 'Artigo necessita de fusão',
label: 'Página:'
prompt: 'Com qual página esta deve ser feita fusão?',
label: 'Página:'
}
},
{
action: 'subst:f-de',
text: 'fusão de',
title: 'Artigo necessita de fusão',
prompt: 'De qual página esta deve ser feita fusão?',
label: 'Página:'
},
{
action: 'subst:f-com',
text: 'fusão com',
title: 'Artigo necessita de fusão',
prompt: 'Com qual página esta deve ser feita fusão?',
label: 'Página:'
}
];
];


/*** Submenu [aviso] ***/
/*** Submenu [aviso] ***/
fb.submenu.warn = [
fb.submenu.warn = [ {
action: 'subst:bem-vindo IP',
{
text: 'BV-IP',
action: 'subst:bem-vindo IP',
title: 'Boas-vindas para usuário(a) não registrado(a)'
text: 'BV-IP',
}, {
title: 'Boas-vindas para usuário(a) não registrado(a)'
action: 'subst:bem-vindo',
},
text: 'BV',
{
title: 'Bem-vindo(a) à Wikipédia'
action: 'subst:bem-vindo',
}, {
text: 'BV',
action: 'subst:bem-vinda',
title: 'Bem-vindo(a) à Wikipédia'
text: 'BVª',
},
title: 'Bem-vinda à Wikipédia'
{
}, {
action: 'subst:bem-vinda',
action: 'subst:bv-av',
text: 'BVª',
text: 'av-BV-IP',
title: 'Bem-vinda à Wikipédia'
title: 'Aviso sobre erro em artigo e boas-vindas para usuário(a) não registrado(a)',
},
prompt: 'Aviso sobre qual artigo?',
{
label: 'Artigo:'
action: 'subst:bv-av',
}, {
text: 'av-BV-IP',
title: 'Aviso sobre erro em artigo e boas-vindas para usuário(a) não registrado(a)',
action: 'subst:bv-av-registrado',
text: 'av-BV',
prompt: 'Aviso sobre qual artigo?',
title: 'Aviso sobre erro em artigo e boas-vindas para usuário(a) registrado',
label: 'Artigo:'
prompt: 'Aviso sobre qual artigo?',
},
label: 'Artigo:'
{
}, {
action: 'subst:bv-av-registrado',
action: 'subst:aviso-ER',
text: 'av-BV',
text: 'av-ER',
title: 'Aviso sobre erro em artigo e boas-vindas para usuário(a) registrado',
prompt: 'Aviso sobre qual artigo?',
title: 'Aviso sobre eliminação rápida',
prompt: 'Qual página foi proposta para eliminação?',
label: 'Artigo:'
label: 'Página:'
},
}, {
{
action: 'subst:aviso-ER',
action: 'subst:av-bv-ER',
text: 'av-ER',
text: 'av-BV-ER',
title: 'Aviso sobre eliminação rápida',
title: 'Aviso sobre eliminação rápida + boas-vindas',
prompt: 'Qual página foi proposta para eliminação?',
prompt: 'Qual página foi proposta para eliminação?',
label: 'Página:'
label: 'Página:'
}, {
},
action: 'subst:aviso-ESR',
{
action: 'subst:av-bv-ER',
text: 'av-ESR',
title: 'Aviso sobre eliminação semirrápida',
text: 'av-BV-ER',
prompt: 'Qual página foi proposta para eliminação?',
title: 'Aviso sobre eliminação rápida + boas-vindas',
label: 'Página:'
prompt: 'Qual página foi proposta para eliminação?',
label: 'Página:'
}, {
action: 'subst:aviso-PE',
},
text: 'av-PE',
{
title: 'Aviso sobre eliminação por votação',
action: 'subst:aviso-ESR',
prompt: 'Qual página foi proposta para eliminação?',
text: 'av-ESR',
label: 'Página:'
title: 'Aviso sobre eliminação semirrápida',
}, {
prompt: 'Qual página foi proposta para eliminação?',
label: 'Página:'
action: 'subst:bv-propaganda',
text: 'prop-BV',
},
title: 'Caro editor,por favor não faça propaganda, [...] Apesar disso, bem-vindo à Wikipédia'
{
}, {
action: 'subst:aviso-PE',
action: 'subst:propaganda',
text: 'av-PE',
text: 'prop',
title: 'Aviso sobre eliminação por votação',
title: 'Caro editor, por favor não faça propaganda...',
prompt: 'Qual página foi proposta para eliminação?',
prompt: 'Em que página foi feita propaganda?',
label: 'Página:'
label: 'Página:'
},
}, {
{
action: 'subst:bv-propaganda',
action: 'subst:aviso',
text: 'prop-BV',
text: 'av',
title: 'Aviso sobre erro em artigo',
title: 'Caro editor,por favor não faça propaganda, [...] Apesar disso, bem-vindo à Wikipédia'
prompt: 'Aviso sobre qual artigo?',
},
label: 'Artigo:'
{
}, {
action: 'subst:propaganda',
action: 'subst:aviso2',
text: 'prop',
text: 'av2',
title: 'Caro editor, por favor não faça propaganda...',
title: 'Aviso sobre vandalismo',
prompt: 'Em que página foi feita propaganda?',
label: 'Página:'
prompt: 'Qual página foi vandalizada?',
label: 'Página:'
},
}, {
{
action: 'subst:aviso',
action: 'subst:BSRE',
text: 'av',
text: 'BSRE',
title: 'Aviso sobre erro em artigo',
title: 'Aviso de biografia sem relevo enciclopédico',
prompt: 'Aviso sobre qual artigo?',
prompt: 'Qual artigo?',
label: 'Artigo:'
label: 'Artigo:'
}, {
},
action: 'subst:cópia',
{
text: 'cópia',
action: 'subst:aviso2',
title: 'Aviso sobre artigo copiado de fonte externa/VDA',
text: 'av2',
prompt: 'Qual a página da Wikipédia? E qual a URL da página copiada?',
title: 'Aviso sobre vandalismo',
label: 'Página:|2=URL:'
prompt: 'Qual página foi vandalizada?',
label: 'Página:'
}, {
action: 'subst:linguagem incorreta',
},
text: 'linguagem',
{
title: 'Não insulte nem use linguagem inadequada em artigos ou discussões'
action: 'subst:BSRE',
}, {
text: 'BSRE',
action: 'subst:ortografia',
title: 'Aviso de biografia sem relevo enciclopédico',
text: 'ortografia',
prompt: 'Qual artigo?',
label: 'Artigo:'
title: 'Não mude a versão da língua',
prompt: 'Em qual artigo a versão da língua foi alterada?',
},
label: 'Artigo:'
{
}, {
action: 'subst:cópia',
action: 'subst:mostrar previsão',
text: 'cópia',
text: 'salvamento sucessivo',
title: 'Aviso sobre artigo copiado de fonte externa/VDA',
title: 'Não faça salvamentos sucessivos, utilize o botão \'Mostrar previsão\'',
prompt: 'Qual a página da Wikipédia? E qual a URL da página copiada?',
prompt: 'Em que artigo foram feitos salvamentos sucessivos?',
label: 'Página:|2=URL:'
label: 'Página:'
},
}, {
{
action: 'subst:linguagem incorreta',
action: 'subst:av-boas vindas',
text: 'linguagem',
text: 'aviso-BV',
title: 'Não dê boas-vindas a usuários que não contribuíram com pelo menos uma edição válida'
title: 'Não insulte nem use linguagem inadequada em artigos ou discussões'
}, {
},
action: 'subst:av-página de usuário',
{
text: 'av-PU',
action: 'subst:ortografia',
title: 'Considere refazer a página de usuário(a)'
text: 'ortografia',
}, {
title: 'Não mude a versão da língua',
action: 'subst:não remova',
prompt: 'Em qual artigo a versão da língua foi alterada?',
label: 'Artigo:'
text: 'não remova',
title: 'Não remova marcações de eliminação das páginas',
},
prompt: 'Qual página em que a marcação de eliminação foi removida?' +
{
'Se desejar, pode especificar o tipo de marcação.',
action: 'subst:mostrar previsão',
label: 'Página:|2=Tipo de marcação:'
text: 'salvamento sucessivo',
}, {
title: 'Não faça salvamentos sucessivos, utilize o botão \'Mostrar previsão\'',
action: 'subst:autobiografia',
prompt: 'Em que artigo foram feitos salvamentos sucessivos?',
label: 'Página:'
text: 'autobiografia',
title: 'Não crie autobiografias',
},
prompt: 'Qual autobiografia foi criada?',
{
label: 'Página:'
action: 'subst:av-boas vindas',
}, {
text: 'aviso-BV',
action: 'subst:av-teste',
title: 'Não dê boas-vindas a usuários que não contribuíram com pelo menos uma edição válida'
text: 'av-teste',
},
title: 'Não faça testes nos artigos',
{
prompt: 'Qual o nível do aviso? E em que página foram feitos testes?',
action: 'subst:av-página de usuário',
label: 'Nível:|2=Página:'
text: 'av-PU',
}, {
title: 'Considere refazer a página de usuário(a)'
action: 'subst:av-data',
},
text: 'av-data',
{
title: 'Não insira seu nome e data de nascimento em páginas de datas',
action: 'subst:não remova',
prompt: 'Em que página de data foram inseridos o nome e a data de nascimento?',
text: 'não remova',
label: 'Página:'
title: 'Não remova marcações de eliminação das páginas',
}, {
prompt: 'Qual página em que a marcação de eliminação foi removida?' +
action: 'subst:aviso-matrad',
'Se desejar, pode especificar o tipo de marcação.',
label: 'Página:|2=Tipo de marcação:'
text: 'aviso-matrad',
title: 'Aviso sobre má tradução',
},
prompt: 'Qual página foi marcada como má tradução?',
{
label: 'Página:'
action: 'subst:autobiografia',
}, {
text: 'autobiografia',
action: 'subst:bloqueado',
title: 'Não crie autobiografias',
text: 'bloqueado',
prompt: 'Qual autobiografia foi criada?',
label: 'Página:'
title: 'Notificação de bloqueio',
prompt: 'Especifique o tempo e o motivo do bloqueio.',
},
label: 'Tempo:|2=Motivo'
{
}, {
action: 'subst:av-teste',
action: 'subst:bloqueado-disc',
text: 'av-teste',
text: 'bloqueado-disc',
title: 'Não faça testes nos artigos',
title: 'Notificação de bloqueio com discussão',
prompt: 'Qual o nível do aviso? E em que página foram feitos testes?',
prompt: 'Especifique o tempo e o motivo do bloqueio.',
label: 'Nível:|2=Página:'
label: 'Tempo:|2=Motivo'
},
}, {
{
action: 'subst:av-data',
action: 'subst:bloqueado-CPV',
text: 'av-data',
text: 'bloqueado-CPV',
title: 'Notificação de bloqueio para contas para vandalismo'
title: 'Não insira seu nome e data de nascimento em páginas de datas',
}, {
prompt: 'Em que página de data foram inseridos o nome e a data de nascimento?',
label: 'Página:'
action: 'proxy',
text: 'proxy',
},
title: 'Notificação de proxy bloqueado'
{
}, {
action: 'subst:aviso-matrad',
action: 'subst:cite fonte',
text: 'aviso-matrad',
text: 'citar fontes',
title: 'Aviso sobre má tradução',
title: 'Faltou citar fontes à página',
prompt: 'Qual página foi marcada como má tradução?',
label: 'Página:'
prompt: 'Qual foi a página?',
label: 'Página:'
},
}
{
action: 'subst:bloqueado',
text: 'bloqueado',
title: 'Notificação de bloqueio',
prompt: 'Especifique o tempo e o motivo do bloqueio.',
label: 'Tempo:|2=Motivo'
},
{
action: 'subst:bloqueado-disc',
text: 'bloqueado-disc',
title: 'Notificação de bloqueio com discussão',
prompt: 'Especifique o tempo e o motivo do bloqueio.',
label: 'Tempo:|2=Motivo'
},
{
action: 'subst:bloqueado-CPV',
text: 'bloqueado-CPV',
title: 'Notificação de bloqueio para contas para vandalismo'
},
{
action: 'proxy',
text: 'proxy',
title: 'Notificação de proxy bloqueado'
},
{
action: 'subst:cite fonte',
text: 'citar fontes',
title: 'Faltou citar fontes à página',
prompt: 'Qual foi a página?',
label: 'Página:'
}
];
];


Linha 696: Linha 632:


// FIXME: Consider using jQuery: $('#target').keypress()
// FIXME: Consider using jQuery: $('#target').keypress()
fb.ok = function( evt, option ) {
fb.ok = function( event, option ) {
if (window.event && window.event.keyCode === 13) {
if ( window.event && window.event.keyCode === 13 ) {
evt = 'ok';
event = 'ok';
} else if (evt && evt.which === 13) {
} else if ( event && event.which === 13 ) {
evt = 'ok';
event = 'ok';
}
}
if (evt === 'ok') {
if ( option === 'esb' ) {
if ( event === 'ok' ) {
if ( option === 'esb' ) {
fb.run('esboço-' + $( '#fb-esb-input').val());
fb.run( 'esboço-' + $( '#fb-esb-input' ).val() );
} else if ( option === 'ESR' ) {
} else if ( option === 'ESR' ) {
fb.run('subst:ESR', $( '#fb-esr-input').val() + ' ~~' + '~~');
fb.run( 'subst:ESR', $( '#fb-esr-input').val() + ' ~~' + '~~' );
}
}
}
}
};
};


Linha 715: Linha 652:
*/
*/
fb.patrolRevision = function ( rcid, success ) {
fb.patrolRevision = function ( rcid, success ) {
$.getJSON(
$.getJSON(
mw.util.wikiScript( 'api' ), {
mw.util.wikiScript( 'api' ), {
format: 'json',
format: 'json',
action: 'query',
action: 'query',
list: 'recentchanges',
list: 'recentchanges',
rctoken: 'patrol',
rctoken: 'patrol',
rcprop: '',
rcprop: '',
rclimit: '1'
rclimit: '1'
},
},
function( data ) {
function( data ) {
var query = data.query,
var query = data.query,
rc = query && query.recentchanges,
rc = query && query.recentchanges,
token = rc && rc[ 0 ] && rc[ 0 ].patroltoken;
token = rc && rc[ 0 ] && rc[ 0 ].patroltoken;
if ( !token ) {
mw.log( 'Não foi possível obter um token para patrulhar a edição.' );
if ( !token ) {
return false;
mw.log( 'Não foi possível obter um token para patrulhar a edição.' );
}
return false;
if ( !rcid ) {
}
mw.log( 'Não foi possível identificar a edição a ser patrulhada.' );
return false;
if ( !rcid ) {
}
mw.log( 'Não foi possível identificar a edição a ser patrulhada.' );
$.post(
return false;
mw.util.wikiScript( 'api' ), {
}
action: 'patrol',
format: 'json',
$.post(
token: token,
mw.util.wikiScript( 'api' ), {
rcid: rcid
action: 'patrol',
},
format: 'json',
function( data ) {
token: token,
if ( data.error ) {
rcid: rcid
mw.log( 'Não foi possível patrulhar a edição: ' + data.error.info );
},
return false;
}
function( data ) {
if ( $.isFunction( success ) ){
if ( data.error ) {
success();
mw.log( 'Não foi possível patrulhar a edição: ' + data.error.info );
}
return false;
mw.log( 'A edição foi marcada como patrulhada.' );
}
return true;
}
if ( $.isFunction( success ) ){
).error(function() {
success();
alert( 'Houve um erro inesperado ao usar a API do MediaWiki.' );
}
return false;
});
mw.log( 'A edição foi marcada como patrulhada.' );
}
).error(function() {
return true;
alert( 'A API retornou um erro ao tentar obter um token para patrulhar a edição.' );
}
return false;
).error( function() {
});
window.alert( 'Houve um erro inesperado ao usar a API do MediaWiki.' );
return false;
} );
}
).error( function() {
alert( 'A API retornou um erro ao tentar obter um token para patrulhar a edição.' );
return false;
});
};
};


Linha 771: Linha 718:
* @return: {boolean} Returns false if the user canceled or the page already has a template
* @return: {boolean} Returns false if the user canceled or the page already has a template
*/
*/
fb.run = function (code, extraText) {
fb.run = function ( code, extraText ) {
var $patrol, rcid,
var $patrol, rcid,
$textBox = $('#wpTextbox1'),
$textBox = $( '#wpTextbox1' ),
value = $textBox.val(),
value = $textBox.val(),
url = mw.util.wikiGetlink( mw.config.get('wgPageName') ) + '?',
url = mw.util.wikiGetlink( mw.config.get( 'wgPageName' ) ) + '?',
data = {
data = {
action: 'edit',
action: 'edit',
fastb: code
fastb: code
},
},
summary = ' (usando [[WP:FB|FastButtons]])',
summary = ' (usando [[WP:FB|FastButtons]])',
// FIXME: Move this to the definition of each button
// FIXME: Move this to the definition of each button
summaries = {
summaries = {
'subst:VDA': 'Página marcada como [[WP:VDA|VDA]]',
'subst:VDA': 'Página marcada como [[WP:VDA|VDA]]',
'subst:apagar': 'Página proposta para [[WP:Eliminação' +
'subst:apagar': 'Página proposta para [[WP:Eliminação' +
' por votação|eliminação por votação]]',
' por votação|eliminação por votação]]',
'subst:s-fontes': 'Página marcada como sem fontes',
'subst:s-fontes': 'Página marcada como sem fontes',
'subst:s-cat': 'Página marcada como sem categoria',
'subst:s-cat': 'Página marcada como sem categoria',
'subst:wkf': 'Página marcada para [[WP:WKF|wikificação]]',
'subst:wkf': 'Página marcada para [[WP:WKF|wikificação]]',
'subst:rec': 'Página marcada para [[WP:RECI|reciclagem]]',
'subst:rec': 'Página marcada para [[WP:RECI|reciclagem]]',
'parcial': 'Página marcada como parcial',
'parcial': 'Página marcada como parcial',
'subst:ctx': 'Página marcada como sem contexto',
'subst:ctx': 'Página marcada como sem contexto',
'controverso|artigo': 'Marcado como controverso',
'controverso|artigo': 'Marcado como controverso',
'subst:f-referências': 'Marcado que existem referências sem formatação',
'subst:f-referências': 'Marcado que existem referências sem formatação',
'subst:m-notas': 'Marcado que carece de mais fontes',
'subst:m-notas': 'Marcado que carece de mais fontes',
'subst:s-notas': 'Página marcada como sem notas',
'subst:s-notas': 'Página marcada como sem notas',
'subst:s-fontes-bpv': 'Marcado como [[WP:BPV|biografia de pessoa' +
'subst:s-fontes-bpv': 'Marcado como [[WP:BPV|biografia de pessoa' +
' viva]] sem fontes',
' viva]] sem fontes',
'subst:fpr': 'Página marcada como sem fontes secundárias fiáveis',
'subst:fpr': 'Página marcada como sem fontes secundárias fiáveis',
'subst:ESR': 'Página proposta para [[WP:ESR|eliminação semirrápida]]',
'subst:ESR': 'Página proposta para [[WP:ESR|eliminação semirrápida]]',
'subst:matrad': 'Página marcada como [[WP:Tradução|má tradução]]',
'subst:matrad': 'Página marcada como [[WP:Tradução|má tradução]]',
'subst:suspeito': 'Página marcada como suspeita de [[WP:VDA|VDA]]',
'subst:suspeito': 'Página marcada como suspeita de [[WP:VDA|VDA]]',
'subst:fu': 'Página marcada para [[WP:Fusão|fusão]]',
'subst:fu': 'Página marcada para [[WP:Fusão|fusão]]',
'subst:f-de': 'Página marcada para [[WP:Fusão|fusão]]',
'subst:f-de': 'Página marcada para [[WP:Fusão|fusão]]',
'subst:f-com': 'Página marcada para [[WP:Fusão|fusão]]'
'subst:f-com': 'Página marcada para [[WP:Fusão|fusão]]'
};
};
if (extraText === null) {
if ( extraText === null ) {
// Do nothing if the user canceled the prompt box
// Do nothing if the user canceled the prompt box
return false;
return false;
}
}
switch (mw.config.get('wgAction')) {
case 'view':
switch ( mw.config.get( 'wgAction' ) ) {
if( extraText ){
case 'view':
data.fbtxt = extraText;
if ( extraText ) {
}
data.fbtxt = extraText;
$patrol = mw.util.$content.find('span.patrollink a').first();
}
rcid = mw.util.getParamValue( 'rcid', $patrol.attr('href') || '' );
if ( rcid ) {
$patrol = mw.util.$content.find( 'span.patrollink a' ).first(),
fb.patrolRevision( rcid, function(){
rcid = mw.util.getParamValue( 'rcid', $patrol.attr( 'href' ) || '' );
location.href = url + $.param( data );
} );
if ( rcid ) {
} else{
fb.patrolRevision( rcid, function(){
location.href = url + $.param( data );
location.href = url + $.param( data );
}
} );
break;
} else {
case 'edit':
location.href = url + $.param( data );
if ( value.match(/\{\{(?:subst:)?(?:ER|ESR(?:2?|-banda|-bio|-empresa|-bsre|-organização)|VDA|Usuário(?:\(a\))?\:Salebot\/Impróprio)[\|\}]/i) ) {
}
alert('Já existe uma predefinição de eliminação nesta página.');
break;
return false;
}
case 'edit':
if (code.indexOf('ER') === 0) {
if ( value.match( /\{\{(?:subst:)?(?:ER|ESR(?:2?|-banda|-bio|-empresa|-bsre|-organização)|VDA|Usuário(?:\(a\))?\:Salebot\/Impróprio)[\|\}]/i ) ) {
extraText = extraText? '|3=' + extraText: '';
alert( 'Já existe uma predefinição de eliminação nesta página.' );
extraText = '{' + '{' + code + '|2=~~' + '~~' + extraText + '}}\n';
$textBox.val( extraText + value );
return false;
if (fb.save) {
}
document.editform.wpSummary.value = 'Página proposta para' +
' [[WP:ER|eliminação rápida]] (regra ' +
if ( code.indexOf( 'ER' ) === 0 ) {
code.substring(3) + ')' + summary;
extraText = extraText ? '|3=' + extraText: '',
}
extraText = '{' + '{' + code + '|2=~~' + '~~' + extraText + '}}\n',
} else if (code === 'redirect') {
$textBox.val( extraText + value );
if (mw.config.get('wgNamespaceNumber') === 14) {
if (extraText) {
if ( fb.save ) {
$textBox.val( '{' + '{redirecionamento de categoria|' +
$( 'input[name="wpSummary"]' ).val(
extraText + '}}' );
'Página proposta para' +
}
' [[WP:ER|eliminação rápida]] (regra ' +
if (fb.save) {
code.substring( 3 ) + ')' + summary
document.editform.wpSummary.value = 'Redirecionando para' +
);
' a [[categoria:' + extraText + ']]' + summary;
}
}
} else {
} else if ( code === 'redirect' ) {
if (extraText) {
if ( mw.config.get( 'wgNamespaceNumber' ) === 14 ) {
$textBox.val( '#Redirecionamento [[' + extraText + ']]' );
if ( extraText ) {
}
$textBox.val( '{' + '{redirecionamento de categoria|' + extraText + '}}' );
}
}
} else {
extraText = extraText? '|1=' + extraText: '';
if ( fb.save ) {
extraText = '{' + '{' + code + extraText + '}}';
document.editform.wpSummary.value = 'Redirecionando para' +
if (mw.config.get('wgNamespaceNumber') === 3) {
value += '\n\n' + extraText + ' ~~' + '~~';
' a [[categoria:' + extraText + ']]' + summary;
}
} else if (code === 'mínimo' || code.indexOf('esboço') === 0) {
} else {
if (value.match(/\n\n\[\[/)) {
if ( extraText ) {
value = value.substring(0, value.search(/\n\n\[\[/)) + '\n\n' +
$textBox.val( '#Redirecionamento [[' + extraText + ']]' );
extraText + value.substring(value.search(/\n\n\[\[/));
}
} else {
}
value += '\n\n' + extraText;
} else {
}
extraText = extraText ? '|1=' + extraText: '',
fb.save = (code === 'mínimo') ?
extraText = '{' + '{' + code + extraText + '}}';
'Página marcada como [[WP:M|mínimo]]' :
'Página marcada como [[WP:EBC|esboço]]';
if ( mw.config.get( 'wgNamespaceNumber' ) === 3 ) {
} else if ($.inArray( code, [ 'subst:VDA' , 'subst:matrad' ]) > -1) {
value = extraText;
value += '\n\n' + extraText + ' ~~' + '~~';
} else if ( code === 'mínimo' || code.indexOf( 'esboço' ) === 0 ) {
} else {
if ( value.match( /\n\n\[\[/ ) ) {
value = extraText + '\n' + value;
value = value.substring( 0, value.search( /\n\n\[\[/ ) ) + '\n\n' +
}
extraText + value.substring( value.search( /\n\n\[\[/ ) );
$textBox.val(value );
} else {
if (fb.save) {
value += '\n\n' + extraText;
if (mw.config.get('wgNamespaceNumber') === 3) {
}
fb.save = 'Adicionando aviso';
} else {
fb.save = ( code === 'mínimo' ) ?
if ( code.indexOf( 'subst:ESR' ) === 0 ) {
'Página marcada como [[WP:M|mínimo]]' :
code = 'subst:ESR';
'Página marcada como [[WP:EBC|esboço]]';
}
} else if ( $.inArray( code, [ 'subst:VDA' , 'subst:matrad' ] ) > -1 ) {
fb.save = summaries[ code ] || 'Adicionando marcação';
value = extraText;
}
} else {
document.editform.wpSummary.value = fb.save + summary;
value = extraText + '\n' + value;
}
}
}
// FIXME: It should not submit if in edit mode and (code === 'mínimo' || code.indexOf('esboço') === 0)
$textBox.val( value );
if (fb.save) {
document.editform.submit();
if ( fb.save ) {
}
if ( mw.config.get( 'wgNamespaceNumber' ) === 3 ) {
break;
fb.save = 'Adicionando aviso';
}
} else {
if ( code.indexOf( 'subst:ESR' ) === 0 ) {
code = 'subst:ESR';
}
fb.save = summaries[ code ] || 'Adicionando marcação';
}
$( 'input[name="wpSummary"]' ).val( fb.save + summary );
}
}
// FIXME: It should not submit if in edit mode and (code === 'mínimo' || code.indexOf('esboço') === 0)
if ( fb.save ) {
$( 'form[name="editform"]' ).submit();
}
break;
}
};
};


Linha 899: Linha 864:
*/
*/
fb.changeSubmenu = function ( items ) {
fb.changeSubmenu = function ( items ) {
fb.$submenu.empty();
var i;
fb.$submenu.empty();
if( !$.isArray( items ) ){
if ( !$.isArray( items ) ) {
items = [ items ];
items = [ items ];
}
}
for(i=0;i<items.length; i++){
if( $.isFunction( items[i] ) ){
for ( var i = 0; i < items.length; i++ ) {
if ( $.isFunction( items[ i ] ) ) {
items[i]();
} else if ( typeof items[i] === 'string' ){
items[ i ]();
} else if ( typeof items[ i ] === 'string' ) {
fb.$submenu.append( items[i] );
fb.$submenu.append( items[ i ] );
} else {
} else {
fb.addButton( fb.$submenu, items[i] );
fb.addButton( fb.$submenu, items[ i ] );
}
}
}
}
fb.$submenu.find( 'a, span' ).tipsy();
fb.$submenu.find( 'a, span' ).tipsy();
};
};


Linha 920: Linha 887:
*/
*/
fb.callAPI = function ( code ) {
fb.callAPI = function ( code ) {
var esb, apiParams, callbacks;
var esb, esbText, esbText2, apiParams, callbacks;
apiParams = {
apiParams = {
esb: {
esb: {
list: 'allpages',
list: 'allpages',
aplimit: '1',
aplimit: '1',
apnamespace: '10'
apnamespace: '10'
},
},
PV: {
list: 'watchlist',
PV: {
wlprop: 'user|comment|title|sizes',
list: 'watchlist',
wlexcludeuser: mw.config.get('wgUserName')
wlprop: 'user|comment|title|sizes',
},
wlexcludeuser: mw.config.get( 'wgUserName' )
PN: {
},
list: 'recentchanges',
rctype: 'new',
PN: {
rcnamespace: '0',
list: 'recentchanges',
rcshow: '!patrolled',
rctype: 'new',
rcprop: 'user|comment|title|sizes|ids'
rcnamespace: '0',
},
rcshow: '!patrolled',
MR: {
rcprop: 'user|comment|title|sizes|ids'
list: 'recentchanges',
},
rctype: 'edit',
rcnamespace: '0',
MR: {
rcshow: 'anon',
list: 'recentchanges',
rcprop: 'user|comment|title|sizes'
rctype: 'edit',
},
rcnamespace: '0',
usu: {
rcshow: 'anon',
list: 'allusers',
rcprop: 'user|comment|title|sizes'
aulimit: '1',
},
auprop: 'editcount|registration',
aufrom: mw.config.get('wgTitle').split('/')[0]
usu: {
},
list: 'allusers',
anon: {
aulimit: '1',
list: 'usercontribs',
auprop: 'editcount|registration',
uclimit: '500',
aufrom: mw.config.get( 'wgTitle' ).split( '/' )[ 0 ]
ucprop: 'timestamp',
},
ucuser: mw.config.get('wgTitle').split('/')[0]
}
anon: {
};
list: 'usercontribs',
callbacks = {
uclimit: '500',
esb: fb.processStubs,
ucprop: 'timestamp',
PV: fb.processRecentEdits,
ucuser: mw.config.get( 'wgTitle' ).split( '/' )[ 0 ]
PN: fb.processRecentEdits,
}
MR: fb.processRecentEdits,
},
usu: fb.processUserInfo,
anon: fb.processUserInfo
callbacks = {
};
esb: fb.processStubs,
if ( 'esb' === code ) {
PV: fb.processRecentEdits,
esb = $( '#fb-esb-input' ).val();
PN: fb.processRecentEdits,
if ( $.inArray( esb, [ esbText, esbText2 ] ) !== -1 ) {
MR: fb.processRecentEdits,
return;
usu: fb.processUserInfo,
}
anon: fb.processUserInfo
esbText = esb;
};
if (esbText === esb.substr(0, (esb.length - 1))) {
return;
if ( 'esb' === code ) {
}
esb = $( '#fb-esb-input' ).val();
apiParams.esb.apprefix = 'Esboço-' + esb;
}
if ( $.inArray( esb, [ esbText, esbText2 ] ) !== -1 ) {
apiParams[ code ].format = 'json';
return;
apiParams[ code ].action = 'query';
}
$.getJSON(
mw.util.wikiScript( 'api' ),
esbText = esb;
apiParams[ code ], function( data ) {
if( !data ){
if ( esbText === esb.substr( 0, ( esb.length - 1 ) ) ) {
mw.log(
return;
'Não foi possível obter a lista "' +
}
apiParams[ code ].list + '" a partir da API.'
);
apiParams.esb.apprefix = 'Esboço-' + esb;
return;
}
}
callbacks[ code ]( data, code );
apiParams[ code ].format = 'json',
}
apiParams[ code ].action = 'query';
);
$.getJSON(
mw.util.wikiScript( 'api' ),
apiParams[ code ], function( data ) {
if ( !data ){
mw.log( 'Não foi possível obter a lista "' + apiParams[ code ].list + '" a partir da API.' );
return;
}
callbacks[ code ]( data, code );
}
);
};
};


Linha 998: Linha 978:
* @param {Object} data JSON content returned by API
* @param {Object} data JSON content returned by API
*/
*/
fb.processBackLinks = function(data) {
fb.processBackLinks = function( data ) {
var info, catLine, backlinks, $hiddenCats, quality,
var info, catLine, backlinks, $hiddenCats, quality,
query = data.query;
query = data.query;
info = '(';
info += (document.getElementById('Refer.C3.AAncias')
info = '(';
info += ( document.getElementById( 'Refer.C3.AAncias' )
|| document.getElementById('Notas_e_refer.C3.AAncias')) ?
|| document.getElementById( 'Notas_e_refer.C3.AAncias' ) ) ?
'ref' :
'ref' :
'<span class="fb-missing" title="Esta página ainda não possui referências">ref</span>';
'<span class="fb-missing" title="Esta página ainda não possui referências">ref</span>',
catLine = document.getElementById( 'mw-normal-catlinks' );
catLine = $( '#mw-normal-catlinks' );
// FIXME: Use the API (instead of 'screen scraping') to get this information!
// FIXME: Use the API (instead of 'screen scraping') to get this information!
if (catLine && catLine.innerHTML.indexOf( '><a href="' + mw.config.get('wgArticlePath').replace('$1', '')) > -1) {
if ( catLine.length && catLine.html().indexOf( '><a href="' + mw.config.get( 'wgArticlePath' ).replace( '$1', '' ) ) !== -1 ) {
info += ' · cat';
info += ' · cat';
} else {
} else {
info += ' · <span class="fb-missing" title="Esta página ainda não foi categorizada">cat</span>';
info += ' · <span class="fb-missing" title="Esta página ainda não foi categorizada">cat</span>';
}
}
info += ( $( '#p-lang' ).length ) ?
info += ( $( '#p-lang' ).length ) ?
' · iw' :
' · iw' :
' · <span class="fb-missing" title="Esta página ainda não' +
' · <span class="fb-missing" title="Esta página ainda não' +
' possui links para outros idiomas">iw</span>';
' possui links para outros idiomas">iw</span>';


// Afluentes
// Afluentes
backlinks = query && query.backlinks;
backlinks = query && query.backlinks;
if ( !backlinks ) {
if ( !backlinks ) {
mw.log( 'The backlinks query returned no data.' );
} else if ( backlinks.length ) {
mw.log( 'The backlinks query returned no data.' );
} else if ( backlinks.length ) {
info += ' · <a href="' +
info += ' · <a href="' +
mw.util.wikiGetlink( 'Especial:Páginas afluentes/' + mw.config.get('wgPageName') ) +
mw.util.wikiGetlink( 'Especial:Páginas afluentes/' + mw.config.get( 'wgPageName' ) ) +
'" title="afluentes">afl</a>)';
'" title="afluentes">afl</a>)';
} else {
} else {
info += ' · <span class="fb-missing" title="Esta página ainda não possui afluentes">afl</span>)';
info += ' · <span class="fb-missing" title="Esta página ainda não possui afluentes">afl</span>)';
}
}
fb.changeSubmenu( info );
if ( !$( '#ca-talk' ).hasClass('new') ) {
fb.changeSubmenu( info );
$.getJSON(
mw.util.wikiScript( 'api' ), {
if ( !$( '#ca-talk' ).hasClass( 'new' ) ) {
format: 'json',
$.getJSON(
action: 'query',
mw.util.wikiScript( 'api' ), {
prop: 'categories',
format: 'json',
indexpageids: '1',
action: 'query',
titles: mw.config.get('wgFormattedNamespaces')[ mw.config.get('wgNamespaceNumber') + 1 ] +
prop: 'categories',
':' + mw.config.get('wgTitle')
indexpageids: '1',
}, function( data ) {
titles: mw.config.get( 'wgFormattedNamespaces' )[ mw.config.get( 'wgNamespaceNumber' ) + 1 ] +
fb.processPageQuality( data );
':' + mw.config.get( 'wgTitle' )
}
}, function( data ) {
);
fb.processPageQuality( data );
} else {
}
$hiddenCats = $('#mw-hidden-catlinks');
);
if ( $hiddenCats.length ) {
} else {
quality = $hiddenCats.html();
$hiddenCats = $( '#mw-hidden-catlinks' );
if (quality.indexOf('!Artigos de qualidade') > -1) {
quality = quality.substr(quality.indexOf('!Artigos de qualidade') + 22, 1);
if ( $hiddenCats.length ) {
if (quality === 'd') {
quality = '?';
quality = $hiddenCats.html();
}
if ( quality.indexOf( '!Artigos de qualidade' ) !== -1 ) {
fb.$submenu.append(
quality = quality.substr( quality.indexOf( '!Artigos de qualidade' ) + 22, 1 );
'<span title="Qualidade do artigo"> Q-<b>' +
quality + '</b></span>'
if ( quality === 'd' ) {
).find( 'a, span' ).tipsy();
quality = '?';
}
}
}
}
fb.$submenu.append(
'<span title="Qualidade do artigo"> Q-<b>' +
quality + '</b></span>'
).find( 'a, span' ).tipsy();
}
}
}
};
};



/* Callback function for the request of talk page categories
/* Callback function for the request of talk page categories
* @param {Object} data JSON content returned by API
* @param {Object} data JSON content returned by API
*/
*/
fb.processPageQuality = function(data) {
fb.processPageQuality = function( data ) {
var cats, pageids, i, cat, quality,
var cats, pageids, i, cat, quality,
query = data.query;
query = data.query;
if ( query ) {
cats = query.pages;
if ( query ) {
pageids = query.pageids;
cats = query.pages,
if ( cats && pageids && pageids.length ) {
pageids = query.pageids;
cats = cats[ pageids[0] ].categories;
if ( !cats ){
if ( cats && pageids && pageids.length ) {
cats = cats[ pageids[0] ].categories;
mw.log( 'The categories query returned incomplete data.' );
return false;
if ( !cats ){
}
mw.log( 'The categories query returned incomplete data.' );
} else {
mw.log( 'The categories query returned incomplete data.' );
return false;
return false;
}
}
} else {
} else {
mw.log( 'The categories query returned no data.' );
mw.log( 'The categories query returned incomplete data.' );
return false;
return false;
}
}
// Qualidade do artigo
for (i = 0; i < cats.length; i++) {
} else {
mw.log( 'The categories query returned no data.' );
cat = cats[i].title;
if ( cat && cat.indexOf( '!Artigos de qualidade' ) > -1 ){
return false;
// Categoria:!Artigos de qualidade 1 sobre ...
// ^
}
// Qualidade do artigo
quality = cat.substr( 32, 1 );
for ( i = 0; i < cats.length; i++ ) {
if (quality === 'd') {
cat = cats[ i ].title;
quality = '?';
}
if ( cat && cat.indexOf( '!Artigos de qualidade' ) !== -1 ) {
fb.$submenu.append(
// Categoria:!Artigos de qualidade 1 sobre ...
'<span title="Qualidade do artigo"> Q-<b>' +
// ^
quality + '</b></span>'
quality = cat.substr( 32, 1 );
).find( 'a, span' ).tipsy();
break;
if ( quality === 'd' ) {
}
quality = '?';
}
}
fb.$submenu.append(
'<span title="Qualidade do artigo"> Q-<b>' +
quality + '</b></span>'
).find( 'a, span' ).tipsy();
break;
}
}
};
};


Linha 1 107: Linha 1 106:
* @param {Object} data JSON content returned by API
* @param {Object} data JSON content returned by API
*/
*/
fb.processStubs = function(data) {
fb.processStubs = function( data ) {
var template, start, sel,
var template, start, sel, esbText2
esb = document.getElementById( 'fb-esb-input' ),
esb = document.getElementById( 'fb-esb-input' ),
query = data.query;
query = data.query;
if ( query ) {
template = query.allpages && query.allpages[0] && query.allpages[0].title;
if ( query ) {
template = query.allpages && query.allpages[ 0 ] && query.allpages[ 0 ].title;
if ( !template ) {
if ( !template ) {
mw.log( 'The categories query returned incomplete data.' );
mw.log( 'The categories query returned incomplete data.' );
return false;
}
return false;
template = template.replace( /^Predefinição:Esboço-/gi, '' );
}
} else {
mw.log( 'The categories query returned no data.' );
template = template.replace( /^Predefinição:Esboço-/gi, '' );
return false;
} else {
}
mw.log( 'The categories query returned no data.' );
if ((esb.setSelectionRange
|| esb.createTextRange
return false;
|| ( typeof esb.selectionStart !== 'undefined'
}
&& typeof esb.selectionEnd !== 'undefined'
if ( ( esb.setSelectionRange
)
|| esb.createTextRange
)
|| ( typeof esb.selectionStart !== 'undefined'
&& esb.value === template.substr(0, esb.value.length)
&& typeof esb.selectionEnd !== 'undefined'
) {
)
// Exibe sugestões. Baseado no script do HotCat
start = esb.value.length;
) && esb.value === template.substr( 0, esb.value.length )
) {
esb.value = template;
// Exibe sugestões. Baseado no script do HotCat
esbText2 = template;
start = esb.value.length,
if (esb.setSelectionRange) {
esb.setSelectionRange(start, template.length);
esb.value = template,
esbText2 = template;
} else if (esb.createTextRange) {
sel = esb.createTextRange();
if ( esb.setSelectionRange ) {
sel.move( 'character', start );
sel.moveEnd( 'character', template.length - start );
esb.setSelectionRange( start, template.length );
} else if ( esb.createTextRange ) {
sel.select();
sel = esb.createTextRange();
} else {
sel.move( 'character', start );
esb.selectionStart = start;
esb.selectionEnd = template.length;
sel.moveEnd( 'character', template.length - start );
sel.select();
}
} else {
}
esb.selectionStart = start;
esb.selectionEnd = template.length;
}
}
};
};


Linha 1 152: Linha 1 156:
*/
*/
fb.processRecentEdits = function(data, code) {
fb.processRecentEdits = function(data, code) {
var listName, summaryChanges, urlParam, list, max, i,
var listName, summaryChanges, urlParam, list, max, i,
item, title, length, comment, j,
item, title, length, comment, j,
pages = [],
pages = [],
charnum = 0,
charnum = 0,
query = data.query;
query = data.query;


listName = {
listName = {
PV: 'watchlist',
PV: 'watchlist',
MR: 'recentchanges',
MR: 'recentchanges',
PN: 'recentchanges'
PN: 'recentchanges'
},
};
summaryChanges = {
summaryChanges = {
PV: [
PV: [
[ '[[Ajuda:SEA|←]]', '' ],
[ '/*', '' ],
[ '[[Ajuda:SEA|?]]', '' ],
[ '*/', ':' ]
[ '/*', '?' ],
[ '*/', ':' ]
],
],
MR: [
[ '/*', '→' ],
MR: [
[ '*/', ':' ]
[ '/*', '?' ],
],
[ '*/', ':' ]
PN: [
],
[ '[[Ajuda:SEA|?]] ', '' ]
]
PN: [
};
[ '[[Ajuda:SEA|?]] ', '' ]
urlParam = {
]
PV: 'diff=last',
},
MR: 'diff=last',
PN: 'redirect=no&rcid='
urlParam = {
};
PV: 'diff=last',
list = query[ listName[ code ] ];
MR: 'diff=last',
max = ( list.length < 10 )? list.length : 10;
PN: 'redirect=no&rcid='
};
list = query[ listName[ code ] ],
max = ( list.length < 10 )? list.length : 10;


for ( i = 0; i < max; i++ ) {
for ( i = 0; i < max; i++ ) {
item = list[ i ];
item = list[ i ];
if ( !item ){
if ( !item ){
continue;
continue;
}
}
title = item.title;
charnum += title.length;
title = item.title;
if (charnum > 180) {
charnum += title.length;
break;
}
if ( charnum > 180 ) {
length = item.newlen - item.oldlen;
break;
if (length > 0) {
}
length = '+' + length;
}
comment = item.comment || '';
length = item.newlen - item.oldlen;
for ( j=0; j < summaryChanges[ code ].length; j++ ){
if ( length > 0 ) {
comment = comment.replace(
length = '+' + length;
summaryChanges[ code ][0],
}
summaryChanges[ code ][1]
);
comment = item.comment || '';
}
if (comment) {
for ( j = 0; j < summaryChanges[ code ].length; j++ ) {
comment = '(' + comment + ')';
comment = comment.replace(
}
summaryChanges[ code ][ 0 ],
if ( code === 'PN' ){
summaryChanges[ code ][ 1 ]
urlParam[ code ] += item.rcid;
);
}
}
pages.push(
'<a href="' + mw.util.wikiGetlink( title ) + '?' +
if ( comment ) {
urlParam[ code ] + '" title="(' + length + ') ' + item.user +
' ' + comment + '">' + title + '</a>'
comment = '(' + comment + ')';
}
);
}
if ( code === 'PN' ){
fb.changeSubmenu( '<div class="horizontal">' + pages.join( ' ' ) + '</div>' );
urlParam[ code ] += item.rcid;
}
pages.push(
'<a href="' + mw.util.wikiGetlink( title ) + '?' +
urlParam[ code ] + '" title="(' + length + ') ' + item.user +
' ' + comment + '">' + title + '</a>'
);
}
fb.changeSubmenu( '<div class="horizontal">' + pages.join( ' ' ) + '</div>' );
};
};


Linha 1 224: Linha 1 244:
* @param {Object} data JSON content returned by API
* @param {Object} data JSON content returned by API
*/
*/
fb.processUserInfo = function(data, code) {
fb.processUserInfo = function( data, code ) {
var contribs, regDate, encUser,
var contribs, regDate, encUser,
user = {},
user = {},
query = data.query;
query = data.query;


// Informações do(a) usuário(a)
// Informações do(a) usuário(a)
if ( !query ) {
if ( !query ) {
mw.log( 'The categories query returned no data.' );
mw.log( 'The categories query returned no data.' );
return false;
return false;
}
}
if( code === 'anon' ){
if( !query.usercontribs ){
if ( code === 'anon' ) {
return;
if ( !query.usercontribs ) {
return;
}
contribs = query.usercontribs,
user.name = contribs[ 0 ].user,
user.editcount = contribs.length,
user.registration = contribs[ contribs.length - 1 ].timestamp;
if ( data[ 'query-continue' ] ) {
user.editcount = 'mais de ' + user.editcount;
user.registration = 'antes de ' + user.registration;
}
} else {
user = query.allusers && query.allusers[ 0 ];
}
if ( user ) {
// Ex.: YYYY-MM-DDThh:mm:ssZ
regDate = user.registration,
regDate = regDate.substr( 8, 2 ) + '/' + regDate.substr( 5, 2 ) +
'/' + regDate.substr( 0, 4 ),
encUser = encodeURI( user.name );
//FIXME: Simplify this!
fb.changeSubmenu( [
user.editcount + ' edições desde ' + regDate + '.',
'<a class="fb-button" href="' +
mw.util.wikiGetlink( 'Especial:Contribuições/' ) + encUser +
'" title="Abrir a lista de contribuições deste editor" >contribuições</a>',
'<a class="fb-button" href="' +
mw.util.wikiGetlink( 'Especial:Registo/' ) + encUser +
'" title="Abrir a lista de registros deste editor" >registros</a>',
'<a class="fb-button" href="' +
mw.util.wikiGetlink( 'Especial:Registo' ) + '?type=block&page=User%3A' + encUser +
'" title="Abrir a lista de registros de bloqueio deste editor">registros de bloqueio</a>',
'<span class="plainlinks"><a class="external text fb-button"' +
'title="Abrir a contagem de edições deste editor"' +
' href="//toolserver.org/~river/cgi-bin/count_edits?user=' +
encUser + '&dbname=' + mw.config.get('wgDBname') + '_p">contador de edições</a></span>'
].join( ' ' )
);
} else {
return;
}
};

fb.nicePrompt = function ( title, label, callback ) {
if ( !label ) {
label = 'Observação';
}
}
contribs = query.usercontribs;
var twoQuestions = label.search( '/|2=' ), $dialog = $( '<div id="nprompt-dialog" class="ui-widget" />');
user.name = contribs[0].user;
user.editcount = contribs.length;
if ( twoQuestions !== -1 ) {
user.registration = contribs[ contribs.length - 1 ].timestamp;
$dialog.append(
if( data[ 'query-continue' ] ){
'<label for="nprompt-input1">' + label.substring( 0, twoQuestions - 1 ) + '</label>'
user.editcount = 'mais de ' + user.editcount;
+ '<input type="text" id="nprompt-input1"> </input> <label for="nprompt-input2">' + label.substring( twoQuestions + 2 ) + '</label>'
user.registration = 'antes de ' + user.registration;
+ '<input type="text" id="nprompt-input2"> </input>'
}
);
} else {
} else {
user = query.allusers && query.allusers[0];
$dialog.append( '<label for="nprompt-input">' + label + '</label>' + '<input type="text" id="nprompt-input"> </input>');
}
if ( user ) {
}
// Ex.: YYYY-MM-DDThh:mm:ssZ
$dialog.dialog({
regDate = user.registration;
title: title,
regDate = regDate.substr(8, 2) + '/' + regDate.substr(5, 2) +
open: function () {
'/' + regDate.substr(0, 4);
$( '.ui-dialog-titlebar-close' ).hide();
encUser = encodeURI( user.name );
},
//FIXME: Simplify this!
close: function () {
fb.changeSubmenu( [
$( '#nprompt-dialog' ).dialog( 'destroy' );
user.editcount + ' edições desde ' + regDate + '.',
$( '#nprompt-dialog' ).remove();
'<a class="fb-button" href="' +
},
mw.util.wikiGetlink( 'Especial:Contribuições/' ) + encUser +
buttons: {
'" title="Abrir a lista de contribuições deste editor" >contribuições</a>',
'OK': function () {
'<a class="fb-button" href="' +
var answer;
mw.util.wikiGetlink( 'Especial:Registo/' ) + encUser +
'" title="Abrir a lista de registros deste editor" >registros</a>',
if ( twoQuestions === -1 ) {
'<a class="fb-button" href="' +
callback( $('#nprompt-input').val() );
mw.util.wikiGetlink( 'Especial:Registo' ) + '?type=block&page=User%3A' + encUser +
} else {
'" title="Abrir a lista de registros de bloqueio deste editor">registros de bloqueio</a>',
answer = ( $( '#nprompt-input1' ).val() + '|2=' + $( '#nprompt-input2' ).val() );
'<span class="plainlinks"><a class="external text fb-button"' +
callback( answer );
'title="Abrir a contagem de edições deste editor"' +
}
' href="//toolserver.org/~river/cgi-bin/count_edits?user=' +
encUser + '&dbname=' + mw.config.get('wgDBname') + '_p">contador de edições</a></span>'
$( this ).dialog( 'close' );
].join( ' ' )
},
);
} else {
'Cancelar': function() {
return;
$( this ).dialog( 'close' );
}
}
}
});
};

fb.useDialog = function( title, message, id ) {
$( '#' + id ).empty()
.dialog( 'option', 'title', title)
.append( $( '<div>' + message + '</div>' ) )
.dialog( 'option', 'buttons', {
'Fechar': function() {
$( this ).dialog( 'close' );
}
});
};
};


/* Initialize the gadget */
/* Initialize the gadget */
fb.init = function () {
fb.init = function () {
var inUserNS, basePageName,
var inUserNS, basePageName,
param = mw.util.getParamValue('fastb');
param = mw.util.getParamValue( 'fastb' );
if ($.inArray(mw.config.get('wgAction'), ['view', 'edit']) !== -1) {
if ( $.inArray( mw.config.get( 'wgAction' ), [ 'view', 'edit' ] ) !== -1 ) {
// FIXME: Is this still necessary? maybe fb.$submenu.empty()?
// FIXME: Is this still necessary? maybe fb.$submenu.empty()?
fb.changeSubmenu( '' );
fb.changeSubmenu( '' );
/*** Menu Principal ***/
if (mw.config.get('wgNamespaceNumber') > -1) {
/*** Menu Principal ***/
inUserNS = $.inArray(mw.config.get('wgNamespaceNumber'), [2, 3]) > -1
&& mw.config.get('wgTitle').indexOf(mw.config.get('wgUserName')) === 0;
if ( mw.config.get( 'wgNamespaceNumber' ) !== -1 ) {
inUserNS = $.inArray( mw.config.get( 'wgNamespaceNumber' ), [ 2, 3 ] ) !== -1
fb.$menu.empty();
&& mw.config.get( 'wgTitle' ).indexOf( mw.config.get( 'wgUserName' ) ) === 0;
if (inUserNS) {
fb.addButton({
fb.$menu.empty();
action: 'ER|1',
text: 'ER1',
if ( inUserNS ) {
title: 'Marcar subpágina do próprio usuário para eliminação'
fb.addButton({
});
action: 'ER|1',
} else {
text: 'ER1',
fb.addButton({
title: 'Marcar subpágina do próprio usuário para eliminação'
action: function(){
});
fb.changeSubmenu(fb.submenu.ER);
} else {
},
fb.addButton({
text: 'ER',
action: function() {
title: 'Exibir regras para a eliminação rápida'
fb.changeSubmenu(fb.submenu.ER);
});
},
}
text: 'ER',
}
title: 'Exibir regras para a eliminação rápida'
if ($.inArray(mw.config.get('wgNamespaceNumber'), [0, 102]) !== -1) {
});
fb.addButton([
}
{
}
action: function(){
fb.changeSubmenu(fb.submenu.ESR);
if ( $.inArray( mw.config.get( 'wgNamespaceNumber' ), [ 0, 102 ] ) !== -1 ) {
},
fb.addButton([ {
text: 'ESR',
action: function(){
title: 'Exibir regras para a eliminação semi-rápida'
fb.changeSubmenu(fb.submenu.ESR);
},
},
{
text: 'ESR',
action: 'subst:apagar',
title: 'Exibir regras para a eliminação semi-rápida'
text: 'PE',
}, {
title: 'Marcar para eliminação por votação'
action: 'subst:apagar',
},
text: 'PE',
{
title: 'Marcar para eliminação por votação'
action: function(){
}, {
fb.nicePrompt(
action: function(){
'Informe o url da página copiada',
fb.nicePrompt(
'Url :', function (obs) { fb.run('subst:VDA', obs);}
'Informe o url da página copiada',
);
'Url :', function (obs) { fb.run('subst:VDA', obs);}
},
);
text: 'VDA',
},
title: 'Marcar como cópia ou violação de direito autoral'
text: 'VDA',
},
title: 'Marcar como cópia ou violação de direito autoral'
{
}, {
action: 'subst:suspeito',
action: 'subst:suspeito',
text: 'susp',
text: 'susp',
title: 'Marcar como suspeito de violação de direitos autorais'
title: 'Marcar como suspeito de violação de direitos autorais'
},
}, {
{
action: 'subst:matrad',
action: 'subst:matrad',
text: 'trad',
text: 'trad',
title: 'Marcar esta tradução como sendo de baixa qualidade',
title: 'Marcar esta tradução como sendo de baixa qualidade',
prompt: 'De qual língua a página foi maltraduzida (ca, de, en, es,' +
prompt: 'De qual língua a página foi maltraduzida (ca, de, en, es,' +
' fr, it, ja, nl, no, pl, ru, sv, zh)?',
' fr, it, ja, nl, no, pl, ru, sv, zh)?',
label: 'Página:'
label: 'Página:'
}, {
},
action: 'redirect',
{
text: '#R',
action: 'redirect',
title: 'Redirecionar para outro título',
text: '#R',
title: 'Redirecionar para outro título',
prompt: 'Redirecionar para qual página?',
label: 'Página:'
prompt: 'Redirecionar para qual página?',
label: 'Página:'
}, {
action: function(){
},
fb.changeSubmenu(fb.submenu.man);
{
},
action: function(){
text: 'manutenção',
fb.changeSubmenu(fb.submenu.man);
title: 'Exibir predefinições para manutenção'
},
}, {
text: 'manutenção',
action: function(){
title: 'Exibir predefinições para manutenção'
fb.changeSubmenu(fb.submenu.esb);
},
},
{
text: 'esboço',
action: function(){
title: 'Exibir predefinições para esboços'
fb.changeSubmenu(fb.submenu.esb);
}, {
},
action: function(){
text: 'esboço',
fb.changeSubmenu(fb.submenu.search);
title: 'Exibir predefinições para esboços'
},
},
text: 'busca',
{
title: 'Exibir opções para a busca de fontes'
action: function(){
}
fb.changeSubmenu(fb.submenu.search);
] );
},
text: 'busca',
if ( mw.config.get( 'wgAction' ) === 'view' ) {
title: 'Exibir opções para a busca de fontes'
$.getJSON(
}
mw.util.wikiScript( 'api' ), {
]);
format: 'json',
if (mw.config.get('wgAction') === 'view') {
action: 'query',
$.getJSON(
list: 'backlinks',
mw.util.wikiScript( 'api' ), {
bllimit: '1',
format: 'json',
blfilterredir: 'nonredirects',
action: 'query',
blnamespace: '0',
list: 'backlinks',
bltitle: mw.config.get('wgPageName')
bllimit: '1',
},
blfilterredir: 'nonredirects',
blnamespace: '0',
fb.processBackLinks
bltitle: mw.config.get('wgPageName')
);
},
}
fb.processBackLinks
} else {
);
if ( $.inArray( mw.config.get( 'wgNamespaceNumber' ), [ 2, 10 ] ) !== -1 ) {
}
fb.addButton({
} else {
action: 'subst:apagar',
if ($.inArray(mw.config.get('wgNamespaceNumber'), [2, 10]) !== -1) {
text: 'PE',
fb.addButton({
title: 'Marcar para eliminação por votação'
action: 'subst:apagar',
});
text: 'PE',
}
title: 'Marcar para eliminação por votação'
});
if ( mw.config.get( 'wgNamespaceNumber' ) % 2 === 0 ) {
}
fb.addButton({
if (mw.config.get('wgNamespaceNumber') % 2 === 0) {
action: 'redirect',
fb.addButton({
text: '#R',
action: 'redirect',
title: 'Redirecionar para outro título',
text: '#R',
title: 'Redirecionar para outro título',
prompt: 'Redirecionar para qual página?',
label: 'Página:'
prompt: 'Redirecionar para qual página?',
label: 'Página:'
});
}
});
}
if (mw.config.get('wgNamespaceNumber') === 14) {
if ( mw.config.get( 'wgNamespaceNumber' ) === 14 ) {
fb.addButton({
fb.addButton({
action: function(){
action: function() {
fb.changeSubmenu(fb.submenu.cat);
fb.changeSubmenu( fb.submenu.cat );
},
},
text: 'CatScan',
text: 'CatScan',
title: 'Exibir opções do CatScan para procurar páginas nesta categoria'
title: 'Exibir opções do CatScan para procurar páginas nesta categoria'
});
});
}
}
}
}
if (mw.config.get('wgNamespaceNumber') === 3) {
if ( mw.config.get( 'wgNamespaceNumber' ) === 3 ) {
fb.addButton({
fb.addButton({
action: function(){
action: function() {
fb.changeSubmenu(fb.submenu.warn);
fb.changeSubmenu( fb.submenu.warn );
},
},
text: 'aviso',
text: 'aviso',
title: 'Exibir lista de predefinições para avisos'
title: 'Exibir lista de predefinições para avisos'
});
});
}
}
if ($.inArray(mw.config.get('wgNamespaceNumber'), [2, 3]) !== -1) {
basePageName = mw.config.get('wgTitle').split('/')[0];
if ( $.inArray( mw.config.get( 'wgNamespaceNumber' ), [ 2, 3 ] ) !== -1 ) {
if ( mw.util.isIPv4Address( basePageName ) || mw.util.isIPv6Address( basePageName ) ) {
basePageName = mw.config.get( 'wgTitle' ).split( '/' )[ 0 ];
fb.addButton({
action: function(){
if ( mw.util.isIPv4Address( basePageName ) || mw.util.isIPv6Address( basePageName ) ) {
fb.callAPI('anon');
fb.addButton({
},
action: function(){
text: 'sobre o IP',
fb.callAPI('anon');
title: 'Exibir informações sobre este IP'
},
});
text: 'sobre o IP',
} else {
title: 'Exibir informações sobre este IP'
fb.addButton({
});
action: function(){
} else {
fb.callAPI('usu');
fb.addButton({
},
action: function(){
text: 'sobre a conta',
fb.callAPI( 'usu' );
title: 'Exibir informações sobre esta conta'
},
});
text: 'sobre a conta',
}
title: 'Exibir informações sobre esta conta'
});
}


}
}
}
fb.addButton([
{
action: function(){
fb.callAPI('PV');
},
text: 'PV',
title: 'Exibir páginas vigiadas que foram alteradas recentemente'
},
{
action: function(){
fb.callAPI('PN');
},
text: 'PN',
title: 'Exibir páginas novas que ainda não foram patrulhadas'
},
{
action: function(){
fb.callAPI('MR');
},
text: 'MR',
title: 'Exibir mudanças recentes feitas por IPs em páginas do domínio principal'
}
]);
if( mw.config.get('skin') === 'modern' ){
$( '#contentSub' ).before( fb.$menu ).before( fb.$submenu );
} else {
$( 'h1' ).first().after( fb.$submenu ).after( fb.$menu );
}

switch (mw.config.get('wgAction')) {
case 'edit':
// FIXME: Use API to edit, because pseudo actions may be dangerous
// (see [[commons:Commons:Administrators' noticeboard/Archive 34#MediaWiki:Gadget-autodel.js]])
fb.save = (param !== null);
if (fb.save) {
fb.run(param, mw.util.getParamValue('fbtxt') || '');
}
break;
case 'markpatrolled':
// FIXME: Use API to patrol, because pseudo actions may be dangerous (see above)
if (param !== null) {
location.href = mw.util.wikiGetlink( mw.config.get('wgPageName') ) +
'?action=edit&fastb=' + param;
}
break;
default:
// Não faz nada nas demais ações
}
fb.$menu.find( 'a' ).tipsy();
};
fb.nicePrompt = function (title, label, callback) {
'use strict';
if (!label){
label = 'Observação';
}
}
var twoQuestions = label.search('/|2='), $dialog = $('<div id="nprompt-dialog" class="ui-widget"></div>');
if (twoQuestions !== -1) {
fb.addButton([ {
action: function(){
$dialog.append('<label for="nprompt-input1">' + label.substring(0, twoQuestions - 1) + '</label>' + '<input type="text" id="nprompt-input1"> </input> <label for="nprompt-input2">' + label.substring(twoQuestions + 2) + '</label>' + '<input type="text" id="nprompt-input2"> </input>');
fb.callAPI('PV');
},
text: 'PV',
title: 'Exibir páginas vigiadas que foram alteradas recentemente'
}, {
action: function(){
fb.callAPI('PN');
},
text: 'PN',
title: 'Exibir páginas novas que ainda não foram patrulhadas'
}, {
action: function(){
fb.callAPI('MR');
},
text: 'MR',
title: 'Exibir mudanças recentes feitas por IPs em páginas do domínio principal'
}
]);
if ( mw.config.get( 'skin' ) === 'modern' ) {
$( '#contentSub' ).before( fb.$menu ).before( fb.$submenu );
} else {
} else {
$( 'h1' ).first().after( fb.$submenu ).after( fb.$menu );
$dialog.append('<label for="nprompt-input">' + label + '</label>' + '<input type="text" id="nprompt-input"> </input>');
}
}

$dialog.dialog({
title: title,
switch ( mw.config.get( 'wgAction' ) ) {
open: function () {
case 'edit':
// FIXME: Use API to edit, because pseudo actions may be dangerous
$(".ui-dialog-titlebar-close").hide();
// (see [[commons:Commons:Administrators' noticeboard/Archive 34#MediaWiki:Gadget-autodel.js]])
},
close: function () {
fb.save = ( param !== null );
$('#nprompt-dialog').dialog('destroy');
$('#nprompt-dialog').remove();
if ( fb.save ) {
fb.run( param, mw.util.getParamValue( 'fbtxt' ) || '' );
},
buttons: {
}
"OK": function () {
var answer;
break;
if (twoQuestions === -1) {
callback($('#nprompt-input').val());
case 'markpatrolled':
} else {
// FIXME: Use API to patrol, because pseudo actions may be dangerous (see above)
answer = ($('#nprompt-input1').val() + '|2=' + $('#nprompt-input2').val());
if ( param !== null ) {
callback(answer);
location.href = mw.util.wikiGetlink( mw.config.get( 'wgPageName' ) ) +
}
'?action=edit&fastb=' + param;
$(this).dialog("close");
}
},
break;
Cancelar: function() {
fb.useDialog('Ah!', 'Você cancelou!', 'nprompt-dialog');
default:
}
// Não faz nada nas demais ações
}
}
});
fb.$menu.find( 'a' ).tipsy();
};
};

fb.useDialog = function (title, message, id) {
'use strict';
$('#' + id).empty();
$('#' + id).dialog("option", "title", title);
$('#' + id).append($('<div>' + message + '</div>'));
$('#' + id).dialog("option", "buttons", { "Fechar": function() {
$(this).dialog("close");
} } );
};
/* Executes the gadget when document is ready */
/* Executes the gadget when document is ready */
window.fb = fb;
window.fb = fb;

mw.loader.using( 'jquery.tipsy', function() {
mw.loader.using( 'jquery.tipsy', function() {
$( fb.init );
$( fb.init );
} );
} );



Revisão das 01h50min de 15 de julho de 2012

/** FastButtons
 * @author: [[es:User:Racso]] (versão original do script, na Wikipédia em espanhol)
 * @author: [[en:User:Macy]] (versão adaptada para a Wikipédia inglesa)
 * @author: Outros editores que aparecem no histórico
 * @source: [[en:User:Macy/FastButtons.js]] (//en.wikipedia.org/w/index.php?oldid=230473471)
 * @source: [[es:Special:PrefixIndex/User:Racso/FB]]
 */
/*jslint browser: true, white: true, devel: true, plusplus: true, continue: true */
/*global jQuery, mediaWiki */
( function ( $, mw ) {
'use strict';

var fb = {
        // Replace this string by 5~ before saving:
        version: '17h16min de 11 de julho de 2012 (UTC)',
        ns: mw.config.get( 'wgNamespaceNumber' ),
        title: mw.config.get( 'wgTitle' ),
        submenu: {},
        $menu: $( '<div id="fb-menu" />' ),
        $submenu: $( '<div id="fb-submenu" />' )
};

/* Create new button links
 * @param {(jQuery|Array|Object)}
 *                 $target A jQuery object representing the target or
 *                         an object representing a button (see 'buttons' param below)
 *                         an Array of this kind of objects
 *                 (Defaults to fb.$menu if the it is not an instance of jQuery)
 * @param {{action: (string|function()), text: string, title: string, prompt: string, label: string, disable: boolean}=}
 *                 buttons Atributes and other information for the new button
 * @return {boolean} true Not useful so far
 */
fb.addButton = function ( $target, buttons ) {
        var     comment, props, button, i,
                doNothing = function( event ) {
                        event.preventDefault();
                },
                
                buttonClick = function( btn ){
                        return function( event ){
                                var question = typeof btn.action === 'string'
                                                && btn.action.substr( 0, 2 ) === 'ER'
                                        ? 'Se necessário, coloque uma observação.'
                                        : btn.prompt, promptCallback;
                                event.preventDefault();
                                
                                promptCallback = function( comment ){
                                        if ( $.isFunction( btn.action ) ) {
                                            btn.action();
                                        } else {
                                            fb.run( btn.action, comment);
                                        }
                                };
                                
                                if ( question ) {
                                        comment = fb.nicePrompt( question, btn.label, promptCallback );
                                } else {
                                        promptCallback ( comment );
                                }
                        };
                };
                
        if ( !$target.jquery ) {
                // if $target is not an instance of jQuery, use it as 'buttons'
                buttons = $target;
                $target = fb.$menu;
        }
        
        if ( !$.isArray( buttons ) ){
                buttons = [ buttons ];
        }
        
        for ( i = 0; i < buttons.length; i++ ) {
                button = buttons[ i ];
                props = {
                        title: button.title,
                        text: button.text
                };

                if ( button.disable ) {
                        props[ 'class' ] = 'fb-button fb-disabled-button',
                        props.click = doNothing;
                } else {
                        props[ 'class' ] = $.isFunction( button.action )
                                ? 'fb-button fb-menu-button'
                                : 'fb-button fb-action-button',
                        props.click = buttonClick( button );
                }
                
                $( '<a />', props ).appendTo( $target ).after( ' ' );
        }
        
        return true;
};

fb.catScanOptions = function(){
        var     i, catScanUrl, list;
        
        list = [ {
                        text: 'sem fontes',
                        desc: 'Procurar páginas desta categoria que precisam de fontes',
                        url: 'ts&templates=Sem-fontes'
                }, {
                        text: 'revisão',
                        desc: 'Procurar páginas desta categoria que precisam de revisão',
                        url: 'ts&templates=Revis%C3%A3o'
                }, {
                        text: 'wikificação',
                        desc: 'Procurar páginas desta categoria que precisam de wikificação',
                        url: 'ts&templates=Wikifica%C3%A7%C3%A3o'
                }, {
                        text: 'menos de 1 000 bytes ou 4 links',
                        desc: 'Procurar páginas desta categoria que possuem menos de 1 000 bytes ou 4 links',
                        url: 'ss&size=1000&stubop=or&links=4'
                }, {
                        text: 'menos de 500 bytes ou 2 links',
                        desc: 'Procurar páginas desta categoria que possuem menos de 500 bytes ou 2 links',
                        url: 'ss&size=500&stubop=or&links=2'
                } ];

        catScanUrl = '//toolserver.org/~daniel/WikiSense/CategoryIntersect.php?' +
                $.param( {
                        wikilang:  mw.config.get( 'wgContentLanguage' ),
                        wikifam: '.wikipedia.org',
                        userlang: mw.config.get( 'wgUserLanguage' ),
                        basecat: mw.config.get( 'wgTitle' ),
                        basedeep: '1',
                        go: 'Examinar',
                        format: 'html',
                        mode: ''
                } );
                
        fb.$submenu.append( 'Procurar nesta categoria:' );
        
        for( i = 0; i < list.length; i++ ){
                fb.$submenu.append( ' ', $('<a></a>', {
                        'class': 'fb-button',
                        'href': catScanUrl + list[ i ].url,
                        'text': list[ i ].text,
                        'title': list[ i ].desc
                }) );
        }
};

fb.addSearchOptions = function(){
        var     i,
                $searchOptions = $('<span class="plainlinks"></span>'),
                search = encodeURIComponent(
                        fb.title.indexOf( ' ' ) > -1
                                ? '"' + fb.title + '"'
                                : fb.title
                ),
                
                list = [ {
                        text: 'Google',
                        desc: 'Pesquisar o título desta página no Google',
                        url: '//www.google.com/search?&as_eq=wikipedia&as_epq=',
                        after: ' — '
                }, {
                        text: 'notícias',
                        desc: 'Pesquisar o título desta página no Google Notícias',
                        url: '//news.google.com/archivesearch?&as_src=-newswire+-wire+-presswire+-PR+-press+-release&as_epq=',
                        after: ', '
                }, {
                        text: 'livros',
                        desc: 'Pesquisar o título desta página no Google Livros',
                        url: '//books.google.com/books?&as_brr=0&as_epq=',
                        after: ', '
                }, {
                        text: 'acadêmico',
                        desc: 'Pesquisar o título desta página no Google Acadêmico',
                        url: '//scholar.google.com/scholar?as_epq=',
                        after: ' — '
                }, {
                        text: 'Scirus',
                        desc: 'Pesquisar o título desta página no Scirus',
                        url: '//www.scirus.com/srsapp/search?t=all&sort=0&g=s&q='
                } ];
                
        for ( i = 0; i < list.length; i++ ) {
                $searchOptions.append( $( '<a></a>', {
                        'class': 'external text',
                        'href': list[ i ].url + search,
                        'text': list[ i ].text,
                        'title': list[ i ].desc
                }) );
                
                if ( list[ i ].after ) {
                        $searchOptions.append( list[ i ].after );
                }
        }
        
        fb.$submenu.append( $searchOptions );
};

fb.addFieldForOtherESROptions = function(){
        var $otherInput, $okButton;

        $otherInput = $( '<input type="text" id="fb-esr-input" size=55/>')
                .keypress( function( event ) {
                        fb.ok( event, 'ESR' );
                } );
                
        $okButton = $( '<input type="button" value="OK"/>' )
                .mousedown( function(){
                        fb.ok( 'ok', 'ESR' );
                } );

        fb.$submenu.append( 'outra: ', $otherInput, $okButton );
};

fb.addFieldForStubs = function(){
        var $stubInput, $okButton;

        $stubInput = $( '<input id="fb-esb-input" size=14/>' )
                .keyup( function(){
                        fb.callAPI( 'esb' );
                } )
                .keypress( function( event ){
                        fb.ok( event, 'esb' );
                } );
                
        $okButton = $('<input type="button" value="OK"/>')
                .mousedown( function () {
                        fb.ok( 'ok', 'esb' );
                } );

        fb.$submenu.append( ' esboço-', $stubInput, $okButton );
};

/*** Submenu [ER] ***/
fb.submenu.ER = [ {
                action: 'ER|1',
                text: '1',
                title: '???',
                disable: true
        }, {
                action: 'ER|5',
                text: '5',
                title: 'Aparecimento recorrente (se o conteúdo for igual ao eliminado por votação)'
        }, {
                action: 'ER|6',
                text: '6',
                title: 'Título é SPAM',
                disable: $.inArray( fb.ns, [ 0, 102 ] ) === -1
        }, {
                action: 'ER|7',
                text: '7',
                title: 'Próprio criador reconhece que se enganou'
        }, {
                action: 'ER|8',
                text: '8',
                title: 'Eliminações temporárias sem perda de histórico para resolver problemas técnicos',
                disable: $.inArray('sysop', mw.config.get('wgUserGroups')) === -1
        }, {
                action: 'ER|9',
                text: '9',
                title: 'Eliminar redirect, página sem histórico relevante' +
                        ' (mover página redirecionada para cá)'
        }, {
                action: 'ER|10',
                text: '10',
                title: 'Namespaces que não existem (WikipÉdia, AjUda)',
                disable: fb.ns !== 0
        }, {
                action: 'ER|11',
                text: '11',
                title: 'Má configuração do teclado (Página, Usuário:Sicrano)'
        }, {
                action: 'ER|12',
                text: '12',
                title: 'Imagens, somente por quem a carregou',
                disable: fb.ns !== 6
        }, {
                action: 'ER|13',
                text: '13',
                title: 'Páginas sem histórico relevante que são violações flagrantes de' +
                        ' direitos autorais de outras páginas na internet.',
                disable: $.inArray( fb.ns, [ 0, 102 ] ) === -1
        }, {
                action: 'ER|14',
                text: '14',
                title: 'Ficheiros (arquivos) duplicados',
                disable: fb.ns !== 6
        }, {
                action: 'ER|17',
                text: '17',
                title: 'Salto de domínio'
        }, {
                action: 'ER|18',
                text: '18',
                title: 'Discussão cujos artigos não existem',
                disable: fb.ns !== 1
        }, {
                action: 'ER|19',
                text: '19',
                title: 'Ficheiros (domínio Ficheiro:) que não são som, imagem ou vídeo',
                disable: fb.ns !== 6
        }, {
                action: 'ER|20',
                text: '20',
                title: 'Impróprio'
        }, {
                action: 'ER|21',
                text: '21',
                title: 'Página de eliminação de um artigo antes de passados 6 meses da última votação',
                disable: mw.config.get( 'wgPageName' ).indexOf( 'Wikipédia:Páginas_para_eliminar/' ) !== 0
        }, {
                action: 'ER|A1',
                text: 'A1',
                title: 'Páginas com o título malformatado, absurdo, com palavras que não' +
                        ' o são, com erros devidos à má configuração do teclado, com codificação' +
                        ' incorreta do sistema ou que expressem domínios que não existem.',
                disable: $.inArray( fb.ns, [ 0, 102 ] ) === -1
        }, {
                action: 'ER|C1',
                text: 'C1',
                title: 'Categorias vazias, desnecessárias ou substituídas',
                disable: fb.ns !== 14
        }, {
                action: 'ER|D1',
                text: 'D1',
                title: 'Discussões de páginas inexistentes',
                disable: fb.ns % 2 === 0
        }, {
                action: 'ER|D2',
                text: 'D2',
                title: 'Discussões de páginas para eliminação ou com histórico irrelevante',
                disable: fb.ns % 2 === 0
        }, {
                action: 'ER|U1',
                text: 'U1',
                title: 'Uso impróprio da página de usuário',
                disable: $.inArray( fb.ns, [ 2, 3 ] ) === -1
        }, {
                action: 'ER|U2',
                text: 'U2',
                title: 'Página de usuário criada por outro usuário',
                disable: fb.ns !== 2
        }, {
                action: 'ER|P1',
                text: 'P1',
                title: 'Predefinições vazias, desnecessárias ou substituídas',
                disable: fb.ns !== 10
        }, {
                action: 'ER|R1',
                text: 'R1',
                title: 'Redirecionamento indevido, desnecessário, sem afluentes,' +
                        ' para páginas inexistente ou eliminadas'
        }, {
                action: 'ER|R2',
                text: 'R2',
                title: 'Redirecionamento de página de discussão sem afluentes',
                disable: fb.ns % 2 === 0
        }
];

/*** Submenu [ESR] ***/
fb.submenu.ESR = [ {
                action: 'subst:ESR-banda|1=~~' + '~~',
                text: 'banda',
                title: 'Artigo sobre banda sem fontes e sem notoriedade'
        }, {
                action: 'subst:ESR-bio|1=~~' + '~~',
                text: 'biografia',
                title: 'Biografia sem fontes e sem notoriedade'
        }, {
                action: 'subst:ESR-empresa|1=~~' + '~~',
                text: 'empresa',
                title: 'Empresa sem fontes e sem notoriedade'
        },
        
        fb.addFieldForOtherESROptions
];

/*** Submenu [esboço] ***/
fb.submenu.esb = [ {
                action: 'mínimo',
                text: 'mínimo',
                title: 'Artigo com apenas uma frase'
        }, {
                action: 'esboço',
                text: 'esboço',
                title: 'Artigo ainda pouco desenvolvido'
        },
        
        fb.addFieldForStubs
];

/*** Submenu [manuteção] ***/
fb.submenu.man = [ {
                action: 'subst:wkf',
                text: 'wikificar',
                title: 'Não está formatado de acordo com o livro de estilo'
        }, {
                action: 'subst:s-fontes',
                text: 'sem fontes',
                title: 'Página não cita nenhuma fonte ou referência'
        }, {
                action: 'subst:s-cat',
                text: 'sem cat',
                title: 'Página não está em nenhuma categoria'
        }, {
                action: 'subst:rec',
                text: 'reciclagem',
                title: 'Página precisa ser reciclada de acordo com o livro de estilo'
        }, {
                action: 'parcial',
                text: 'parcial',
                title: 'Artigo possui passagens que não respeitam o princípio da imparcialidade'
        }, {
                action: 'subst:ctx',
                text: 'contexto',
                title: 'Página carece de contexto'
        }, {
                action: 'controverso|artigo',
                text: 'controverso',
                title: 'controverso devido às disputas sobre o seu conteúdo'
        }, {
                action: 'subst:f-referências',
                text: 'formatar referências',
                title: 'Artigo contém referências que necessitam de formatação'
        }, {
                action: 'subst:m-notas',
                text: 'mais notas',
                title: 'Página cita fontes fiáveis, mas não cobre todo o texto'
        }, {
                action: 'subst:s-notas',
                text: 'sem notas',
                title: 'Existem fontes no final da página, mas não são citadas no corpo do artigo'
        }, {
                action: 'subst:s-fontes-bpv',
                text: 'bpv sem fontes',
                title: 'Biografia de pessoa viva que não cita nenhuma fonte'
        }, {
                action: 'subst:fpr',
                text: 'fonte primária',
                title: 'Artigo necessita de fontes secundárias fiáveis publicadas por terceiros'
        }, {
                action: 'subst:fu',
                text: 'fusão',
                title: 'Artigo necessita de fusão',
                prompt: 'Com qual página esta deve ser feita fusão?',
                label: 'Página:'
        }, {
                action: 'subst:f-de',
                text: 'fusão de',
                title: 'Artigo necessita de fusão',
                prompt: 'De qual página esta deve ser feita fusão?',
                label: 'Página:'
        }, {
                action: 'subst:f-com',
                text: 'fusão com',
                title: 'Artigo necessita de fusão',
                prompt: 'Com qual página esta deve ser feita fusão?',
                label: 'Página:'
        }
];

/*** Submenu [aviso] ***/
fb.submenu.warn = [ {
                action: 'subst:bem-vindo IP',
                text: 'BV-IP',
                title: 'Boas-vindas para usuário(a) não registrado(a)'
        }, {
                action: 'subst:bem-vindo',
                text: 'BV',
                title: 'Bem-vindo(a) à Wikipédia'
        }, {
                action: 'subst:bem-vinda',
                text: 'BVª',
                title: 'Bem-vinda à Wikipédia'
        }, {
                action: 'subst:bv-av',
                text: 'av-BV-IP',
                title: 'Aviso sobre erro em artigo e boas-vindas para usuário(a) não registrado(a)',
                prompt: 'Aviso sobre qual artigo?',
                label: 'Artigo:'
        }, {
                action: 'subst:bv-av-registrado',
                text: 'av-BV',
                title: 'Aviso sobre erro em artigo e boas-vindas para usuário(a) registrado',
                prompt: 'Aviso sobre qual artigo?',
                label: 'Artigo:'
        }, {
                action: 'subst:aviso-ER',
                text: 'av-ER',
                title: 'Aviso sobre eliminação rápida',
                prompt: 'Qual página foi proposta para eliminação?',
                label: 'Página:'
        }, {
                action: 'subst:av-bv-ER',
                text: 'av-BV-ER',
                title: 'Aviso sobre eliminação rápida + boas-vindas',
                prompt: 'Qual página foi proposta para eliminação?',
                    label: 'Página:'
        }, {
                action: 'subst:aviso-ESR',
                text: 'av-ESR',
                title: 'Aviso sobre eliminação semirrápida',
                prompt: 'Qual página foi proposta para eliminação?',
                label: 'Página:'
        }, {
                action: 'subst:aviso-PE',
                text: 'av-PE',
                title: 'Aviso sobre eliminação por votação',
                prompt: 'Qual página foi proposta para eliminação?',
                label: 'Página:'
        }, {
                action: 'subst:bv-propaganda',
                text: 'prop-BV',
                title: 'Caro editor,por favor não faça propaganda, [...] Apesar disso, bem-vindo à Wikipédia'
        }, {
                action: 'subst:propaganda',
                text: 'prop',
                title: 'Caro editor, por favor não faça propaganda...',
                prompt: 'Em que página foi feita propaganda?',
                label: 'Página:'
        }, {
                action: 'subst:aviso',
                text: 'av',
                title: 'Aviso sobre erro em artigo',
                prompt: 'Aviso sobre qual artigo?',
                label: 'Artigo:'
        }, {
                action: 'subst:aviso2',
                text: 'av2',
                title: 'Aviso sobre vandalismo',
                prompt: 'Qual página foi vandalizada?',
                label: 'Página:'
        }, {
                action: 'subst:BSRE',
                text: 'BSRE',
                title: 'Aviso de biografia sem relevo enciclopédico',
                prompt: 'Qual artigo?',
                label: 'Artigo:'
        }, {
                action: 'subst:cópia',
                text: 'cópia',
                title: 'Aviso sobre artigo copiado de fonte externa/VDA',
                prompt: 'Qual a página da Wikipédia? E qual a URL da página copiada?',
                label: 'Página:|2=URL:'
        }, {
                action: 'subst:linguagem incorreta',
                text: 'linguagem',
                title: 'Não insulte nem use linguagem inadequada em artigos ou discussões'
        }, {
                action: 'subst:ortografia',
                text: 'ortografia',
                title: 'Não mude a versão da língua',
                prompt: 'Em qual artigo a versão da língua foi alterada?',
                label: 'Artigo:'
        }, {
                action: 'subst:mostrar previsão',
                text: 'salvamento sucessivo',
                title: 'Não faça salvamentos sucessivos, utilize o botão \'Mostrar previsão\'',
                prompt: 'Em que artigo foram feitos salvamentos sucessivos?',
                label: 'Página:'
        }, {
                action: 'subst:av-boas vindas',
                text: 'aviso-BV',
                title: 'Não dê boas-vindas a usuários que não contribuíram com pelo menos uma edição válida'
        }, {
                action: 'subst:av-página de usuário',
                text: 'av-PU',
                title: 'Considere refazer a página de usuário(a)'
        }, {
                action: 'subst:não remova',
                text: 'não remova',
                title: 'Não remova marcações de eliminação das páginas',
                prompt: 'Qual página em que a marcação de eliminação foi removida?' +
                        'Se desejar, pode especificar o tipo de marcação.',
                label: 'Página:|2=Tipo de marcação:'
        }, {
                action: 'subst:autobiografia',
                text: 'autobiografia',
                title: 'Não crie autobiografias',
                prompt: 'Qual autobiografia foi criada?',
                label: 'Página:'
        }, {
                action: 'subst:av-teste',
                text: 'av-teste',
                title: 'Não faça testes nos artigos',
                prompt: 'Qual o nível do aviso? E em que página foram feitos testes?',
                label: 'Nível:|2=Página:'
        }, {
                action: 'subst:av-data',
                text: 'av-data',
                title: 'Não insira seu nome e data de nascimento em páginas de datas',
                prompt: 'Em que página de data foram inseridos o nome e a data de nascimento?',
                label: 'Página:'
        }, {
                action: 'subst:aviso-matrad',
                text: 'aviso-matrad',
                title: 'Aviso sobre má tradução',
                prompt: 'Qual página foi marcada como má tradução?',
                label: 'Página:'
        }, {
                action: 'subst:bloqueado',
                text: 'bloqueado',
                title: 'Notificação de bloqueio',
                prompt: 'Especifique o tempo e o motivo do bloqueio.',
                label: 'Tempo:|2=Motivo'
        }, {
                action: 'subst:bloqueado-disc',
                text: 'bloqueado-disc',
                title: 'Notificação de bloqueio com discussão',
                prompt: 'Especifique o tempo e o motivo do bloqueio.',
                label: 'Tempo:|2=Motivo'
        }, {
                action: 'subst:bloqueado-CPV',
                text: 'bloqueado-CPV',
                title: 'Notificação de bloqueio para contas para vandalismo'
        }, {
                action: 'proxy',
                text: 'proxy',
                title: 'Notificação de proxy bloqueado'
        }, {
                action: 'subst:cite fonte',
                text: 'citar fontes',
                title: 'Faltou citar fontes à página',
                prompt: 'Qual foi a página?',
                label: 'Página:'
        }
];

/** Submenu [busca] **/
fb.submenu.search = fb.addSearchOptions;

/** Submenu [CatScan] **/
fb.submenu.cat = fb.catScanOptions;

// FIXME: Consider using jQuery: $('#target').keypress()
fb.ok = function( event, option ) {
        if ( window.event && window.event.keyCode === 13 ) {
                event = 'ok';
        } else if ( event && event.which === 13 ) {
                event = 'ok';
        }
        
        if ( event === 'ok' ) {
                if ( option === 'esb' ) {
                        fb.run( 'esboço-' + $( '#fb-esb-input' ).val() );
                } else if ( option === 'ESR' ) {
                        fb.run( 'subst:ESR', $( '#fb-esr-input').val() + ' ~~' + '~~' );
                }
        }
};

/* Patrol the edit currently displayed
 * @param {function()} succes Callback function to be executed after the edit is pattroled
 */
fb.patrolRevision = function ( rcid, success ) {
        $.getJSON(
                mw.util.wikiScript( 'api' ), {
                        format: 'json',
                        action: 'query',
                        list: 'recentchanges',
                        rctoken: 'patrol',
                        rcprop: '',
                        rclimit: '1'
                },
                
                function( data ) {
                        var     query = data.query,
                                rc = query && query.recentchanges,
                                token = rc && rc[ 0 ] && rc[ 0 ].patroltoken;
                                
                        if ( !token ) {
                                mw.log( 'Não foi possível obter um token para patrulhar a edição.' );
                                return false;
                        }
                        
                        if ( !rcid ) {
                                mw.log( 'Não foi possível identificar a edição a ser patrulhada.' );
                                return false;
                        }
                        
                        $.post(
                                mw.util.wikiScript( 'api' ), {
                                        action: 'patrol',
                                        format: 'json',
                                        token: token,
                                        rcid: rcid
                                },
                                
                                function( data ) {
                                        if ( data.error ) {
                                                mw.log( 'Não foi possível patrulhar a edição: ' + data.error.info );
                                                return false;
                                        }
                                        
                                        if ( $.isFunction( success ) ){
                                                success();
                                        }
                                        
                                        mw.log( 'A edição foi marcada como patrulhada.' );
                                        
                                        return true;
                                }
                        ).error( function() {
                                window.alert( 'Houve um erro inesperado ao usar a API do MediaWiki.' );
                                
                                return false;
                        } );
                }
        ).error( function() {
                alert( 'A API retornou um erro ao tentar obter um token para patrulhar a edição.' );
                
                return false;
        });
};

/* Função de edição
 * @param: {string} code A template name, possibly preceded by "subst:",
 *                         and optionally followed by "|" and some parameter(s)
 * @param: {(string|null)=} extraText Extra text for templates and redirects (optional)
 * @return: {boolean} Returns false if the user canceled or the page already has a template
 */
fb.run = function ( code, extraText ) {
        var     $patrol, rcid,
                $textBox = $( '#wpTextbox1' ),
                value = $textBox.val(),
                url = mw.util.wikiGetlink( mw.config.get( 'wgPageName' ) ) + '?',
                data = {
                        action: 'edit',
                        fastb: code
                },
                summary = ' (usando [[WP:FB|FastButtons]])',
                // FIXME: Move this to the definition of each button
                summaries = {
                        'subst:VDA': 'Página marcada como [[WP:VDA|VDA]]',
                        'subst:apagar': 'Página proposta para [[WP:Eliminação' +
                                ' por votação|eliminação por votação]]',
                        'subst:s-fontes': 'Página marcada como sem fontes',
                        'subst:s-cat': 'Página marcada como sem categoria',
                        'subst:wkf': 'Página marcada para [[WP:WKF|wikificação]]',
                        'subst:rec': 'Página marcada para [[WP:RECI|reciclagem]]',
                        'parcial': 'Página marcada como parcial',
                        'subst:ctx': 'Página marcada como sem contexto',
                        'controverso|artigo': 'Marcado como controverso',
                        'subst:f-referências': 'Marcado que existem referências sem formatação',
                        'subst:m-notas': 'Marcado que carece de mais fontes',
                        'subst:s-notas': 'Página marcada como sem notas',
                        'subst:s-fontes-bpv': 'Marcado como [[WP:BPV|biografia de pessoa' +
                                        ' viva]] sem fontes',
                        'subst:fpr': 'Página marcada como sem fontes secundárias fiáveis',
                        'subst:ESR': 'Página proposta para [[WP:ESR|eliminação semirrápida]]',
                        'subst:matrad': 'Página marcada como [[WP:Tradução|má tradução]]',
                        'subst:suspeito': 'Página marcada como suspeita de [[WP:VDA|VDA]]',
                        'subst:fu': 'Página marcada para [[WP:Fusão|fusão]]',
                        'subst:f-de': 'Página marcada para [[WP:Fusão|fusão]]',
                        'subst:f-com': 'Página marcada para [[WP:Fusão|fusão]]'
                };
                
        if ( extraText === null ) {
                // Do nothing if the user canceled the prompt box
                return false;
        }
        
        switch ( mw.config.get( 'wgAction' ) ) {
                case 'view':
                        if ( extraText ) {
                                data.fbtxt = extraText;
                        }
                        
                        $patrol = mw.util.$content.find( 'span.patrollink a' ).first(),
                        rcid     = mw.util.getParamValue( 'rcid', $patrol.attr( 'href' ) || '' );
                        
                        if ( rcid ) {
                                fb.patrolRevision( rcid, function(){
                                        location.href = url + $.param( data );
                                } );
                        } else {
                                location.href = url + $.param( data );
                        }
                break;
                        
                case 'edit':
                        if ( value.match( /\{\{(?:subst:)?(?:ER|ESR(?:2?|-banda|-bio|-empresa|-bsre|-organização)|VDA|Usuário(?:\(a\))?\:Salebot\/Impróprio)[\|\}]/i ) ) {
                                alert( 'Já existe uma predefinição de eliminação nesta página.' );
                                
                                return false;
                        }
                        
                        if ( code.indexOf( 'ER' ) === 0 ) {
                                extraText = extraText ? '|3=' + extraText: '',
                                extraText = '{' + '{' + code + '|2=~~' + '~~' + extraText + '}}\n',
                                $textBox.val( extraText + value );
                                
                                if ( fb.save ) {
                                        $( 'input[name="wpSummary"]' ).val(
                                                'Página proposta para' +
                                                ' [[WP:ER|eliminação rápida]] (regra ' +
                                                code.substring( 3 ) + ')' + summary
                                        );        
                                }
                                
                        } else if ( code === 'redirect' ) {
                                if ( mw.config.get( 'wgNamespaceNumber' ) === 14 ) {
                                        if ( extraText ) {
                                                $textBox.val( '{' + '{redirecionamento de categoria|' + extraText + '}}' );
                                        }
                                        
                                        if ( fb.save ) {
                                                document.editform.wpSummary.value = 'Redirecionando para' +
                                                        ' a [[categoria:' + extraText + ']]' + summary;
                                        }
                                } else {
                                        if ( extraText ) {
                                                $textBox.val( '#Redirecionamento [[' + extraText + ']]' );
                                        }
                                }
                        } else {
                                extraText = extraText ? '|1=' + extraText: '',
                                extraText = '{' + '{' + code + extraText + '}}';
                                
                                if ( mw.config.get( 'wgNamespaceNumber' ) === 3 ) {
                                        value += '\n\n' + extraText + ' ~~' + '~~';
                                } else if ( code === 'mínimo' || code.indexOf( 'esboço' ) === 0 ) {
                                        if ( value.match( /\n\n\[\[/ ) ) {
                                                value = value.substring( 0, value.search( /\n\n\[\[/ ) ) + '\n\n' +
                                                        extraText + value.substring( value.search( /\n\n\[\[/ ) );
                                        } else {
                                                value += '\n\n' + extraText;
                                        }
                                        
                                        fb.save = ( code === 'mínimo' ) ?
                                                'Página marcada como [[WP:M|mínimo]]' :
                                                'Página marcada como [[WP:EBC|esboço]]';
                                } else if ( $.inArray( code, [ 'subst:VDA' , 'subst:matrad' ] ) > -1 ) {
                                        value = extraText;
                                } else {
                                        value = extraText + '\n' + value;
                                }
                                
                                $textBox.val( value );
                                
                                if ( fb.save ) {
                                        if ( mw.config.get( 'wgNamespaceNumber' ) === 3 ) {
                                                fb.save = 'Adicionando aviso';
                                        } else {
                                                if ( code.indexOf( 'subst:ESR' ) === 0 ) {
                                                        code = 'subst:ESR';
                                                }
                                                
                                                fb.save = summaries[ code ] || 'Adicionando marcação';
                                        }
                                        
                                        $( 'input[name="wpSummary"]' ).val( fb.save + summary );
                                }
                        }
                        
                        // FIXME: It should not submit if in edit mode and (code === 'mínimo' || code.indexOf('esboço') === 0)
                        if ( fb.save ) {
                                $( 'form[name="editform"]' ).submit();
                        }
                break;
        }
};

/* Changes the content of the submenu
 * @param {string} items The new buttons for the new submenu
 */
fb.changeSubmenu = function ( items ) {
        fb.$submenu.empty();
        
        if ( !$.isArray( items ) ) {
                items = [ items ];
        }
        
        for ( var i = 0; i < items.length; i++ ) {
                if ( $.isFunction( items[ i ] ) ) {
                        items[ i ]();
                } else if ( typeof items[ i ] === 'string' ) {
                        fb.$submenu.append( items[ i ] );
                } else {
                        fb.addButton( fb.$submenu, items[ i ] );
                }
        }
        
        fb.$submenu.find( 'a, span' ).tipsy();
};

/* Callback function for API calls
 * @param {string} code An abreviation such as "esb", "PV",
 */
fb.callAPI = function ( code ) {
        var esb, esbText, esbText2, apiParams, callbacks;
        
        apiParams = {
                esb: {
                        list: 'allpages',
                        aplimit: '1',
                        apnamespace: '10'
                },
                
                PV: {
                        list: 'watchlist',
                        wlprop: 'user|comment|title|sizes',
                        wlexcludeuser: mw.config.get( 'wgUserName' )
                },
                
                PN: {
                        list: 'recentchanges',
                        rctype: 'new',
                        rcnamespace: '0',
                        rcshow: '!patrolled',
                        rcprop: 'user|comment|title|sizes|ids'
                },
                
                MR: {
                        list: 'recentchanges',
                        rctype: 'edit',
                        rcnamespace: '0',
                        rcshow: 'anon',
                        rcprop: 'user|comment|title|sizes'
                },
                
                usu: {
                        list: 'allusers',
                        aulimit: '1',
                        auprop: 'editcount|registration',
                        aufrom: mw.config.get( 'wgTitle' ).split( '/' )[ 0 ]
                },
                
                anon: {
                        list: 'usercontribs',
                        uclimit: '500',
                        ucprop: 'timestamp',
                        ucuser: mw.config.get( 'wgTitle' ).split( '/' )[ 0 ]
                }
        },
        
        callbacks = {
                esb: fb.processStubs,
                PV: fb.processRecentEdits,
                PN: fb.processRecentEdits,
                MR: fb.processRecentEdits,
                usu: fb.processUserInfo,
                anon: fb.processUserInfo
        };
        
        if ( 'esb' === code ) {
                esb = $( '#fb-esb-input' ).val();
                
                if ( $.inArray( esb, [ esbText, esbText2 ] ) !== -1 ) {
                        return;
                }
                
                esbText = esb;
                
                if ( esbText === esb.substr( 0, ( esb.length - 1 ) ) ) {
                        return;
                }
                
                apiParams.esb.apprefix = 'Esboço-' + esb;
        }
        
        apiParams[ code ].format = 'json',
        apiParams[ code ].action = 'query';
        
        $.getJSON(
                mw.util.wikiScript( 'api' ),
                apiParams[ code ], function( data ) {
                        if ( !data ){
                                mw.log( 'Não foi possível obter a lista "' + apiParams[ code ].list + '" a partir da API.' );
                                
                                return;
                        }
                        
                        callbacks[ code ]( data, code );
                }
        );
};

/* Callback function for backlinks request
 * @param {Object} data JSON content returned by API
 */
fb.processBackLinks = function( data ) {
        var     info, catLine, backlinks, $hiddenCats, quality,
                query = data.query;
                
        info = '(';
        info += ( document.getElementById( 'Refer.C3.AAncias' )
                        || document.getElementById( 'Notas_e_refer.C3.AAncias' ) ) ?
                                'ref' :
                                '<span class="fb-missing" title="Esta página ainda não possui referências">ref</span>',
        catLine = $( '#mw-normal-catlinks' );
        
        // FIXME: Use the API (instead of 'screen scraping') to get this information!
        if ( catLine.length && catLine.html().indexOf( '><a href="' + mw.config.get( 'wgArticlePath' ).replace( '$1', '' ) ) !== -1 ) {
                info += ' · cat';
        } else {
                info += ' · <span class="fb-missing" title="Esta página ainda não foi categorizada">cat</span>';
        }
        
        info += ( $( '#p-lang' ).length ) ?
                ' · iw' :
                ' · <span class="fb-missing" title="Esta página ainda não' +
                        ' possui links para outros idiomas">iw</span>';

        // Afluentes
        backlinks = query && query.backlinks;
        
        if ( !backlinks ) {
                mw.log( 'The backlinks query returned no data.' );
        } else if ( backlinks.length ) {
                info += ' · <a href="' +
                        mw.util.wikiGetlink( 'Especial:Páginas afluentes/' + mw.config.get( 'wgPageName' ) ) +
                        '" title="afluentes">afl</a>)';
        } else {
                info += ' · <span class="fb-missing" title="Esta página ainda não possui afluentes">afl</span>)';
        }
        
        fb.changeSubmenu( info );
        
        if ( !$( '#ca-talk' ).hasClass( 'new' ) ) {
                $.getJSON(
                        mw.util.wikiScript( 'api' ), {
                                format: 'json',
                                action: 'query',
                                prop: 'categories',
                                indexpageids: '1',
                                titles: mw.config.get( 'wgFormattedNamespaces' )[ mw.config.get( 'wgNamespaceNumber' ) + 1 ] +
                                        ':' + mw.config.get( 'wgTitle' )
                        }, function( data ) {
                                fb.processPageQuality( data );
                        }
                );
        } else {
                $hiddenCats = $( '#mw-hidden-catlinks' );
                
                if ( $hiddenCats.length ) {
                        quality = $hiddenCats.html();
                        
                        if ( quality.indexOf( '!Artigos de qualidade' ) !== -1 ) {
                                quality = quality.substr( quality.indexOf( '!Artigos de qualidade' ) + 22, 1 );
                                
                                if ( quality === 'd' ) {
                                        quality = '?';
                                }
                                
                                fb.$submenu.append(
                                        '<span title="Qualidade do artigo"> Q-<b>' +
                                        quality + '</b></span>'
                                ).find( 'a, span' ).tipsy();
                        }
                }
        }
};

/* Callback function for the request of talk page categories
 * @param {Object} data JSON content returned by API
 */
fb.processPageQuality = function( data ) {
        var     cats, pageids, i, cat, quality,
                query = data.query;
                
        if ( query ) {
                cats = query.pages,
                pageids = query.pageids;
                
                if ( cats && pageids && pageids.length ) {
                        cats = cats[ pageids[0] ].categories;
                        
                        if ( !cats ){
                                mw.log( 'The categories query returned incomplete data.' );
                                
                                return false;
                        }
                } else {
                        mw.log( 'The categories query returned incomplete data.' );
                        
                        return false;
                }
        } else {
                mw.log( 'The categories query returned no data.' );
                
                return false;
        }
        // Qualidade do artigo
        for ( i = 0; i < cats.length; i++ ) {
                cat = cats[ i ].title;
                
                if ( cat && cat.indexOf( '!Artigos de qualidade' ) !== -1 ) {
                        // Categoria:!Artigos de qualidade 1 sobre ...
                        //                                 ^
                        quality = cat.substr( 32, 1 );
                        
                        if ( quality === 'd' ) {
                                quality = '?';
                        }
                        
                        fb.$submenu.append(
                                '<span title="Qualidade do artigo"> Q-<b>' +
                                        quality + '</b></span>'
                        ).find( 'a, span' ).tipsy();
                        
                        break;
                }
        }
};

/* Callback function for the request of stub templates
 * @param {Object} data JSON content returned by API
 */
fb.processStubs = function( data ) {
        var     template, start, sel, esbText2
                esb = document.getElementById( 'fb-esb-input' ),
                query = data.query;
                
        if ( query ) {
                template = query.allpages && query.allpages[ 0 ] && query.allpages[ 0 ].title;
                
                if ( !template ) {
                        mw.log( 'The categories query returned incomplete data.' );
                        
                        return false;
                }
                
                template = template.replace( /^Predefinição:Esboço-/gi, '' );
        } else {
                mw.log( 'The categories query returned no data.' );
                
                return false;
        }
        if ( ( esb.setSelectionRange
                        || esb.createTextRange
                        || ( typeof esb.selectionStart !== 'undefined'
                                && typeof esb.selectionEnd !== 'undefined'
                        )
                ) && esb.value === template.substr( 0, esb.value.length )
        ) {
                // Exibe sugestões. Baseado no script do HotCat
                start = esb.value.length,
                esb.value = template,
                esbText2 = template;
                
                if ( esb.setSelectionRange ) {
                        esb.setSelectionRange( start, template.length );
                } else if ( esb.createTextRange ) {
                        sel = esb.createTextRange();
                        sel.move( 'character', start );
                        sel.moveEnd( 'character', template.length - start );
                        sel.select();
                } else {
                        esb.selectionStart = start;
                        esb.selectionEnd = template.length;
                }
        }
};

/* Callback function for the request of recent edits (from watchlist or recent changes)
 * @param {Object} data JSON content returned by API
 */
fb.processRecentEdits = function(data, code) {
        var     listName, summaryChanges, urlParam, list, max, i,
                item, title, length, comment, j,
                pages = [],
                charnum = 0,
                query = data.query;

        listName = {
                PV: 'watchlist',
                MR: 'recentchanges',
                PN: 'recentchanges'
        },
        
        summaryChanges = {
                PV: [
                        [ '[[Ajuda:SEA|?]]', '' ],
                        [ '/*', '?' ],
                        [ '*/', ':' ]
                ],
                
                MR: [
                        [ '/*', '?' ],
                        [ '*/', ':' ]
                ],
                
                PN: [
                        [ '[[Ajuda:SEA|?]] ', '' ]
                ]
        },
        
        urlParam = {
                PV: 'diff=last',
                MR: 'diff=last',
                PN: 'redirect=no&rcid='
        };
        
        list = query[ listName[ code ] ],
        max = ( list.length < 10 )? list.length : 10;

        for ( i = 0; i < max; i++ ) {
                item = list[ i ];
                
                if ( !item ){
                        continue;
                }
                
                title = item.title;
                charnum += title.length;
                
                if ( charnum > 180 ) {
                        break;
                }
                
                length = item.newlen - item.oldlen;
                
                if ( length > 0 ) {
                        length = '+' + length;
                }
                
                comment = item.comment || '';
                
                for ( j = 0; j < summaryChanges[ code ].length; j++ ) {
                        comment = comment.replace(
                                summaryChanges[ code ][ 0 ],
                                summaryChanges[ code ][ 1 ]
                        );
                }
                
                if ( comment ) {
                        comment = '(' + comment + ')';
                }
                
                if ( code === 'PN' ){
                        urlParam[ code ] += item.rcid;
                }
                
                pages.push(
                        '<a href="' + mw.util.wikiGetlink( title ) + '?' +
                        urlParam[ code ] + '" title="(' + length + ') ' + item.user +
                        ' ' + comment + '">' + title + '</a>'
                );
        }
        
        fb.changeSubmenu( '<div class="horizontal">' + pages.join( ' ' ) + '</div>' );
};

/* Callback function for the request of user info
 * @param {Object} data JSON content returned by API
 */
fb.processUserInfo = function( data, code ) {
        var     contribs, regDate, encUser,
                user = {},
                query = data.query;

        // Informações do(a) usuário(a)
        if ( !query ) {
                mw.log( 'The categories query returned no data.' );
                
                return false;
        }
        
        if ( code === 'anon' ) {
                if ( !query.usercontribs ) {
                        return;
                }
                
                contribs = query.usercontribs,
                user.name = contribs[ 0 ].user,
                user.editcount = contribs.length,
                user.registration = contribs[ contribs.length - 1 ].timestamp;
                
                if ( data[ 'query-continue' ] ) {
                        user.editcount = 'mais de ' + user.editcount;
                        user.registration = 'antes de ' + user.registration;
                }
        } else {
                user = query.allusers && query.allusers[ 0 ];
        }
        
        if ( user ) {
                // Ex.: YYYY-MM-DDThh:mm:ssZ
                regDate = user.registration,
                regDate = regDate.substr( 8, 2 ) + '/' + regDate.substr( 5, 2 ) +
                        '/' + regDate.substr( 0, 4 ),
                encUser = encodeURI( user.name );
                
                //FIXME: Simplify this!
                fb.changeSubmenu( [
                                user.editcount + ' edições desde ' + regDate + '.',
                                '<a class="fb-button" href="' +
                                        mw.util.wikiGetlink( 'Especial:Contribuições/' ) + encUser +
                                        '" title="Abrir a lista de contribuições deste editor" >contribuições</a>',
                                '<a class="fb-button" href="' +
                                        mw.util.wikiGetlink( 'Especial:Registo/' ) + encUser +
                                        '" title="Abrir a lista de registros deste editor" >registros</a>',
                                '<a class="fb-button" href="' +
                                        mw.util.wikiGetlink( 'Especial:Registo' ) + '?type=block&page=User%3A' + encUser +
                                        '" title="Abrir a lista de registros de bloqueio deste editor">registros de bloqueio</a>',
                                '<span class="plainlinks"><a class="external text fb-button"' +
                                        'title="Abrir a contagem de edições deste editor"' +
                                        ' href="//toolserver.org/~river/cgi-bin/count_edits?user=' +
                                        encUser + '&dbname=' + mw.config.get('wgDBname') + '_p">contador de edições</a></span>'
                        ].join( ' ' )
                );
        } else {
                return;
        }
};

fb.nicePrompt = function ( title, label, callback ) {
        if ( !label ) {
				label = 'Observação';
		}
		
		var twoQuestions = label.search( '/|2=' ), $dialog = $( '<div id="nprompt-dialog" class="ui-widget" />');
        
        if ( twoQuestions !== -1 ) {
                $dialog.append(
                        '<label for="nprompt-input1">' + label.substring( 0, twoQuestions - 1 ) + '</label>'
                        + '<input type="text" id="nprompt-input1"> </input> <label for="nprompt-input2">' + label.substring( twoQuestions + 2 ) + '</label>'
                        + '<input type="text" id="nprompt-input2"> </input>'
                );
        } else {
                $dialog.append( '<label for="nprompt-input">' + label + '</label>' + '<input type="text" id="nprompt-input"> </input>');
        }
        
        $dialog.dialog({
                title: title,
                open: function () {
                        $( '.ui-dialog-titlebar-close' ).hide();
                },
                close: function () {
                        $( '#nprompt-dialog' ).dialog( 'destroy' );
                        $( '#nprompt-dialog' ).remove();
                },
                buttons: {
                    'OK': function () {
                            var answer;
                            
                            if ( twoQuestions === -1 ) {
                                    callback( $('#nprompt-input').val() );
                            } else {
                                    answer = ( $( '#nprompt-input1' ).val() + '|2=' + $( '#nprompt-input2' ).val() );
                                    callback( answer );
                            }
                            
                            $( this ).dialog( 'close' );
                    },
                    
                    'Cancelar': function() {
                            $( this ).dialog( 'close' );
                    }
                }         
        });
};

fb.useDialog = function( title, message, id ) {
    $( '#' + id ).empty()
            .dialog( 'option', 'title', title)
            .append( $( '<div>' + message + '</div>' ) )
            .dialog( 'option', 'buttons', {
                    'Fechar': function() {
                            $( this ).dialog( 'close' );
                    }
            });
};

/* Initialize the gadget */
fb.init = function () {
        var     inUserNS, basePageName,
                param = mw.util.getParamValue( 'fastb' );
                
        if ( $.inArray( mw.config.get( 'wgAction' ), [ 'view', 'edit' ] ) !== -1 ) {
                // FIXME: Is this still necessary? maybe fb.$submenu.empty()?
                fb.changeSubmenu( '' );
                
                /*** Menu Principal ***/
                if ( mw.config.get( 'wgNamespaceNumber' ) !== -1 ) {
                        inUserNS = $.inArray( mw.config.get( 'wgNamespaceNumber' ), [ 2, 3 ] ) !== -1
                                && mw.config.get( 'wgTitle' ).indexOf( mw.config.get( 'wgUserName' ) ) === 0;
                                
                        fb.$menu.empty();
                        
                        if ( inUserNS ) {
                                fb.addButton({
                                        action: 'ER|1',
                                        text: 'ER1',
                                        title: 'Marcar subpágina do próprio usuário para eliminação'
                                });
                        } else {
                                fb.addButton({
                                        action: function() {
                                                fb.changeSubmenu(fb.submenu.ER);
                                        },
                                        text: 'ER',
                                        title: 'Exibir regras para a eliminação rápida'
                                });
                        }
                }
                
                if ( $.inArray( mw.config.get( 'wgNamespaceNumber' ), [ 0, 102 ] ) !== -1 ) {
                        fb.addButton([ {
                                        action: function(){
                                                fb.changeSubmenu(fb.submenu.ESR);
                                        },
                                        text: 'ESR',
                                        title: 'Exibir regras para a eliminação semi-rápida'
                                }, {
                                        action: 'subst:apagar',
                                        text: 'PE',
                                        title: 'Marcar para eliminação por votação'
                                }, {
                                        action: function(){
                                                fb.nicePrompt(
                                                        'Informe o url da página copiada',
                                                        'Url :', function (obs) { fb.run('subst:VDA', obs);}
                                                );
                                        },
                                        text: 'VDA',
                                        title: 'Marcar como cópia ou violação de direito autoral'
                                }, {
                                        action: 'subst:suspeito',
                                        text: 'susp',
                                        title: 'Marcar como suspeito de violação de direitos autorais'
                                }, {
                                        action: 'subst:matrad',
                                        text: 'trad',
                                        title: 'Marcar esta tradução como sendo de baixa qualidade',
                                        prompt: 'De qual língua a página foi maltraduzida (ca, de, en, es,' +
                                                ' fr, it, ja, nl, no, pl, ru, sv, zh)?',
                                        label: 'Página:'
                                }, {
                                        action: 'redirect',
                                        text: '#R',
                                        title: 'Redirecionar para outro título',
                                        prompt: 'Redirecionar para qual página?',
                                        label: 'Página:'
                                }, {
                                        action: function(){
                                                fb.changeSubmenu(fb.submenu.man);
                                        },
                                        text: 'manutenção',
                                        title: 'Exibir predefinições para manutenção'
                                }, {
                                        action: function(){
                                                fb.changeSubmenu(fb.submenu.esb);
                                        },
                                        text: 'esboço',
                                        title: 'Exibir predefinições para esboços'
                                }, {
                                        action: function(){
                                                fb.changeSubmenu(fb.submenu.search);
                                        },
                                        text: 'busca',
                                        title: 'Exibir opções para a busca de fontes'
                                }
                        ] );
                        
                        if ( mw.config.get( 'wgAction' ) === 'view' ) {
                                $.getJSON(
                                        mw.util.wikiScript( 'api' ), {
                                                format: 'json',
                                                action: 'query',
                                                list: 'backlinks',
                                                bllimit: '1',
                                                blfilterredir: 'nonredirects',
                                                blnamespace: '0',
                                                bltitle: mw.config.get('wgPageName')
                                        },
                                        
                                        fb.processBackLinks
                                );
                        }
                } else {
                        if ( $.inArray( mw.config.get( 'wgNamespaceNumber' ), [ 2, 10 ] ) !== -1 ) {
                                fb.addButton({
                                        action: 'subst:apagar',
                                        text: 'PE',
                                        title: 'Marcar para eliminação por votação'
                                });
                        }
                        
                        if ( mw.config.get( 'wgNamespaceNumber' ) % 2 === 0 ) {
                                fb.addButton({
                                        action: 'redirect',
                                        text: '#R',
                                        title: 'Redirecionar para outro título',
                                        prompt: 'Redirecionar para qual página?',
                                        label: 'Página:'
                                });
                        }
                        
                        if ( mw.config.get( 'wgNamespaceNumber' ) === 14 ) {
                                fb.addButton({
                                        action: function() {
                                                fb.changeSubmenu( fb.submenu.cat );
                                        },
                                        text: 'CatScan',
                                        title: 'Exibir opções do CatScan para procurar páginas nesta categoria'
                                });
                        }
                }
                
                if ( mw.config.get( 'wgNamespaceNumber' ) === 3 ) {
                        fb.addButton({
                                action: function() {
                                        fb.changeSubmenu( fb.submenu.warn );
                                },
                                text: 'aviso',
                                title: 'Exibir lista de predefinições para avisos'
                        });
                }
                
                if ( $.inArray( mw.config.get( 'wgNamespaceNumber' ), [ 2, 3 ] ) !== -1 ) {
                        basePageName = mw.config.get( 'wgTitle' ).split( '/' )[ 0 ];
                        
                        if ( mw.util.isIPv4Address( basePageName ) || mw.util.isIPv6Address( basePageName ) ) {
                                fb.addButton({
                                        action: function(){
                                                fb.callAPI('anon');
                                        },
                                        text: 'sobre o IP',
                                        title: 'Exibir informações sobre este IP'
                                });
                        } else {
                                fb.addButton({
                                        action: function(){
                                                fb.callAPI( 'usu' );
                                        },
                                        text: 'sobre a conta',
                                        title: 'Exibir informações sobre esta conta'
                                });
                        }

                }
        }
        
        fb.addButton([ {
                        action: function(){
                                fb.callAPI('PV');
                        },
                        text: 'PV',
                        title: 'Exibir páginas vigiadas que foram alteradas recentemente'
                }, {
                        action: function(){
                                fb.callAPI('PN');
                        },
                        text: 'PN',
                        title: 'Exibir páginas novas que ainda não foram patrulhadas'
                }, {
                        action: function(){
                                fb.callAPI('MR');
                        },
                        text: 'MR',
                        title: 'Exibir mudanças recentes feitas por IPs em páginas do domínio principal'
                }
        ]);
        
        if ( mw.config.get( 'skin' ) === 'modern' ) {
                $( '#contentSub' ).before( fb.$menu ).before( fb.$submenu );
        } else {
                $( 'h1' ).first().after( fb.$submenu ).after( fb.$menu );
        }

        switch ( mw.config.get( 'wgAction' ) ) {
                case 'edit':
                        // FIXME: Use API to edit, because pseudo actions may be dangerous
                        // (see [[commons:Commons:Administrators' noticeboard/Archive 34#MediaWiki:Gadget-autodel.js]])
                        fb.save = ( param !== null );
                        
                        if ( fb.save ) {
                                fb.run( param, mw.util.getParamValue( 'fbtxt' ) || '' );
                        }
                        
                break;
                
                case 'markpatrolled':
                        // FIXME: Use API to patrol, because pseudo actions may be dangerous (see above)
                        if ( param !== null ) {
                                location.href = mw.util.wikiGetlink( mw.config.get( 'wgPageName' ) ) +
                                        '?action=edit&fastb=' + param;
                        }
                break;
                
                default:
                        // Não faz nada nas demais ações
        }
        
        fb.$menu.find( 'a' ).tipsy();
};

/* Executes the gadget when document is ready */
window.fb = fb;

mw.loader.using( 'jquery.tipsy', function() {
        $( fb.init );
} );

}( jQuery, mediaWiki ) );