MediaWiki:Common.js/pt

O conteúdo da página não é suportado noutras línguas.
Origem: Wikcionário, o dicionário livre.

/* Any JavaScript here will be loaded for all users on every page load. */

/**

* Create a new DOM node for the current document.
*    Basic usage:  var mySpan = newNode('span', "Hello World!")
*    Supports attributes and event handlers*: var mySpan = newNode('span', {style:"color: red", focus: function(){alert(this)}, id:"hello"}, "World, Hello!")
*    Also allows nesting to create trees: var myPar = newNode('p', newNode('b',{style:"color: blue"},"Hello"), mySpan)
*
* *event handlers, there are some issues with IE6 not registering event handlers on some nodes that are not yet attached to the DOM,
* it may be safer to add event handlers later manually.
    • /

function newNode(tagname){

 var node = document.createElement(tagname);
 for( var i=1;i<arguments.length;i++ ){
   if(typeof arguments[i] == 'string'){ //Text
     node.appendChild( document.createTextNode(arguments[i]) );
   }else if(typeof arguments[i] == 'object'){
     if(arguments[i].nodeName){ //If it is a DOM Node
       node.appendChild(arguments[i]);
     }else{ //Attributes (hopefully)
       for(var j in arguments[i]){
         if(j == 'class'){ //Classname different because...
           node.className = arguments[i][j];
         }else if(j == 'style'){ //Style is special
           node.style.cssText = arguments[i][j];
         }else if(typeof arguments[i][j] == 'function'){ //Basic event handlers
           try{ node.addEventListener(j,arguments[i][j],false); //W3C
           }catch(e){try{ node.attachEvent('on'+j,arguments[i][j],"Language"); //MSIE
           }catch(e){ node['on'+j]=arguments[i][j]; }} //Legacy
         }else{
           node.setAttribute(j,arguments[i][j]); //Normal attributes
         }
       }
     }
   }
 }
 return node;

}


/* select subsection of special characters */ function chooseCharSubset(s) {

 var l = document.getElementById('editpage-specialchars').getElementsByTagName('p');
 for (var i = 0; i < l.length ; i++) {
   l[i].style.display = i == s ? 'inline' : 'none';
   l[i].style.visibility = i == s ? 'visible' : 'hidden';
 }
 $.cookie('edittoolscharsubset', s, { expires : 999 });

}

/* add menu for selecting subsets of secial characters */ /***** must match MediaWiki:Edittools *****/ function addCharSubsetMenu() {

 mw.loader.load( 'mediawiki.toolbar' ); /* Load the insertTags legacy stub */

}

/* do any Wiktionary-specific customizations */ function customizeWiktionary() {

 addCharSubsetMenu();

}

$( customizeWiktionary );

//Essa função altera o funcionamento dos cabeçalhos de idioma (nível 1)

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) {
/* Something went wrong. */
}

};

$( rewritePageH1 );

// The function looks for a banner like that:

//

Div that is hidden

// title

//

// An element with id=DisableRealTitle disables the function.

$(function () {

 var $titleBanner = $("#RealTitleBanner");
 if ($titleBanner && !$("#DisableRealTitle").length) {
   var $realTitle = $("#RealTitle");
   var realTitle = $realTitle.html();
   var $h1 = $("h1")[0];
   if (realTitle && $h1) {
     if (realTitle === "") {
       $($h1).hide();
     } else {
       $($h1).html(realTitle);
       // noinspection JSValidateTypes
       if (mw.config.get("wgAction") === "view" && $realTitle.children().length === 0) {
         document.title = $realTitle.text() + " — Wikcionário";
       }
     }
     $titleBanner.hide();
   }
 }

});

