MediaWiki:Common.js: mudanças entre as edições

De Clube Atletico Mineiro - Enciclopedia Galo Digital
Ir para navegação Ir para pesquisar
(outro teste)
Sem resumo de edição
Linha 1 094: Linha 1 094:
   }
   }
}
}
importScript('MediaWiki:Common.js/HotCat.js')


//</source>
//</source>

Edição das 23h54min de 13 de agosto de 2010

//<source lang="javascript">
/* Todo código JavaScript presente aqui será carregado por todos os usuários em cada página carregada. */

 /** Importar scripts específicos se for necessário ******************************************/

if (wgAction == "edit" || wgAction == "submit") //scripts específicos para editar páginas
{
    importScript("MediaWiki:Common.js/edit.js")
}
else if ( wgCanonicalSpecialPageName == "Search" ||wgPageName == "Special:Search" || wgPageName == "Special:Busca" || wgPageName == "Especial:Search"  || wgPageName == "Especial:Busca" ) //scripts específicos para Especial:Busca
{
    importScript("MediaWiki:Common.js/search.js")
}

if (navigator.appName == "Microsoft Internet Explorer") //scripts específicos para Internet Explorer
{
    importScript("MediaWiki:Common.js/IEFixes.js")
}


 /** Importar módulos JavaScript de páginas da fr.wikipedia.org ******************************
  * Obs: Importar os demais scripts utilizados da página francesa e utilizar o
  * importScript() acima, que opossui a mesma função.
  ********************************************************************************************/
 function loadJs(page)
 {
  document.write('<script type="text/javascript" src="' +
                'http://fr.wikipedia.org/w/index.php?title=' + page +
                '&action=raw&ctype=text/javascript&dontcountme=s"></script>');
 }


 /** Link destaque ***************************************************************************
  *  Descrição: Adiciona estrela ao lado da ligação dos artigos destacados das outras Wikipédias
  ********************************************************************************************/
function LinkFA() 
 {
     if ( document.getElementById( "p-lang" ) ) {
         var InterwikiLinks = document.getElementById( "p-lang" ).getElementsByTagName( "li" );
 
         for ( var i = 0; i < InterwikiLinks.length; i++ ) {
             if ( document.getElementById( InterwikiLinks[i].className + "-fa" ) ) {
                 InterwikiLinks[i].className += " FA"
                 InterwikiLinks[i].title = "Este artigo recebeu estatuto de destaque.";
             }
         }
     }
 }
 
 addOnloadHook( LinkFA );
/** Link bom ***************************************************************************
  *  Descrição: Adiciona estrela prateada ao lado da ligação dos artigos bons das outras Wikipédias
  ********************************************************************************************/
function Bominterwiki() 
 {
     if ( document.getElementById( "p-lang" ) ) {
         var InterwikiLinks = document.getElementById( "p-lang" ).getElementsByTagName( "li" );
 
         for ( var i = 0; i < InterwikiLinks.length; i++ ) {
             if ( document.getElementById( InterwikiLinks[i].className + "-bom" ) ) {
                 InterwikiLinks[i].className += " BOM"
                 InterwikiLinks[i].title = "Este artigo recebeu estatuto de bom.";
             }
         }
     }
 }
 
 addOnloadHook( Bominterwiki );


 
 /** Correlatos ******************************************************************************
  *  Descrição:Correlatos no menu lateral. Código copiado do de:wikt
  ********************************************************************************************/
 // InterProjekt-Links (vgl. [[MediaZilla:708]])
  document.write('<style type="text/css">#interProject, #sisterProjects {display: none; speak: none;} #p-tb .pBody {padding-right: 0;}<\/style>');
 function iProject() {
  if (document.getElementById("interProject")) {
   var iProject = document.getElementById("interProject").innerHTML;
   var interProject = document.createElement("div");
   interProject.style.marginTop = "0.7em";
   interProject.innerHTML = '<h5>Correlatos<\/h5><div class="pBody body">'+iProject+'<\/div>';
   document.getElementById("p-tb").appendChild(interProject);
  }
 }
 addOnloadHook(iProject);
 


 /** Altera o título da página **************************************************************
  *    Origem: [[:w:en:MediaWiki:Common.js]]
  * Descrição: A função procura por um banner como:
  * <nowiki><div id="RealTitleBanner">Div that is hidden</nowiki>
  *   <nowiki><span id="RealTitle">title</span></nowiki>
  * <nowiki></div></nowiki>
  * An element with id=DisableRealTitle disables the function.
  ********************************************************************************************/

 rewritePageH1 = function() {
    try {
        var realTitleBanner = document.getElementById("RealTitleBanner");
        if (realTitleBanner) {
            if (!document.getElementById("DisableRealTitle")) {
                var realTitle = document.getElementById("RealTitle");
                var h1 = document.getElementsByTagName("h1")[0];
                if (realTitle && h1) {
                    h1.innerHTML = realTitle.innerHTML;
                    realTitleBanner.style.display = "none";
                }
            }
        }
    } 
 catch (e) {
    /* Algo deu errado. */
    }
 }
 addOnloadHook(rewritePageH1);


 /** Wiki Mini Atlas ************************************************************************
  *  Descrição: Mini atlas para artigos com geocoodernadas.
  *      Autor: [[en:User:Dschwen]]
  ********************************************************************************************/

if (wgServer == "https://secure.wikimedia.org") {
  var metaBase = "https://secure.wikimedia.org/wikipedia/meta";
} else {
  var metaBase = "http://meta.wikimedia.org";
}
importScriptURI(metaBase+"/w/index.php?title=MediaWiki:Wikiminiatlas.js&action=raw&ctype=text/javascript&smaxage=21600&maxage=86400")


