MediaWiki:Common.js

do Galizionario, dicionario galego na Internet.

Nota: Após grabar, cómpre limpar a memoria caché do seu navegador para ver os cambios: Mozilla: prema Recargar (ou Ctrl-R), IE / Opera: Ctrl-F5, Safari: Cmd-R, Konqueror Ctrl-R.

/* Calquera JavaScript que haxa aquí será cargado para todos os usuarios */
/* Véxame tamén [[Especial:A_miña_páxina_de_usuario/vector.js]], [[MediaWiki:Vector.js]] */

/*</pre>
=== DOM creation ===
<pre>*/
/**
 * 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;
}

/*</pre>

==Wiktionary Customisation==
<pre>*/

//initialize the storage for script options. Gadgets that set script
//options should also include this line as they are loaded before us.
if(typeof WiktScriptPrefs == 'undefined') WiktScriptPrefs = {};

/*</pre>

===Edit page javascript===
<pre>*/
/*if (mw.config.get('wgAction') == 'edit' || mw.config.get('wgAction') == 'submit' ) importScript('MediaWiki:Edit.js')

$( function () { 
    if (document.getElementById('editpage-specialchars'))
        importScript('MediaWiki:Edit.js');
});*/
/*</pre>
===Page specific extensions===
<pre>*/

/*</pre>
====Wiktionary:Main Page====
<pre>*/
// Hide the title and "Redirected from" (maybe we should keep the redirected from so's people update their bookmarks ;)
// Broken in IE!
if ( mw.config.get('wgPageName') == 'Wiktionary:Páxina_principal' && !( mw.config.get('wgAction') == 'view' || mw.config.get('wgAction') == 'submit' ) ){
  mw.util.addCSS('.firstHeading {display: block !important;}');
  mw.util.addCSS('#contentSub {display: inline !important;}');

} else if (mw.config.get('wgPageName') == 'Wiktionary:Páxina_principal' || mw.config.get('wgPageName') == 'Conversa_Wiktionary:Páxina_principal') 
    $(function () {
        mw.util.addPortletLink('p-lang', '//meta.wikimedia.org/wiki/Wiktionary#List_of_Wiktionaries',
                 'Lista completa', 'interwiki-completelist', 'Lista completa de Wiktionaries')
        var nstab = document.getElementById('ca-nstab-project')
        if (nstab && wgUserLanguage=='gl') {
            while (nstab.firstChild) nstab = nstab.firstChild
            nstab.nodeValue = 'Páxina principal'
        }
    }
)

/*</pre>
====Special:Search====
<pre>*/

/*if ( mw.config.get('wgPageName') == 'Special:Search') {
    importScript('MediaWiki:SpecialSearch.js');
}
$(function () { if(document.getElementById('preloadGuide')) {
    importScript('MediaWiki:SpecialSearch.js');
}});*/