/*

Controle de imagem ofensiva

  • /

// Desenvolvido por Voz da Verdade 27/jan/2007

function ApagarAvisoImagemOfensiva(){

   var aviso01=document.getElementById("imagemOfensiva01");
   aviso01.style.display = 'none';

}

function criarBtnMostraImgOfensiva() {

   var aviso02=document.getElementById("imagemOfensiva02");
   if (aviso02) {
     var botaoImgOfensiva = document.createElement('a');
     var pularLinha = document.createElement('br');
     botaoImgOfensiva.className = 'btnMostraImagemOfensiva';
     botaoImgOfensiva.setAttribute('href', 'javascript:mostrarImagemOfensiva();');
     var textoMostraImgOfensiva = document.createTextNode('Mostrar imagem');
     botaoImgOfensiva.appendChild(pularLinha);
     botaoImgOfensiva.appendChild(textoMostraImgOfensiva);
     aviso02.appendChild(botaoImgOfensiva);
     var apagarEsteAviso = document.createElement('a');
     apagarEsteAviso.setAttribute('href','javascript:ApagarAvisoImagemOfensiva();');
     var textoApagarAvisoImgOfensiva = document.createTextNode('Ocultar');
     var pularLinha2 = document.createElement('br');
     apagarEsteAviso.appendChild(pularLinha2);
     apagarEsteAviso.appendChild(textoApagarAvisoImgOfensiva);
     aviso02.appendChild(apagarEsteAviso);
   }

}

function mostrarImagemOfensiva(){

   var aviso01=document.getElementById("imagemOfensiva01");
   aviso01.style.display = 'none';
   var aviso03=document.getElementById("imagemOfensiva03");
   aviso03.style.display = 'block';

}

$( criarBtnMostraImgOfensiva);


/** Collapsible tables

*
* Description: Allows tables to be collapsed, showing only the header. See
*              Wikipedia:NavFrame.
* Maintainers: User:R. Koot
* TODO: substituir pelo plugin makeCollapsible quando estiver online (ver mw:RL/DM#jQuery.makeCollapsible)
*/