/** Mobile Redirect Helper ************************************************
 *
 *  Redirecionana para o gateway optimizado para sistemas móveis em pt.m.wikipedia.org
 *  para visualizadores em iPhone, iPod Touch, Palm Pre, e Android.
 *
 *  Você pode desativar o redirecionamento setando o cookie "stopMobileRedirect=true"
 *
 *  Mantenedores: [[en:User:Brion VIBBER]], [[en:User:hcatlin]]
 */
if (/(Android|iPhone|iPod|webOS|NetFront|Opera Mini|SEMC-Browser|PlayStation Portable|Nintendo Wii)/.test(navigator.userAgent)) {

  var wgMainPageName = 'Página_principal';
 
  var stopMobileRedirectCookieExists = function() {
    return (document.cookie.indexOf("stopMobileRedirect=true") >= 0);
  }
 
  var mobileSiteLink = function() {
    if ( (wgCanonicalNamespace == 'Special' || wgCanonicalNamespace == 'Especial') && (wgCanonicalSpecialPageName == 'Search' || wgCanonicalSpecialPageName == 'Busca') ) {
        var pageLink = '?search=' + encodeURIComponent(document.getElementById('searchText').value);
    } else if (wgPageName == wgMainPageName) {
        var pageLink = '::Home'; // Special case
    } else {
        var pageLink = encodeURIComponent(wgPageName).replace('%2F','/').replace('%3A',':');
    }
    return 'http://' + wgContentLanguage + '.m.wikipedia.org/wiki/' + pageLink + "?wasRedirected=true"
  }
 
  if (!stopMobileRedirectCookieExists()) {
    document.location = mobileSiteLink();
  }
}


 /** Collapsible tables *********************************************************
  *
  *  Description: Allows tables to be collapsed, showing only the header. See
  *               [[Wikipedia:NavFrame]].
  *  Maintainers: [[User:R. Koot]]
  */


 var autoCollapse = 2;
 var collapseCaption = "Esconder";
 var expandCaption = "Expandir";
 
 function collapseTable( tableIndex )
 {
     var Button = document.getElementById( "collapseButton" + tableIndex );
     var Table = document.getElementById( "collapsibleTable" + tableIndex );
 
     if ( !Table || !Button ) {
         return false;
     }
 
     var Rows = Table.rows;
 
     if ( Button.firstChild.data == collapseCaption ) {
         for ( var i = 1; i < Rows.length; i++ ) {
             Rows[i].style.display = "none";
         }
         Button.firstChild.data = expandCaption;
     } else {
         for ( var i = 1; i < Rows.length; i++ ) {
             Rows[i].style.display = Rows[0].style.display;
         }
         Button.firstChild.data = collapseCaption;
     }
 }
 
 function createCollapseButtons()
 {
     var tableIndex = 0;
     var NavigationBoxes = new Object();
     var Tables = document.getElementsByTagName( "table" );
 
     for ( var i = 0; i < Tables.length; i++ ) {
         if ( hasClass( Tables[i], "collapsible" ) ) {
 
             /* only add button and increment count if there is a header row to work with */
             var HeaderRow = Tables[i].getElementsByTagName( "tr" )[0];
             if (!HeaderRow) continue;
             var Header = HeaderRow.getElementsByTagName( "th" )[0];
             if (!Header) continue;
 
             NavigationBoxes[ tableIndex ] = Tables[i];
             Tables[i].setAttribute( "id", "collapsibleTable" + tableIndex );
 
             var Button     = document.createElement( "span" );
             var ButtonLink = document.createElement( "a" );
             var ButtonText = document.createTextNode( collapseCaption );
 
             Button.style.styleFloat = "right";
             Button.style.cssFloat = "right";
             Button.style.fontWeight = "normal";
             Button.style.textAlign = "right";
             Button.style.width = "6em";
 
             ButtonLink.style.color = Header.style.color;
             ButtonLink.setAttribute( "id", "collapseButton" + tableIndex );
             ButtonLink.setAttribute( "href", "javascript:collapseTable(" + tableIndex + ");" );
             ButtonLink.appendChild( ButtonText );
 
             Button.appendChild( document.createTextNode( "[" ) );
             Button.appendChild( ButtonLink );
             Button.appendChild( document.createTextNode( "]" ) );
 
             Header.insertBefore( Button, Header.childNodes[0] );
             tableIndex++;
         }
     }
 
     for ( var i = 0;  i < tableIndex; i++ ) {
         if ( hasClass( NavigationBoxes[i], "collapsed" ) || ( tableIndex >= autoCollapse && hasClass( NavigationBoxes[i], "autocollapse" ) ) ) {
             collapseTable( i );
         }
     }
 }
 
 addOnloadHook( createCollapseButtons );
 
 /** Dynamic Navigation Bars (experimental) *************************************
  *
  *  Description: See [[Wikipedia:NavFrame]].
  *  Maintainers: UNMAINTAINED
  */
 
  // set up the words in your language
  var NavigationBarHide = '[' + collapseCaption + ']';
  var NavigationBarShow = '[' + expandCaption + ']';
 
  // shows and hides content and picture (if available) of navigation bars
  // Parameters:
  //     indexNavigationBar: the index of navigation bar to be toggled
  function toggleNavigationBar(indexNavigationBar)
  {
     var NavToggle = document.getElementById("NavToggle" + indexNavigationBar);
     var NavFrame = document.getElementById("NavFrame" + indexNavigationBar);
 
     if (!NavFrame || !NavToggle) {
         return false;
     }
 
     // if shown now
     if (NavToggle.firstChild.data == NavigationBarHide) {
         for (
                 var NavChild = NavFrame.firstChild;
                 NavChild != null;
                 NavChild = NavChild.nextSibling
             ) {
             if ( hasClass( NavChild, 'NavPic' ) ) {
                 NavChild.style.display = 'none';
             }
             if ( hasClass( NavChild, 'NavContent') ) {
                 NavChild.style.display = 'none';
             }
         }
     NavToggle.firstChild.data = NavigationBarShow;
 
     // if hidden now
     } else if (NavToggle.firstChild.data == NavigationBarShow) {
         for (
                 var NavChild = NavFrame.firstChild;
                 NavChild != null;
                 NavChild = NavChild.nextSibling
             ) {
             if (hasClass(NavChild, 'NavPic')) {
                 NavChild.style.display = 'block';
             }
             if (hasClass(NavChild, 'NavContent')) {
                 NavChild.style.display = 'block';
             }
         }
     NavToggle.firstChild.data = NavigationBarHide;
     }
  }
 
  // adds show/hide-button to navigation bars
  function createNavigationBarToggleButton()
  {
     var indexNavigationBar = 0;
     // iterate over all < div >-elements 
     var divs = document.getElementsByTagName("div");
     for(
             var i=0; 
             NavFrame = divs[i]; 
             i++
         ) {
         // if found a navigation bar
         if (hasClass(NavFrame, "NavFrame")) {
 
             indexNavigationBar++;
             var NavToggle = document.createElement("a");
             NavToggle.className = 'NavToggle';
             NavToggle.setAttribute('id', 'NavToggle' + indexNavigationBar);
             NavToggle.setAttribute('href', 'javascript:toggleNavigationBar(' + indexNavigationBar + ');');
 
             var NavToggleText = document.createTextNode(NavigationBarHide);
             for (
                  var NavChild = NavFrame.firstChild;
                  NavChild != null;
                  NavChild = NavChild.nextSibling
                 ) {
                 if ( hasClass( NavChild, 'NavPic' ) || hasClass( NavChild, 'NavContent' ) ) {
                     if (NavChild.style.display == 'none') {
                         NavToggleText = document.createTextNode(NavigationBarShow);
                         break;
                     }
                 }
             }
 
             NavToggle.appendChild(NavToggleText);
             // Find the NavHead and attach the toggle link (Must be this complicated because Moz's firstChild handling is borked)
             for(
               var j=0; 
               j < NavFrame.childNodes.length; 
               j++
             ) {
               if (hasClass(NavFrame.childNodes[j], "NavHead")) {
                 NavFrame.childNodes[j].appendChild(NavToggle);
               }
             }
             NavFrame.setAttribute('id', 'NavFrame' + indexNavigationBar);
         }
     }
  }
 
  addOnloadHook( createNavigationBarToggleButton );


 /* Test if an element has a certain class **************************************
  *
  * Description: Uses regular expressions and caching for better performance.
  * Maintainers: [[User:Mike Dillon]], [[User:R. Koot]], [[User:SG]]
  */
 
 var hasClass = (function () {
     var reCache = {};
     return function (element, className) {
         return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className);
     };
 })();






 /** Caixa com abas - [[Predefinição:Metacaixa]] *********************************************
  *    Origem: [[:w:fr:MediaWiki:Common.js]] (traduzido de [[:w:ca:MediaWiki:Common.js]])
  * Descrição: Ver [[Predefinição:Metacaixa]]
  *     Autor: [[:w:ca:User:Peleguer]], [[:w:ca:User:Joanjoc]], [[:w:fr:User:Antaya]] (adaptação), [[:w:pt:Rei-artur]] (adaptação)
  ********************************************************************************************/