/*</pre>
== Visibility toggling ==
<pre>*/
var VisibilityToggles = {
    // toggles[category] = [[show, hide],...]; statuses[category] = [true, false,...]; buttons = <li>
    toggles: {}, statuses: {}, buttons: null,

    // Add a new toggle, adds a Show/Hide category button in the toolbar,
    // and will call show_function and hide_function once on register, and every alternate click.
    register: function (category, show_function, hide_function) {

        var id = 0;
        if (!this.toggles[category]) {
            this.toggles[category] = [];
            this.statuses[category] = [];
        } else {
            id = this.toggles[category].length;
        }
        this.toggles[category].push([show_function, hide_function]);
        this.statuses[category].push(this.currentStatus(category));
        this.addGlobalToggle(category);

        (this.statuses[category][id] ? show_function : hide_function)();

        return function () {
            var statuses = VisibilityToggles.statuses[category];
            statuses[id] = !statuses[id]
            VisibilityToggles.checkGlobalToggle(category);
            return (statuses[id] ? show_function : hide_function)();
        }

    },

    // Add a new global toggle to the side bar
    addGlobalToggle: function(category) {
        if (document.getElementById('p-visibility-'+category))
            return;
        if (!this.buttons) {
            this.buttons = newNode('ul');
            var collapsed = $.cookie("vector-nav-p-visibility") == "false", toolbox = newNode('div', {'class': "portal portlet "+(collapsed?"collapsed":"expanded"), 'id': 'p-visibility'},
                            newNode('h5', 'Visibilidade'),
                            newNode('div', {'class': "pBody body"}, collapsed?undefined:{'style':'display:block;'}, this.buttons)
                          );
            var sidebar = document.getElementById('mw-panel') || document.getElementById('column-one');
            var insert = null;
            if (insert = (document.getElementById('p-lang') || document.getElementById('p-feedback')))
                sidebar.insertBefore(toolbox, insert);
            else
                sidebar.appendChild(toolbox);

        }
        var status = this.currentStatus(category);
        var newToggle = newNode('li', newNode('a', {
            id: 'p-visibility-' + category, 
            style: 'cursor: pointer',
            href: '#visibility-' + category,
            click: function(e)
            {
                VisibilityToggles.toggleGlobal(category); 
                if (e && e.preventDefault)
                    e.preventDefault();
                else 
                    window.event.returnValue = false;
                return false; 
            }},
            (status ? 'Agochar ' : 'Mostrar ') + category));
        for (var i=0; i < this.buttons.childNodes.length; i++) {
            if (this.buttons.childNodes[i].id < newToggle.id) {
                this.buttons.insertBefore(newToggle, this.buttons.childNodes[i]);
                return;
            }
        }
        this.buttons.appendChild(newToggle);
    },

    // Update the toggle-all buttons when all things are toggled one way
    checkGlobalToggle: function(category) {
        var statuses = this.statuses[category];
        var status = statuses[0];
        for (var i = 1; i < statuses.length; i++) {
            if (status != statuses[i])
                return;
        }
        document.getElementById('p-visibility-' + category).innerHTML = (status ? 'Agochar ' : 'Mostrar ') + category;
    },

    // Toggle all un-toggled elements when the global button is clicked
    toggleGlobal: function(category) {
        var status = document.getElementById('p-visibility-' + category).innerHTML.indexOf('Mostrar ') == 0;
        for (var i = 0; i < this.toggles[category].length; i++ ) {
            if (this.statuses[category][i] != status) {
                this.toggles[category][i][status ? 0 : 1]();
                this.statuses[category][i] = status;
            }
        }
        document.getElementById('p-visibility-' + category).innerHTML = (status ? 'Agochar ' : 'Mostrar ') + category;
        var current = $.cookie('Visibility');
        if (!current)
            current = ";";
        current = current.replace(';' + category + ';', ';');
        if (status)
            current = current + category + ";";
        $.cookie('Visibility', current);
    },

    currentStatus: function(category) {
        if ($.cookie('WiktionaryPreferencesShowNav') == 'true')
            return true;
        else if ($.cookie('Visibility') && $.cookie('Visibility').indexOf(';' + category + ';') >= 0)
            return true;
        return false; // TODO load this from category specific cookies
    }
};
/*</pre>
=== NavBars ===
<pre>*/
var NavigationBarHide = 'agochar ▲';
var NavigationBarShow = 'mostrar ▼';