var autoCollapse = 2;
var collapseCaption = "Esconder ▲";
var expandCaption = "Expandir ▼";
function collapseTable( tableIndex )
{
    var Button = document.getElementById( 'collapseButton' + tableIndex );
    var Table = document.getElementById( 'collapsibleTable' + tableIndex );
    var i;
    if ( !Table || !Button ) {
        return false;
    }
    var Rows = Table.rows;
    if ( Button.firstChild.data == collapseCaption ) {
        for ( i = 1; i < Rows.length; i++ ) {
            Rows[i].style.display = 'none';
        }
        Button.firstChild.data = expandCaption;
    } else {
        for ( 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 = {};
    var Tables = document.getElementsByTagName( 'table' );
    var i;
    for ( i = 0; i < Tables.length; i++ ) {
        if ( $(Tables[i]).hasClass('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 ( i = 0;  i < tableIndex; i++ ) {
        if ( $(NavigationBoxes[i]).hasClass('collapsed' ) || ( tableIndex >= autoCollapse && $(NavigationBoxes[i]).hasClass( 'autocollapse' ) ) ) {
            collapseTable( i );
        }
    }
}
$( createCollapseButtons );


// ============================================================
// BEGIN Dynamic Navigation Bars (experimental)
// TODO: substituir pelo plugin makeCollapsible quando estiver online (ver mw:RL/DM#jQuery.makeCollapsible)
// set up the words in your language
var NavigationBarHide = '[ Esconder ▲ ]';
var NavigationBarShow = '[ Expandir ▼ ]';
// set up max count of Navigation Bars on page,
// if there are more, all will be hidden
// NavigationBarShowDefault = 0; // all bars will be hidden
// NavigationBarShowDefault = 1; // on pages with more than 1 bar all bars will be hidden
var NavigationBarShowDefault = 0;


// 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);
   var NavChild;
   if (!NavFrame || !NavToggle) {
       return false;
   }
   // if shown now
   if (NavToggle.firstChild.data == NavigationBarHide) {
       for (
               NavChild = NavFrame.firstChild;
               NavChild != null;
               NavChild = NavChild.nextSibling
           ) {
           if (NavChild.className == 'NavPic') {
               NavChild.style.display = 'none';
           }
           if (NavChild.className == 'NavContent') {
               NavChild.style.display = 'none';
           }
       }
   NavToggle.firstChild.data = NavigationBarShow;
   // if hidden now
   } else if (NavToggle.firstChild.data == NavigationBarShow) {
       for (
               NavChild = NavFrame.firstChild;
               NavChild != null;
               NavChild = NavChild.nextSibling
           ) {
           if (NavChild.className == 'NavPic') {
               NavChild.style.display = 'block';
           }
           if (NavChild.className == 'NavContent') {
               NavChild.style.display = 'block';
           }
       }
   NavToggle.firstChild.data = NavigationBarHide;
   }
}

// adds show/hide-button to navigation bars function createNavigationBarToggleButton() {

   var indexNavigationBar = 0;
   var i;
   // iterate over all < div >-elements
   for(
           i=0;
           NavFrame = document.getElementsByTagName('div')[i];
           i++
       ) {
       // if found a navigation bar
       if (NavFrame.className == '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);
           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 (NavFrame.childNodes[j].className == 'NavHead') {
               NavFrame.childNodes[j].appendChild(NavToggle);
             }
           }
           NavFrame.setAttribute('id', 'NavFrame' + indexNavigationBar);
       }
   }
   // if more Navigation Bars found than Default: hide all
   if (NavigationBarShowDefault < indexNavigationBar) {
       for(
               i=1;
               i<=indexNavigationBar;
               i++
       ) {
           toggleNavigationBar(i);
       }
   }

}

$( createNavigationBarToggleButton );

// END Dynamic Navigation Bars
// ============================================================


/**

* @source: 
* @todo: Migrar para um gadget e sincronizar com o original
*/

//Gera a aba Citações (e, no namespace Predefinição, também a aba Documentação) var conf = mw.config.get([ 'wgPageName', 'wgArticleId', 'wgCanonicalNamespace', 'wgTitle', 'wgScriptPath' ]);

function citations_tab(){

 var texts = {
     // tab id : [ label, hover-text, access-key (c if tab comes first, 3 if last) ]
     'ca-nstab-main': ['Entrada', 'Ver a página de conteúdo', 'c'],
     'ca-nstab-citações': ['Citações', 'Ver página de citações', '3'],
     'ca-nstab-template': ['Predefinição', 'Ver predefinição', 'c'],
     'ca-nstab-documentation': ['Documentação', 'Documentação da predefinição', '3']
 };

 var lookup = {}; // {page-title: tab-node} these are looked up and changed to red if missing.

 // Returns [id-of-portlet, node-to-insert-before or null] for inserting the tab.
 function get_insert_position(id) {
   var portlet = document.getElementById('p-namespaces') ? 'p-namespaces' : 'p-cactions';
   var insbef = null;

   if (texts[id][2] == 'c') { // otherwise '3'
      insbef = document.getElementById(portlet).getElementsByTagName('ul')[0].firstChild;
   } else if (portlet == 'p-cactions' ) { // 'last' in Monobook means "before Edit"
     var insbef = document.getElementById('ca-edit');
     if(! insbef) insbef = document.getElementById('ca-viewsource');
   }

   return [portlet, insbef];
 }

 // Add a new namespace with addPortletLink using the lookup table above.
 function add_namespace_tab(page, id) {
   var insert = get_insert_position(id);
   mw.util.addPortletLink( insert[0], mw.util.getUrl( page ), texts[id][0], id, texts[id][1], texts[id][2], insert[1] ); 
   if (page == conf.wgPageName) { // Can by-pass lookup
       var tab = document.getElementById(id);
       tab.className = 'selected';
       if (conf.wgArticleId == 0) {
        make_tab_red(tab);
       }
   } else { // lookup the redness with the ajax below
       lookup[page]=document.getElementById(id);
   }
 }

 // Replace the two current tabs with new ones, used when in the third namespace.
 function change_main_tabs(old_id, new_id, talk_page) {
   // Remove old tab.
   var ct = document.getElementById(old_id);
   ct.parentNode.removeChild(ct);
   // Add new tab.
   add_namespace_tab(conf.wgPageName, new_id);

   // Change destination of talk tab.
   var dt = document.getElementById('ca-talk');
   var a = dt.getElementsByTagName('a')[0];
   a.setAttribute('href', mw.util.getUrl( talk_page ));
   lookup[talk_page] = dt;
   if(dt.className) dt.className = dt.className.replace('new',);
 }

 // Change a blue-link to a red-link
 function make_tab_red(tab){
   tab.className = tab.className+' new';
   var a = tab.getElementsByTagName('a')[0];
   var href = a.getAttribute('href');
   a.setAttribute('href',href+(href.indexOf('?')>0?'&':'?')+'action=edit&redlink=1');
 }

 if( conf.wgCanonicalNamespace == 'Citações' ){  
   change_main_tabs('ca-nstab-citações', 'ca-nstab-citações', 'Discussão:' + conf.wgTitle);
   add_namespace_tab(conf.wgTitle, 'ca-nstab-main');

 }else if( conf.wgCanonicalNamespace ==  || conf.wgCanonicalNamespace == 'Talk' ){
   add_namespace_tab('Citações:'+conf.wgTitle, 'ca-nstab-citações');

 }else if( conf.wgCanonicalNamespace == 'Template' && /\/doc$/.test(conf.wgTitle) ){
   var baseTitle = conf.wgTitle.replace(/\/doc$/, "");
   change_main_tabs('ca-nstab-template', 'ca-nstab-documentation', 'Predefinição Discussão:' + baseTitle);
   add_namespace_tab('Predefinição:' + baseTitle, 'ca-nstab-template');

 }else if( conf.wgCanonicalNamespace == 'Template' || conf.wgCanonicalNamespace == 'Template_talk' ){
   add_namespace_tab('Predefinição:'+conf.wgTitle+'/doc', 'ca-nstab-documentation');

 }else{ //Nothing to see here...
   return false;

 }

 //Now check for red pages
 // mw:RL/JD: sajax_init_object is deprecated. Use $.ajax, $.getJSON and/or $.get

 var pagetitles = ;
 var spl = ;
 for(var page in lookup) {
   pagetitles += spl + page;  // encodeURIComponent(page);
   spl = '|';
 }

$.getJSON(

mw.util.wikiScript( 'api' ), { format: 'json', action: 'query', titles: pagetitles, prop: 'info' }, function( obj ) { /* API call was successful do something with obj */

          if (obj['query']['pages'] == undefined)     return;
          $.each( obj['query']['pages'], function () {
             title = this.title;
             if (this.missing != undefined) {
               make_tab_red(lookup[title]);
             }
          } );
        }
);

}

$( function() { mw.loader.using( 'mediawiki.util', citations_tab ); } );

/*

Redirecionamento automático

Permite o redirecionamento automático para página com grafia semelhante (geralmente, troca de inicial maiúscula por minúscula e vice-versa).

  • /

function doRedirect() {

   // REDIRECTED FROM
   if( window.location.href.indexOf('redirde=') != -1 ) {
       var wiktDYMfrom = decodeURIComponent(window.location.href.replace(/^(.+[&\?]redirde=([^&]+).*|.*)?$/,"$2"));
       jQuery('#siteSub').after(
           newNode('div', {id: 'contentSub'}, '(Auto-redirecionado de ',
               newNode('tt', newNode('a', {href: mw.util.getUrl(wiktDYMfrom) + '?redirect=no', 'class': 'new'}, wiktDYMfrom)),
       ')'));
   } else {
       // DID YOU MEAN
   
       var target = jQuery('#did-you-mean a').html(),
           pagetitle = jQuery.trim(jQuery('h1').first().text());
       if( target && target != pagetitle
                  && !window.location.href.match(/[&\?]redirect=no|[&\?]action=(?!view)/)
                  && ($.cookie('WiktionaryDisableAutoRedirect') != 'true')
                  && mw.config.get('wgArticleId') === 0
                  && !/Redirected from/.test(jQuery('#contentSub').html())) {
           document.location = mw.util.getUrl( target ) + '?redirde=' + mw.util.wikiUrlencode( pagetitle );
       }
   }

}

$( doRedirect );