function CadreOngletInit(){
 // retour si ailleurs que sur l'espace utilisateur, 
 // sachant que c'est une horreur au niveau de l'accessibilité
 // et qu'il est impossible de "récupérer" ou de recycler ce script
 // (celui-ci fonctionnant par inclusion de sous pages)
 if ( wgNamespaceNumber == 0 || wgNamespaceNumber == 102 ) return;  
  var i=0       
  for (i=0;i<=9;i++){
     var vMb = document.getElementById("mb"+i);
     if (!vMb) break;
 
     var j=1    
     var vOgIni = 0  
     for (j=1;j<=9;j++){
        var vBt = document.getElementById("mb"+i+"bt"+j);
        if (!vBt) break;
        vBt.onclick = CadreOngletVoirOnglet;          
        if (vBt.className=="mbBoutonSel") vOgIni=j;  
     }
 
     if (vOgIni == 0) { 
         vOgIni = 1+Math.floor((j-1)*Math.random()) ;
         document.getElementById("mb"+i+"og"+vOgIni).style.display = "block";
         document.getElementById("mb"+i+"og"+vOgIni).style.visibility = "visible";
         document.getElementById("mb"+i+"bt"+vOgIni).className="mbBoutonSel";
     } 
  }
 }
 
 function CadreOngletVoirOnglet(){
  var vMbNom = this.id.substr(0,3); 
  var vIndex = this.id.substr(5,1); 
 
  var i=1
  for (i=1;i<=9;i++){        
        var vOgElem = document.getElementById(vMbNom+"og"+i);
        if (!vOgElem) break;
        if (vIndex==i){ 
                vOgElem.style.display = "block";
                vOgElem.style.visibility = "visible";
                document.getElementById(vMbNom+"bt"+i).className="mbBoutonSel";
        } else {             
                vOgElem.style.display = "none";
                vOgElem.style.visibility = "hidden";
                document.getElementById(vMbNom+"bt"+i).className="mbBouton";
        }
  }
  return false; 
 }
 
 addOnloadHook(CadreOngletInit);