function NavToggleCategory(navFrame)
{
    var table = navFrame.getElementsByTagName('table')[0];
    if (table && table.className == "conjugations")
        return "conxugacións";

    var heading = navFrame.previousSibling;
    while (heading) {
        if (/[hH][4-6]/.test(heading.nodeName)) {
            if (heading.getElementsByTagName('span')[1]) {
                return heading.getElementsByTagName('span')[1].innerHTML.toLowerCase();
                }
            else {
                return heading.getElementsByTagName('span')[0].innerHTML.toLowerCase();
                }
            }
        else if (/[hH][1-3]/.test(heading.nodeName)) 
            break;
        heading = heading.previousSibling;
    }
    return "outras caixas";
};
function createNavToggle(navFrame)
{
    var navHead, navToggle, navContent;
    for (var j=0; j < navFrame.childNodes.length; j++) {
        var div = navFrame.childNodes[j];
        switch (div.className) {
            case 'NavHead':
                navHead = div;
                break;
            case 'NavContent':
                navContent = div;
                break;
        }
    }
    if (!navHead || !navContent)
        return;
    // Step 1, don't react when a subitem is clicked.
    for (var i=0; i<navHead.childNodes.length; i++) {
        var child = navHead.childNodes[i];
        if (child.nodeType == 1) {
            child.onclick = function (e)
            {
                if (e && e.stopPropagation)
                    e.stopPropagation();
                else
                    window.event.cancelBubble = true;
            }
        }
    }
    // Step 2, toggle visibility when bar is clicked.
    // NOTE This function was chosen due to some funny behaviour in Safari.
    navToggle = newNode('a', {href: 'javascript:(function(){})()'}, '');
    navHead.insertBefore(newNode('span', {'class': 'NavToggle'}, '[', navToggle, ']'), navHead.firstChild);

    navHead.style.cursor = "pointer";
    navHead.onclick = VisibilityToggles.register(NavToggleCategory(navFrame),
        function show() {
            navToggle.innerHTML = NavigationBarHide;
            if (navContent)
                navContent.style.display = "block";
        },
        function hide() {
            navToggle.innerHTML = NavigationBarShow;
            if (navContent)
                navContent.style.display = "none";
        });
};

$( function ()
{
    var divs = $(".NavFrame");
    for (var i=0; i<divs.length; i++) {
        // NOTE: some templates use a class of NavFrame for the style, but for legacy reasons, are not NavFrames
        if (divs[i].className == "NavFrame") {
            createNavToggle(divs[i]);
        }
    }
 
});

/*</pre>

===Hidden Quotes===
<pre>*/

function setupHiddenQuotes(li)
{
   var HQToggle, liComp;
   var HQShow = '+ info';
   var HQHide = '− info';
   for (var k = 0; k < li.childNodes.length; k++) {
      // Look at each component of the definition.
      liComp = li.childNodes[k];
      // If we find a ul or dl, we have quotes or example sentences, and thus need a button.
      if (/^(ul|UL)$/.test(liComp.nodeName)) {
         HQToggle = newNode('a', {href: 'javascript:(function(){})()'}, '');
         li.insertBefore(newNode('span', {'class': 'HQToggle', 'style': 'font-size:0.65em'}, ' [', HQToggle, ']'), liComp);
         HQToggle.onclick = VisibilityToggles.register('información nas definicións',          
            function show() {
               HQToggle.innerHTML = HQHide;
               for (var child = li.firstChild; child != null; child = child.nextSibling) {
                  if (/^(ul|UL)$/.test(child.nodeName)) {
                     child.style.display = 'block';
                     }
                  }
               },
            function hide() {
               HQToggle.innerHTML = HQShow;
               for (var child = li.firstChild; child != null; child = child.nextSibling) {
                  if (/^(ul|UL)$/.test(child.nodeName)) {
                     child.style.display = 'none';
                     }
                  }
               });

         break;
         }
      }
   }            
               
$( function () 
{
   if (mw.config.get('wgNamespaceNumber') == 0) {
      var ols, lis, li;
      // First, find all the ordered lists, i.e. all the series of definitions.
      var ols = document.getElementsByTagName('ol');
      for(var i = 0; i < ols.length; i++) {
         // Then, for every set, find all the individual definitions.
         for (var j = 0; j < ols[i].childNodes.length; j++) {
            li = ols[i].childNodes[j];
            if (li.nodeName.toUpperCase() == 'LI') {
               setupHiddenQuotes(li);
               }
            }
         }
      }
   });

// Aquí remata o traído de [[:en:MediaWiki:Common.js]]; o que vén a continuación procede da Galipedia
 