/* CÓDIGO JAVASCRIPT DE "METACAIXA" */



 /** ***************************************************************************
  *  Descrição: Adiciona a predefinição {protegido} e {protegido-ip} automáticos para artigos protegidos
  *  Autor: [[:pt:User:Rei-artur]]
  ******************************************************************************/
 importScript('MediaWiki:Topicon.js')


/** Banners para dicas e doações vista apenas por anônimos **************************
    *  Descrição: Frases aleatórias que podem ser vistas por anônimos the bug:
    *  Autores: [[:en:User:Gmaxwell]], [[:en:User:MZMcBride]]
  ******************************************************************************/
 importScript('MediaWiki:WikiBanners.js')


/*
 * Descrição: Manter no servidor seguro quem se loga pelo servidor seguro quando muda para outro projeto
 *            Sem este código, o usuário logado por https quando segue um interwiki, usa http e será deslogado (os logins são independentes).
 */
if(wgServer == 'https://secure.wikimedia.org') {
    importScript( 'MediaWiki:Common.js/secure.js');
}

var hotcat_running = 0 ;
var hotcat_last_v = "" ;
var hotcat_exists_yes = "http://upload.wikimedia.org/wikipedia/commons/thumb/b/be/P_yes.svg/20px-P_yes.svg.png" ;
var hotcat_exists_no = "http://upload.wikimedia.org/wikipedia/commons/thumb/4/42/P_no.svg/20px-P_no.svg.png" ;

var hotcat_no_autocommit = 0;
// In Commons hotcat_suggestion_delay is configurable trough JSconfig
var hotcat_suggestion_delay = 100;

var hotcat_old_onsubmit = null;
var hotcat_nosuggestions = false;
// hotcat_nosuggestions is set to true if we don't have XMLHttp! (On IE6, XMLHttp uses
// ActiveX, and the user may deny execution.) If true, no suggestions will ever be
// displayed, and there won't be any checking whether the category  exists.
// Lupo, 2008-01-20

var hotcat_modify_blacklist = new Array (
""
) ;

addOnloadHook ( hotcat ) ;

function hotcat () {
  if ( hotcat_check_action() ) return ; // Edited page, reloading anyway

  // Não adicionar a interface páginas protegidas, se o usuário não tem permissão editar
  // Também desativá-lo em preview páginas: por um preview, *já* estamos a ediar,
  // HotCat e não deve abrir a página para a edição de uma segunda vez. Lupo, 2008-02-27
  if( wgAction != "view" || document.getElementById('ca-viewsource' ) != null ||
      wgNamespaceNumber == -1 )
    return;

  // If we have no Categories div, then add one
  // TheDJ, 2008-02-28
  
  var visible_catlinks = document.getElementById ('mw-normal-catlinks') || getElementsByClassName ( document , "p" , "catlinks" ) [0];
  var hidden_catlinks = document.getElementById ('mw-hidden-catlinks');

  if ( visible_catlinks == null || typeof( visible_catlinks ) == 'undefined' ) {
    d3 = document.createElement ( "div" );
    d3.id = "mw-normal-catlinks";
    d3.innerHTML = '<a href="/wiki/Especial:Categorias" title="Especial:Categorias">Categorias</a>: ';
    visible_catlinks = d3;

    if ( hidden_catlinks ) {
      // Não há categorias ocultas.
      hidden_catlinks.parentNode.insertBefore( d3, hidden_catlinks );
      hidden_catlinks.parentNode.className = "catlinks";
    } else {
      // Esta página não tem em todas as categorias, permite criar uma secção onde podemos adicioná-las.
      var footer = getElementsByClassName ( document , "div" , "printfooter" ) [0];
      if( !footer ) return; // Não temos nenhuma ideia que temos, pois, adicione essa.

      d1 = document.createElement ( "div" );
      d1.id = "catlinks";
      d1.className = "catlinks";
      d1.appendChild ( d3 );
      footer.parentNode.insertBefore( d1, footer.nextSibling );
    } 
  }

  hotcat_modify_existing ( visible_catlinks ) ;
  hotcat_append_add_span ( visible_catlinks ) ;
}

function hotcat_append_add_span ( catline ) {
  // Se estiver no namespace Predefinição, desativar a opção de adicionar "(+)"
  if ( wgNamespaceNumber == 10 ) return ;
  var span_add = document.createElement ( "span" ) ;
  var span_sep = document.createTextNode ( " | " ) ;
  if ( catline.getElementsByTagName("span")[0] ) catline.appendChild ( span_sep ) ;
  catline.appendChild ( span_add ) ;
  hotcat_create_span ( span_add ) ;
}

String.prototype.ucFirst = function () {
   return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
}

function hotcat_is_on_blacklist ( cat_title ) {
  if ( !cat_title ) return 0 ;
  cat_title = cat_title.ucFirst.replace( /Category:/gi, "" );
  for ( var i = 0 ; i < hotcat_modify_blacklist.length ; i++ ) {
    if ( cat_title.substr ( 0 , hotcat_modify_blacklist[i].length ) == hotcat_modify_blacklist[i] ) return 1 ;
  }
  return 0 ;
}

function hotcat_modify_span ( span , i ) {
  //var cat_title = span.firstChild.getAttribute ( "title" ) ;
  // Esta falha em MW 1.13alpha se a categoria é um link vermelho, porque anexa à MW 1.13alpha
  // [[MediaWiki:Red-link-title]] para o nome da categoria ... temos outra forma de obter essa categoria
  // name. Lupo, 2008-02-27
  var cat_title = span.firstChild.innerHTML; // without "Categoria:"
 
  var sep1 = document.createTextNode ( " " ) ;
  var a1 = document.createTextNode ( "(-)" ) ;
  var remove_link = document.createElement ( "a" ) ;
  // Set the href to a dummy value to make sure we don't move if somehow the onclick handler
  // is bypassed.
  remove_link.href = "#catlinks";
  remove_link.onclick = hotcat_remove;
  remove_link.appendChild ( a1 ) ;
  span.appendChild ( sep1 ) ;
  span.appendChild ( remove_link ) ;
 
  // Se estiver no namespace Predefinição, desativar a opção de alterar "(±)"
  if ( wgNamespaceNumber == 10 ) return ;
 
  // Disabled blacklist check TheDJ, 2008-02-28
  // if ( hotcat_is_on_blacklist ( cat_title ) ) return ;
  var mod_id = "hotcat_modify_" + i ;
  var sep2 = document.createTextNode ( " " ) ;
  var a2 = document.createTextNode ( "(±)" ) ;
  var modify_link = document.createElement ( "a" ) ;
  modify_link.id = mod_id ;
  modify_link.href = "javascript:hotcat_modify(\"" + mod_id + "\");" ;
  modify_link.appendChild ( a2 ) ;
  span.appendChild ( sep2 ) ;
  span.appendChild ( modify_link ) ;
}

function hotcat_modify_existing ( catline ) {
  var spans = catline.getElementsByTagName ( "span" ) ;
  for ( var i = 0 ; i < spans.length ; i++ ) {
    hotcat_modify_span ( spans[i] , i ) ;
  }
}

function hotcat_getEvt (evt) {
  return evt || window.event || window.Event; // Gecko, IE, Netscape
}
  
function hotcat_evt2node (evt) {
  var node = null;
  try {
    var e = hotcat_getEvt (evt);
    node = e.target;
    if (!node) node = e.srcElement;
  } catch (ex) {
    node = null;
  }
  return node;
}

function hotcat_evtkeys (evt) {
  var code = 0;
  try {
    var e = hotcat_getEvt (evt);
    if (typeof(e.ctrlKey) != 'undefined') { // All modern browsers
      if (e.ctrlKey)  code |= 1;
      if (e.shiftKey) code |= 2;
      if (e.altKey) code |= 4;
    } else if (typeof (e.modifiers) != 'undefined') { // Netscape...
      if (e.modifiers & Event.CONTROL_MASK) code |= 1;
      if (e.modifiers & Event.SHIFT_MASK)   code |= 2;
      if (e.modifiers & Event.ALT_MASK)   code |= 4;
    }
  } catch (ex) {
  }
  return code;
}

function hotcat_killEvt (evt)
{
  try {
    var e = hotcat_getEvt (evt);
    if (typeof (e.preventDefault) != 'undefined') {
      e.preventDefault();
      e.stopPropagation()
    } else
      e.cancelBubble = true;
  } catch (ex) {
  }
}
  
function hotcat_remove (evt) {
  var node = hotcat_evt2node (evt);
  if (!node) return false;
  // Get the category name from the original link to the category
  var cat_title = node.parentNode.firstChild.innerHTML;
  
  var editlk = document.getElementById('ca-edit').getElementsByTagName('a')[0].href;
  if ((hotcat_evtkeys (evt) & 1) || (hotcat_evtkeys (evt) & 4 )) // CTRL or ALT pressed?
    editlk = editlk + '&hotcat_nocommit=1';
  hotcat_killEvt (evt);
  document.location = editlk + '&hotcat_removecat=' + encodeURIComponent(cat_title) ;
  return false;
}

function hotcatGetParamValue(paramName, h) {
        if (typeof(h) == 'undefined' ) { h = document.location.href; }
        var cmdRe=RegExp('[&?]'+paramName+'=([^&]*)');
        var m=cmdRe.exec(h);
        if (m) {
                try {
                        return decodeURIComponent(m[1]);
                } catch (someError) {}
        }
        return null;
}

// New. Code by Lupo & Superm401, added by Lupo, 2008-02-2007
function hotcat_find_category (wikitext, category)
{
  var cat_name  = category.replace(/([\\\^\$\.\?\*\+\(\)])/g, "\\$1");
  var initial   = cat_name.substr (0, 1);
  var cat_regex = new RegExp ("\\[\\[\\s*[Cc]ategoria\\s*:\\s*"
                              + (initial == "\\"
                                 ? initial
                                 : "[" + initial.toUpperCase() + initial.toLowerCase() + "]")
                              + cat_name.substring (1).replace (/[ _]/g, "[ _]")
                              + "\\s*(\\|.*?)?\\]\\]", "g"
                             );
  var result = new Array ();
  var curr_match  = null;
  while ((curr_match = cat_regex.exec (wikitext)) != null) {
    result [result.length] = {match : curr_match};
  }
  return result; // An array containing all matches, with positions, in result[i].match
}

// New. Code by TheDJ, 2008-03-12
function hotcat_find_ins ( wikitext )
{
  var re = /\[\[(?:Categoria):[^\]]+\]\]/ig
  var index = -1;
  while( re.exec(wikitext) != null ) index = re.lastIndex;
  
  if( index > -1) return index;
  //deveríamos tentar encontrar InterWiki links aqui, mas isso é para mais tarde.

  return -1;
}