function hiddencat()
{
 var cl = document.getElementById('catlinks');           if(!cl) return;
 var hc = document.getElementById('mw-hidden-catlinks'); if(!hc) return;
 var nc = document.getElementById('mw-normal-catlinks');
 if(!nc)
 {
  var ahc = '<div id="mw-normal-catlinks"><a href="/wiki/Especial:Categorías" title="Especial:Categorías">Categorías</a>&nbsp;:&#32;<span dir="ltr"><a onclick="javascript:toggleHiddenCats();" id="mw-hidden-cats-link" style="cursor:pointer; color:black;" title="Este artigo contén categorías ocultas"><small>[<span style="color:#002BB8;"> amosar </span>]</small></a></span></div>';
  document.getElementById('catlinks').innerHTML = ahc + cl.innerHTML;
 }
 else if( $(hc).hasClass('mw-hidden-cats-hidden') )
 {
  var ahc = ' | <a onclick="javascript:toggleHiddenCats();" id="mw-hidden-cats-link" style="cursor:pointer; color:black;" title="Este artigo contén categorías ocultas"><small>[<span style="color:#002BB8;"> amosar </span>]</small></a>';
  document.getElementById('mw-normal-catlinks').innerHTML += ahc;
 }
}
function toggleHiddenCats()
{
 var hc = document.getElementById('mw-hidden-catlinks');
 if( $(hc).hasClass('mw-hidden-cats-hidden') )
 {
  $(hc).removeClass('mw-hidden-cats-hidden');
  $(hc).addClass('mw-hidden-cat-user-shown');
  document.getElementById('mw-hidden-cats-link').innerHTML = '<small>[<span style="color:#002BB8;"> ocultar </span>]</small>';
 }
 else
 {
  $(hc).removeClass('mw-hidden-cat-user-shown');
  $(hc).addClass('mw-hidden-cats-hidden');
  document.getElementById('mw-hidden-cats-link').innerHTML = '<small>[<span style="color:#002BB8;"> amosar </span>]</small>';
 }
}
 
$(hiddencat);


/***** Menú do MediaWiki:Edittools (adaptado do pt.wikt) *****/

/* 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);
}

/* add menu for selecting subsets of special characters */
/***** must match MediaWiki:Edittools *****/
function addCharSubsetMenu() {
  var edittools = document.getElementById('editpage-specialchars');

  if (edittools) {
    var menu = "<select id=\"charSubsetControl\" style=\"display:inline\" onChange=\"chooseCharSubset(selectedIndex)\">";
    menu += "<option>Miscelánea</option>";
    menu += "<option>Modelos</option>";
    menu += "<option>Latín</option>";
    menu += "<option>AFI</option>";
    menu += "<option>AHD</option>";
    menu += "<option>Alemán</option>";
    menu += "<option>Árabe</option>";
    menu += "<option>Armenio</option>";
    menu += "<option>Catalán</option>";
    menu += "<option>Cirílico</option>";
    menu += "<option>Esperanto</option>";
    menu += "<option>Estoniano</option>";
    menu += "<option>Francés</option>";
    menu += "<option>Galego</option>";
    menu += "<option>Grego</option>";
    menu += "<option>Grego antigo</option>";
    menu += "<option>Hawaiano</option>";
    menu += "<option>Inglés antigo</option>";
    menu += "<option>Islandés</option>";
    menu += "<option>Italiano</option>";
    menu += "<option>Lituano</option>";
    menu += "<option>Maltés</option>";
    menu += "<option>Portugués</option>";
    menu += "<option>Romanés</option>";
    menu += "<option>Tailandés</option>";
    menu += "<option>Turco</option>";
    menu += "<option>Vietnamita</option>";
    menu += "<option>Yoruba</option>";
    menu += "</select>";
    edittools.innerHTML = menu + edittools.innerHTML;

    /* default subset from cookie */
    var s = parseInt( $.cookie('edittoolscharsubset') );
    if ( isNaN(s) ) s = 0;

    /* update dropdown control to value of cookie */
    document.getElementById('charSubsetControl').selectedIndex = s;

    /* display the subset indicated by the cookie */
    chooseCharSubset( s );
  }
}

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

$( customizeWiktionary );