// Reescrito (quase) a partir do zero. Lupo, 2008-02-27
function hotcat_check_action () {
  var ret = 0;
  if (wgAction != 'edit' || typeof(document.editform) == "undefined" ) return ret; // Not an edit page, so not our business...
  var summary = new Array () ;
  var t = document.editform.wpTextbox1.value ;
  var prevent_autocommit = 0;
  if (   (typeof (hotcat_no_autocommit) != "undefined" && hotcat_no_autocommit)
      || hotcatGetParamValue ('hotcat_nocommit') == '1')
    prevent_autocommit = 1;

  var cat_rm  = hotcatGetParamValue ('hotcat_removecat');
  var cat_add = hotcatGetParamValue ('hotcat_newcat');
  var cat_key = null;
  if (cat_rm != null && cat_rm.length > 0) {
    var matches = hotcat_find_category (t, cat_rm);
    if (!matches || matches.length == 0) {
      alert ('Categoria "' + cat_rm + '" não foi encontrada! Talvez esteja em uma predefinição.');
      prevent_autocommit = 1;
    } else if (matches.length > 1) {
      alert ('Categoria "' + cat_rm + "\" encontrada por diversas vezes, não sabe quais as opções para remover.");
      prevent_autocommit = 1;
    } else {
      if (cat_add != null && cat_add.length > 0 && matches[0].match.length > 1)
        cat_key = matches[0].match[1]; // Lembre do nome da categoria, se for o caso.
      var t1 = t.substring (0, matches[0].match.index);
      var t2 = t.substring (matches[0].match.index + matches[0].match[0].length);
      // Remover branco (corretamente): tira branco, mas apenas até a próxima linha.
      // Se não tem duas linha, remover uma. Caso contrário, se não temos dois-
      // inserir caracteres em branco.
      var i = t1.length - 1;
      while (i >= 0 && t1.charAt (i) != '\n' && t1.substr (i, 1).search (/\s/) >= 0) i--;
      var j = 0;
      while (j < t2.length && t2.charAt (j) != '\n' && t1.substr (j, 1).search (/\s/) >= 0) j++;
      if (i >= 0 && t1.charAt (i) == '\n' && j < t2.length && t2.charAt (j) == '\n')
        i--;
      if (i >= 0) t1 = t1.substring (0, i+1); else t1 = "";
      if (j < t2.length) t2 = t2.substring (j); else t2 = "";
      if (t1.length > 0 && t1.substring (t1.length - 1).search (/\S/) >= 0
          && t2.length > 0 && t2.substr (0, 1).search (/\S/) >= 0)
        t1 = t1 + ' ';
      t = t1 + t2;
      summary.push ( "removeu \[\[:categoria:" + cat_rm + "\]\]" ) ;
      ret = 1;
    }
  }
  if (cat_add != null && cat_add.length > 0) {
    var matches = hotcat_find_category (t, cat_add);
    if (matches && matches.length > 0) {
      alert ('Categoria "' + cat_add + '" já existe, mas não adicionado.');
      prevent_autocommit = 1;
    } else {
      var insertionpoint = hotcat_find_ins( t );
      var newcatstring = '\n\[\[Categoria:' + cat_add + (cat_key != null ? cat_key : "") + '\]\]';
      if( insertionpoint > -1 ) {
        t = t.substring(0, insertionpoint ) + newcatstring + t.substring( insertionpoint );
      } else {
        t = t + newcatstring;
      }
      summary.push ( "adicionou \[\[:categoria:" + cat_add + "\]\]" ) ;
      var t2 = t.replace(/\{\{[Ss]emcat[^}]*\}\}/g, ""); // Remover a predefinição "semcat"
      if (t2.length != t.length) {
        t = t2;
        summary.push ( "removeu a predefinição {{\[\[Predefinição:Semcat|semcat\]\]}}" ) ;
      }
      ret = 1;
    }
  }
  if (ret) {
    document.editform.wpTextbox1.value = t ;
    document.editform.wpSummary.value = summary.join( "; " )
                                      + " (usando [[Wikipedia:Software/Scripts/HotCat|HotCat]])" ;
    document.editform.wpMinoredit.checked = true ;
    if (!prevent_autocommit) {
      // Ocultar toda a secção editada de modo a não seduzir o usuário em edição...
      var bodyContentId = document.getElementById("bodyContent") || document.getElementById("mw_contentholder");
      bodyContentId.style.display = "none";
      document.editform.submit();
    }
  }
  return ret;
}

function hotcat_clear_span ( span_add ) {
  while ( span_add.firstChild ) span_add.removeChild ( span_add.firstChild ) ;
}

function hotcat_create_span ( span_add ) {
  hotcat_clear_span ( span_add ) ;
  var a_add = document.createElement ( "a" ) ;
  var a_text = document.createTextNode ( "(+)" ) ;
  span_add.id = "hotcat_add" ;
  a_add.href = "javascript:hotcat_add_new()" ;
  a_add.appendChild ( a_text ) ;
  span_add.appendChild ( a_add ) ;
}

function hotcat_modify ( link_id ) {
  var link = document.getElementById ( link_id ) ;
  var span = link.parentNode ;
  var catname = span.firstChild.innerHTML; // was .firstChild.data. Just for consistency
  
  while ( span.firstChild.nextSibling ) span.removeChild ( span.firstChild.nextSibling ) ;
  span.firstChild.style.display = "none" ;
  hotcat_create_new_span ( span , catname ) ;
  hotcat_last_v = "" ;
  hotcat_text_changed () ; // Update icon
}

function hotcat_add_new () {
  var span_add = document.getElementById ( "hotcat_add" ) ;
  hotcat_clear_span ( span_add ) ;
  hotcat_last_v = "" ;
  hotcat_create_new_span ( span_add , "" ) ;
}

function hotcat_create_new_span ( thespan , init_text ) {
  var form = document.createElement ( "form" ) ;
  form.method = "post" ;
  form.onsubmit = function () { hotcat_ok(); return false; } ; 
  form.id = "hotcat_form" ;
  form.style.display = "inline" ;

  var list = null;
  
  if (!hotcat_nosuggestions) {
    // Só nós podemos fazer isso se realmente usar XMLHttp...
    list = document.createElement ( "select" ) ;
    list.id = "hotcat_list" ;
    list.onclick = function ()
      {
        var l = document.getElementById("hotcat_list");
        if (l != null)
          document.getElementById("hotcat_text").value = l.options[l.selectedIndex].text;
        hotcat_text_changed();
      };
    list.ondblclick = function (evt)
      {
        var l = document.getElementById("hotcat_list");
        if (l != null)
          document.getElementById("hotcat_text").value = l.options[l.selectedIndex].text;
        // Não chamada texto aqui se alterou a forma se carregar: hotcat_ok irá remover a lista
        // mesmo assim, de modo que não devemos pedir novas sugestões poderiam desde mostara sugestões
        // levantar uma exceção se ele tentou mostrar uma lista inexistente.
        // Lupo, 2008-01-20
        hotcat_text_changed();
        hotcat_ok((hotcat_evtkeys (evt) & 1) || (hotcat_evtkeys (evt) & 4)); // CTRL or ALT pressed?
      };
    list.style.display = "none" ;
  }
  
  var text = document.createElement ( "input" ) ;
  text.size = 40 ;
  text.id = "hotcat_text" ;
  text.type = "text" ;
  text.value = init_text ;
  text.onkeyup = function () { window.setTimeout("hotcat_text_changed();", hotcat_suggestion_delay ); } ;

  var exists = null;
  if (!hotcat_nosuggestions) {
    exists = document.createElement ( "img" ) ;
    exists.id = "hotcat_exists" ;
    exists.src = hotcat_exists_no ;
  }

  var OK = document.createElement ( "input" ) ;
  OK.type = "button" ;
  OK.value = "OK" ;
  OK.onclick = function (evt) { hotcat_ok ((hotcat_evtkeys (evt) & 1) || (hotcat_evtkeys (evt) & 4)); }; // CTRL or ALT pressed?

  var cancel = document.createElement ( "input" ) ;
  cancel.type = "button" ;
  cancel.value = "Cancelar" ;
  cancel.onclick = hotcat_cancel ;

  if (list != null) form.appendChild ( list ) ;
  form.appendChild ( text ) ;
  if (exists != null) form.appendChild ( exists ) ;
  form.appendChild ( OK ) ;
  form.appendChild ( cancel ) ;
  thespan.appendChild ( form ) ;
  text.focus () ;
}

function hotcat_ok (nocommit) {
  var text = document.getElementById ( "hotcat_text" ) ;
  var v = text.value ;

  // Esvaziar categoria ?
  if ( v == "" ) {
    hotcat_cancel() ;
    return ;
  }

  var editlk = document.getElementById('ca-edit').getElementsByTagName('a')[0].href;
  var url = editlk + '&hotcat_newcat=' + encodeURIComponent( v ) ;

  // Editar existentes?
  var span = text.parentNode.parentNode ; // span.form.text
  if ( span.id != "hotcat_add" ) { // Not plain "addition"   
    url += '&hotcat_removecat=' + span.firstChild.innerHTML;
  }
  if (nocommit) url = url + '&hotcat_nocommit=1';
  document.location = url ;
}

function hotcat_just_add ( text ) {
  var span = document.getElementById("hotcat_form") ;
  while ( span.tagName != "SPAN" ) span = span.parentNode ;
  var add = 0 ;
  if ( span.id == "hotcat_add" ) add = 1 ;
  span.id = "" ;
  while ( span.firstChild ) span.removeChild ( span.firstChild ) ;
  var na = document.createElement ( "a" ) ;
  na.href = wgArticlePath.split("$1").join("Category:" + encodeURI (text)) ;
  na.appendChild ( document.createTextNode ( text ) ) ;
  na.setAttribute ( "título" , "Categoria:" + texto ) ;
  span.appendChild ( na ) ;
  var catline = getElementsByClassName ( document , "p" , "catlinks" ) [0] ;
  if ( add ) hotcat_append_add_span ( catline ) ;

  for ( var i = 0 ; i < span.parentNode.childNodes.length ; i++ ) {
    if ( span.parentNode.childNodes[i] != span ) continue ;
    hotcat_modify_span ( span , i ) ;
    break ;
  }
}

function hotcat_cancel () {
  var span = document.getElementById("hotcat_form").parentNode ;
  if ( span.id == "hotcat_add" ) {
    hotcat_create_span ( span ) ;
  } else {
    while ( span.firstChild.nextSibling ) span.removeChild ( span.firstChild.nextSibling ) ;
    span.firstChild.style.display = "" ;
    for ( var i = 0 ; i < span.parentNode.childNodes.length ; i++ ) {
      if ( span.parentNode.childNodes[i] != span ) continue ;
      hotcat_modify_span ( span , i ) ;
      break ;
    }
  }
}

function hotcat_text_changed () {
  if ( hotcat_running ) return ;
  var text = document.getElementById ( "hotcat_text" ) ;
  var v = text.value.ucFirst() ;
  if ( hotcat_last_v == v ) return ; // Nothing's changed...

  if (hotcat_nosuggestions) {
    // No IE, XMLHttp usa ActiveX, e o usuário pode negar execução... apenas se certificar
    // A lista não é exibida.
    var list = document.getElementById ('hotcat_list');
    if (list != null) list.style.display = "none" ;
    var exists = document.getElementById ('hotcat_exists');
    if (exists != null) exists.style.display = "none" ;
    return;
  }
  
  hotcat_running = 1 ;
  hotcat_last_v = v ;

  if ( v != "" ) {
    var url = wgServer + wgScriptPath
            + "/api.php?format=xml&action=query&list=allpages&apnamespace=14&apfrom="
            + encodeURIComponent( v ) ;
    var request = sajax_init_object() ;
    if (request == null) {
      //Oops! We don't have XMLHttp...
      hotcat_nosuggestions = true;
      var list = document.getElementById ('hotcat_list');
      if (list != null) list.style.display = "none" ;
      var exists = document.getElementById ('hotcat_exists');
      if (exists != null) exists.style.display = "none" ;
      hotcat_running = 0;
      return;
    } 
    request.open('GET', url, true);
    request.onreadystatechange = function () {
          if (request.readyState == 4) {
            var xml = request.responseXML ;
            if ( xml == null ) return ;
            var pages = xml.getElementsByTagName( "p" ) ;
            var titles = new Array () ;
            for ( var i = 0 ; i < pages.length ; i++ ) {
              // Faixa "Categoria:" mas não se quebram com títulos como "Categoria:Espaço: 2001 a space odyssey"
              var s = pages[i].getAttribute("title").replace( /Categoria:/gi, "" );
              if ( s.substr ( 0 , hotcat_last_v.length ) != hotcat_last_v ) break ;
              titles.push ( s ) ;
            }
            hotcat_show_suggestions ( titles ) ;
          }
      };
    request.setRequestHeader ('Pragma', 'cache=yes');
    request.setRequestHeader ('Cache-Control', 'no-transform');
    request.send(null);
  } else {
    hotcat_show_suggestions ( new Array () ) ;
  }
  hotcat_running = 0 ;
}

function hotcat_show_suggestions ( titles ) {
  var text = document.getElementById ( "hotcat_text" ) ;
  var list = document.getElementById ( "hotcat_list" ) ;
  var icon = document.getElementById ( "hotcat_exists" ) ;
  // Somehow, after a double click on the selection list, we still get here in IE, but
  // the list may no longer exist... Lupo, 2008-01-20
  if (list == null) return;
  if (hotcat_nosuggestions) {
    list.style.display = "none" ;
    if (icon != null) icon.style.display = "none";
    return;
  }
  if ( titles.length == 0 ) {
    list.style.display = "none" ;
    icon.src = hotcat_exists_no ;
    return ;
  }
  
  // Definir a lista dimensão mínima de 5 e o número de títulos. Anteriormente era apenas 5.
  // Lupo, 2008-01-20
  list.size = (titles.length > 5 ? 5 : titles.length) ;
  // Avoid list height 1: double-click doesn't work in FF. Lupo, 2008-02-27
  if (list.size == 1) list.size = 2;
  list.style.align = "left" ;
  list.style.zIndex = 5 ;
  list.style.position = "absolute" ;

  // Was listh = titles.length * 20: that makes no sense if titles.length > list.size
  // Lupo, 2008-01-20
  var listh = list.size * 20;
  var nl = parseInt (text.offsetLeft) - 1 ;
  var nt = parseInt (text.offsetTop) - listh ;
  list.style.top = nt + "px" ;
  list.style.width = text.offsetWidth + "px" ;
  list.style.height = listh + "px" ;
  list.style.left = nl + "px" ;
  while ( list.firstChild ) list.removeChild ( list.firstChild ) ;
  for ( var i = 0 ; i < titles.length ; i++ ) {
    var opt = document.createElement ( "option" ) ;
    var ot = document.createTextNode ( titles[i] ) ;
    opt.appendChild ( ot ) ;
    //opt.value = titles[i] ;
    list.appendChild ( opt ) ;
  }
  
  icon.src = hotcat_exists_yes ;

  var nof_titles = titles.lenght;
  var first_title = titles.shift () ;
  var v = text.value.ucFirst() ;
  if ( first_title == v ) {
    if( nof_titles == 1 ) {
      // Apenas um resultado, e é o mesmo que o que está na caixa de entrada: não faz sentido
      // para mostrar a lista. Mas, certifique-se do campo de texto tem o foco !
      text.focus();
      list.style.display = "none";
    }
    return;
  }
  list.style.display = "block" ;

  // Coloque a primeira entrada da lista o título no campo de texto, e selecione o
  // novo sufixo que este será sobrescrito se mantém o usuário digitar.
  // Faça isto apenas se nós temos uma maneira de selecionar o conteúdo das partes de um texto
  // campo, caso contrário, isso é muito desagradável para o usuário. Nota: IE não é
  // novamente de forma diferente da anteriormente implementadas duas versões.
  // Lupo, 2008-01-20
  // Apenas ponha entrada em primeiro da lista, se o utilizador não tenha algo digitado 
  // conflicting yet Dschwen 2008-02-18
  if ( ( text.setSelectionRange ||
         text.createTextRange ||
         typeof (text.selectionStart) != 'undefined' &&
         typeof (text.selectionEnd) != 'undefined' ) &&
         v == first_title.substr(0,v.length) )
  {
    // tendo hotcat_last_v era um grande incómodo, 
    // uma vez que constantemente mortos no texto que foi digitado
    // desde o último pedido AJAX foi despedido! Dschwen 2008-02-18
    var nosel = v.length ;
  
    text.value = first_title ;
    
    if (text.setSelectionRange)      // e.g. khtml
      text.setSelectionRange (nosel, first_title.length);
    else if (text.createTextRange) { // IE
      var new_selection = text.createTextRange();
      new_selection.move ("character", nosel);
      new_selection.moveEnd ("character", first_title.length - nosel);
      new_selection.select();
    } else {
      text.selectionStart = nosel;
      text.selectionEnd   = first_title.length;
    }
  }
}

importScript('MediaWiki:Common.js/HotCat.js')

//</source>