MediaWiki:Common.js: различия между версиями

Материал из Emuverse
Нет описания правки
(Текущая версия из википедии)
Строка 1: Строка 1:
/*
importMW = function ( name ) {
Execute function on page load *********************************************
importScript( 'MediaWiki:' + name + '.js' );
  *
};
  *  Description: Wrapper around addOnloadHook() for backwards compatibility.
  *              Will be removed in the near future.
  */
/* Чтоб была возможность изменить поведение кнопки "+" (добавление новой темы) для страниц обсуждения */
addOnloadHook(function(){
  var plus = document.getElementById('ca-addsection');
  if (!plus) return;
  var custom = document.getElementById('add-custom-section');
  if (!custom) return;
  plus.firstChild.setAttribute('href', custom.getElementsByTagName('A')[0].href);
})
/**********************************************************************************/
function addLoadEvent( f ) { addOnloadHook( f ); }


/** Import module *************************************************************
importScript_ = importScript;
  *
importScript = function ( page, proj ) {
  *  Предложен [[Участник:Alex_Smotrov]], на основе аналогичной английской функции
if ( !proj ) {
  *
importScript_( page );
  *  Description: Includes a raw wiki page as javascript or CSS,  
} else {
  *              used for including user made modules.
if ( proj.indexOf( '.' ) === -1 ) {
  */
proj += '.wikipedia.org';
}
function importScript(page, lang) {
mw.loader.load( '//' + proj + '/w/index.php?title=' + mw.util.wikiUrlencode( page ) + '&action=raw&ctype=text/javascript' );
    var url = wgScriptPath + '/index.php?title='
}
                            + encodeURIComponent(page.replace(' ','_'))
};
                            + '&action=raw&ctype=text/javascript&dontcountme=s';
    if (lang) url = 'http://' + lang + '.wikipedia.org' + url;
    var s = document.createElement('script');
    s.src = url;
    s.type='text/javascript';
    document.getElementsByTagName('head')[0].appendChild(s);
}


/** Internet Explorer bug fix **************************************************
  */
if (window.showModalDialog && document.compatMode && document.compatMode == "CSS1Compat")
{
  var oldWidth;
  var docEl = document.documentElement;
  function fixIEScroll()
  {
    if (!oldWidth || docEl.clientWidth > oldWidth)
      doFixIEScroll();
    else
      setTimeout(doFixIEScroll, 1);
 
    oldWidth = docEl.clientWidth;
  }
  function doFixIEScroll() {
    docEl.style.overflowX = (docEl.scrollWidth - docEl.clientWidth < 4) ? "hidden" : "";
  }
  document.attachEvent("onreadystatechange", fixIEScroll);
  attachEvent("onresize", fixIEScroll);
}


/** Tooltips and access keys ***************************************************
mw.config.set( 'tableSorterCollation', { 'ё': 'е' } );
  */
ta = new Object();
ta["t-print"] = new Array("","Версия без кнопок, пригодная для распечатки");
ta["t-permalink"]          = new Array("","Ссылка на текущую версию этой статьи");


/** Interwiki links to featured articles ***************************************
  *
  *  Описание: Ставит звёздочки для избранных иноязычных статей, а заодно и даёт картинку для статуса ICQ
  */
function LinkFA()
{
  // iterate over all span-elements
  for(var i=0; a = document.getElementsByTagName("span")[i]; i++) {
      // if found a ICQ span
      if(a.className == "ICQ") {
            a.style.padding = "0 0 0 20px";
            a.style.backgroundImage = "url('http://status.icq.com/online.gif?icq="+a.id+"&img=5')";
            a.style.backgroundRepeat = "no-repeat";
      }
  }
}
addOnloadHook( LinkFA );


/* меняет текст вкладки «статья» на «заглавная», когда надо */
// Messages
var NavigationBarHide = '[скрыть]',
NavigationBarShow = '[показать]',
NavigationBarShowDefault = 2;


addOnloadHook(function(){
if ( /^en$/.test( mw.config.get( 'wgUserLanguage' ) ) ) {
  if(wgArticleId==4401||wgArticleId==23){var nstabmain=document.getElementById('ca-nstab-main').firstChild;if(nstabmain.textContent){nstabmain.textContent='Заглавная'}else{nstabmain.innerText='Заглавная'};}
importMW( 'Common-' + mw.config.get( 'wgUserLanguage' ) );
});
}
 
// Collapsiblе: [[ВП:СБ]]
 
function collapsibleTables( $content ) {
var $btn,
$a,
tblIdx = 0,
colTables = [],
$Tables = $content.find( 'table' );
 
    $Tables.each( function( i, table ) {
        if ( $(table).hasClass( 'collapsible' ) ) {
var $table = $( this ),
$row = $table.find( 'tr' ).first(),
$cell = $row.find( 'th' ).first();
if ( !$cell.length ) {
return;
}
$table.attr( 'id', 'collapsibleTable' + tblIdx );
$btn = $( '<span>' )
.css( {
'float': 'right',
'font-weight': 'normal',
'font-size': 'smaller'
} );
$a = $( '<a>' )
.attr( 'id', 'collapseButton' + tblIdx )
.attr( 'href', 'javascript:collapseTable(' + tblIdx + ');' )
.css( 'color', $cell.css( 'color' ) )
.text( NavigationBarHide )
.appendTo( $btn );
if ( $cell.contents().length ) {
$btn.insertBefore( $cell.contents().first() );
} else {
$btn.appendTo( $cell );
}
colTables[tblIdx++] = $table;
        }
} );
for ( var i = 0; i < tblIdx; i++ ) {
if ( colTables[i].hasClass( 'collapsed' ) ||
( tblIdx > NavigationBarShowDefault &&
colTables[i].hasClass( 'autocollapse' )
)
) {
collapseTable( i );
}
}
}
 
mw.hook( 'wikipage.content' ).add( collapsibleTables );


/* hasClass from en-wiki */
function collapseTable ( idx ) {
var $table = $( '#collapsibleTable' + idx ),
$rows = $table.children().children( 'tr' ),
$btn = $( '#collapseButton' + idx );
if ( !$table.length || !$rows.length || !$btn.length ) {
return false;
}


var hasClass = (function () {
var isShown = ( $btn.text() === NavigationBarHide ),
    var reCache = {};
cssDisplay = isShown ? 'none' : $rows.first().css( 'display' );
    return function (element, className) {
        return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className);
    };
})();


/** Collapsible tables *********************************************************
$btn.text( isShown ? NavigationBarShow : NavigationBarHide );
  *
$rows.slice( 1 ).each( function() {
  *  Description: Allows tables to be collapsed, showing only the header. See
$( this ).css( 'display', cssDisplay );
  *              [[Wikipedia:NavFrame]].
} );
  *  Maintainers: [[User:R. Koot]]
}
  */
var autoCollapse = 2;
var collapseCaption = "скрыть";
var expandCaption = "показать";
function collapseTable( tableIndex )
{
    var Button = document.getElementById( "collapseButton" + tableIndex );
    var Table = document.getElementById( "collapsibleTable" + tableIndex );
    if ( !Table || !Button ) {
        return false;
    }
    var Rows = Table.getElementsByTagName( "tr" );
    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" ) ) {
            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.setAttribute( "id", "collapseButton" + tableIndex );
            ButtonLink.setAttribute( "href", "javascript:collapseTable(" + tableIndex + ");" );
            ButtonLink.appendChild( ButtonText );
            Button.appendChild( document.createTextNode( "[" ) );
            Button.appendChild( ButtonLink );
            Button.appendChild( document.createTextNode( "]" ) );
            var Header = Tables[i].getElementsByTagName( "tr" )[0].getElementsByTagName( "th" )[0];
            /* only add button and increment count if there is a header row to work with */
            if (Header) {
                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) *************************************
function collapsibleDivs( $content ) {
  *
var navIdx = 0,
  *  Description: See [[Wikipedia:NavFrame]].
colNavs = [],
  *  Maintainers: UNMAINTAINED
i,
  */
$Divs = $content.find( 'div' );
  // set up the words in your language
$Divs.each( function( i, div ) {
  var NavigationBarHide = '[' + collapseCaption + ']';
        if ( $(div).hasClass( 'NavFrame' ) ) {
  var NavigationBarShow = '[' + expandCaption + ']';
var $navFrame = $( this );
 
$navFrame.attr( 'id', 'NavFrame' + navIdx );
  // set up max count of Navigation Bars on page,
var $a = $( '<a>' )
  // if there are more, all will be hidden
.addClass( 'NavToggle' )
  // NavigationBarShowDefault = 0; // all bars will be hidden
.attr( 'id', 'NavToggle' + navIdx )
  // NavigationBarShowDefault = 1; // on pages with more than 1 bar all bars will be hidden
.attr( 'href', 'javascript:collapseDiv(' + navIdx + ');' )
  var NavigationBarShowDefault = autoCollapse;
.text( NavigationBarHide );
 
$navFrame.children( '.NavHead' ).append( $a );
 
colNavs[navIdx++] = $navFrame;
  // shows and hides content and picture (if available) of navigation bars
        }
  // Parameters:
} );
  //    indexNavigationBar: the index of navigation bar to be toggled
for ( i = 0; i < navIdx; i++ ) {
  function toggleNavigationBar(indexNavigationBar)
if ( colNavs[i].hasClass( 'collapsed' ) ||
  {
( navIdx > NavigationBarShowDefault &&
    var NavToggle = document.getElementById("NavToggle" + indexNavigationBar);
!colNavs[i].hasClass( 'expanded' )
    var NavFrame = document.getElementById("NavFrame" + indexNavigationBar);
)
 
) {
    if (!NavFrame || !NavToggle) {
collapseDiv( i );
        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);
            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);
        }
    }
    // if more Navigation Bars found than Default: hide all
    if (NavigationBarShowDefault < indexNavigationBar) {
        for(
                var i=1;
                i<=indexNavigationBar;
                i++
        ) {
            toggleNavigationBar(i);
        }
    }
 
  }
 
  addOnloadHook( createNavigationBarToggleButton );


mw.hook( 'wikipage.content' ).add( collapsibleDivs );
/** Делаем ссылку "править" для нулевой секции *****************************************<nowiki>
*/
var disable_zero_section = 0;
function edit_zero_section()
{
  var  body = document.getElementById ('bodyContent');
  if (disable_zero_section != 1 && body.innerHTML.match ('class="editsection"')) {
    var  title = document.title.substr (0, document.title.lastIndexOf (' — '));
    if (typeof encodeURIComponent == 'function')
      title = encodeURIComponent (title);
    body.innerHTML = '<div class="editsection" id="ca-edit-0">[<a href="http://emuverse.ru/w/index.php?title=' + title + '&amp;action=edit&amp;section=0">править</a>]</div>' + body.innerHTML;
  }
}
addOnloadHook(edit_zero_section);


/*</nowiki>*/
function collapseDiv ( idx ) {
var $div = $( '#NavFrame' + idx ),
$btn = $( '#NavToggle' + idx );
if ( !$div.length || !$btn.length ) {
return false;
}
var isShown = ( $btn.text() === NavigationBarHide );
$btn.text( isShown ? NavigationBarShow : NavigationBarHide );
$div.children( '.NavContent,.NavPic' ).each( function() {
$( this ).css( 'display', isShown ? 'none' : 'block' );
} );
}


/** Расширенный поиск *****************************************<nowiki>
function checkEmptyCreatebox() {
** Автор: ru:User:Не А
$( 'form.createbox' ).on( 'submit', function() {
*/
if ( !$( this ).find( 'input.createboxInput' ).val() ) {
function SpecialSearchEnhanced()  
window.alert( 'Не указано название новой статьи!' );
{
return false;
    var mainNode = document.getElementsByTagName("form");
}
    if (!mainNode) return;
return true;
   
} );
    var searchValue = document.forms[0].search.value
}
var safeSearchValue = searchValue.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
    var firstForm = mainNode[0];


    var node = document.createElement('div');
   
    var googleSearch  = '<form action="http://www.google.com/custom" method="get" name="google" target="_blank" id="google">';
    googleSearch += '<input type="hidden" name="hl" value="ru" />';
    googleSearch += '<input type="hidden" name="domains" value="emuverse.ru" />';
    googleSearch += '<input type="hidden" name="q" maxlength="2048" value="' + safeSearchValue + '" />'
    googleSearch += '<input type="hidden" name="sitesearch" value="emuverse.ru" />'
    googleSearch += '<input type="button" value="Google по Emuverse" onclick="document.google.q.value = document.forms[0].search.value; this.form.submit();" style="width: 12em;" />'
    googleSearch += '</form>'
   
    var yandexSearch  = '<form action="http://www.yandex.ru/yandsearch" method="get" name="yandex" target="_blank" id="yandex">';
    yandexSearch += '<input type="hidden" name="text" maxlength="300" value="' + safeSearchValue + '" />';
    yandexSearch += '<input type="hidden" name="site" value="www.emuverse.ru" />';
    yandexSearch += '<input type="hidden" name="ras" value="1" />'
    yandexSearch += '<input type="hidden" name="site_manually"  value="true" />'
    yandexSearch += '<input type="hidden" name="server_name" value="Emuverse" />'
    yandexSearch += '<input type="button" value="Яндекс по Emuverse"  onclick="document.yandex.text.value = document.forms[0].search.value; this.form.submit();" style="width: 12em;" />'
    yandexSearch += '</form>'


    node.innerHTML = node.innerHTML + '<table style="margin-left: 75%;  padding-left:4px;"><tr><td>' + yandexSearch + '</td></tr><tr><td>' + googleSearch + '</td></tr></table>';
// Execution
       
mw.loader.using( 'mediawiki.util', function() {
    firstForm.parentNode.insertBefore(node, firstForm.nextSibling);
}


if (wgPageName == "Служебная:Search") { addOnloadHook(SpecialSearchEnhanced); }
if ( mw.config.get( 'wgCanonicalNamespace' ) === 'Special' ) {
if ( /^(Uplo|Sear|Stat|Spec|Abus|Prefe|Move|Watch|Newp|Log|Block$)/i.test( mw.config.get( 'wgCanonicalSpecialPageName' ) ) ) {
importMW( mw.config.get( 'wgCanonicalSpecialPageName' ) );
}


/*</nowiki>*/
} else {
switch ( mw.config.get( 'wgAction' ) ) {


/** "Technical restrictions" title fix *****************************************
case 'history':
  */
importMW( 'History' );
break;
// For pages that have something like Template:Lowercase, replace the title, but only if it is cut-and-pasteable as a valid wikilink.
// (for instance [[iPod]]'s title is updated.  <nowiki>But [[C#]] is not an equivalent wikilink, so [[C Sharp]] doesn't have its main title changed)</nowiki>
//
// The function looks for a banner like this: <nowiki>
// <div id="RealTitleBanner">    <!-- div that gets hidden -->
//  <span id="RealTitle">title</span>
// </div>
// </nowiki>An element with id=DisableRealTitle disables the function.
// similar to innerHTML, but only returns the text portions of the insides, excludes HTML
function pickUpText(aParentElement) {
  var str = "";
  function pickUpTextInternal(aElement) {
    var child = aElement.firstChild;
    while (child) {
      if (child.nodeType == 1)          // ELEMENT_NODE
        pickUpTextInternal(child);
      else if (child.nodeType == 3)    // TEXT_NODE
        str += child.nodeValue;
      child = child.nextSibling;
    }
  }
  pickUpTextInternal(aParentElement);
  return str;
}
var disableRealTitle = 0; // users can disable this by making this true from their monobook.js
addOnloadHook(function() {
try {
var realTitleBanner = document.getElementById("RealTitleBanner");
if (realTitleBanner && !document.getElementById("DisableRealTitle") && !disableRealTitle) {
var realTitle = document.getElementById("RealTitle");
if (realTitle) {
var realTitleHTML = realTitle.innerHTML;
realTitleText = pickUpText(realTitle);
var isPasteable = 0;
//var containsHTML = /</.test(realTitleHTML); // contains ANY HTML
var containsTooMuchHTML = /</.test( realTitleHTML.replace(/<\/?(sub|sup|small|big)>/gi, "") ); // contains HTML that will be ignored when cut-n-pasted as a wikilink
// calculate whether the title is pasteable
var verifyTitle = realTitleText.replace(/^ +/, ""); // trim left spaces
verifyTitle = verifyTitle.charAt(0).toUpperCase() + verifyTitle.substring(1, verifyTitle.length); // uppercase first character
// if the namespace prefix is there, remove it on our verification copy.  If it isn't there, add it to the original realValue copy.
if (wgNamespaceNumber != 0) {
if (wgCanonicalNamespace == verifyTitle.substr(0, wgCanonicalNamespace.length).replace(/ /g, "_") && verifyTitle.charAt(wgCanonicalNamespace.length) == ":") {
verifyTitle = verifyTitle.substr(wgCanonicalNamespace.length + 1);
} else {
realTitleText = wgCanonicalNamespace.replace(/_/g, " ") + ":" + realTitleText;
realTitleHTML = wgCanonicalNamespace.replace(/_/g, " ") + ":" + realTitleHTML;
}
}
// verify whether wgTitle matches
verifyTitle = verifyTitle.replace(/^ +/, "").replace(/ +$/, ""); // trim left and right spaces
verifyTitle = verifyTitle.replace(/_/g, " "); // underscores to spaces
verifyTitle = verifyTitle.charAt(0).toUpperCase() + verifyTitle.substring(1, verifyTitle.length); // uppercase first character
isPasteable = (verifyTitle == wgTitle);
var h1 = document.getElementsByTagName("h1")[0];
if (h1 && isPasteable) {
h1.innerHTML = containsTooMuchHTML ? realTitleText : realTitleHTML;
if (!containsTooMuchHTML)
realTitleBanner.style.display = "none";
}
document.title = realTitleText + " — Википедия";
}
}
} catch (e) {
/* Something went wrong. */
}
});


/* Замена неправильного заголовка правильным by SergV *****************************************
case 'delete':
*/
importMW( 'Deletepage' );
 
break;
  // Все неправильные заголовки
  title_restr_alerts = ["trestrictions_replace", "trestrictions_alert"];


  // Только шаблон title
case 'edit':
  //title_restr_alerts = ["trestrictions_replace"];
case 'submit':
importMW( 'Editpage' );
// and continue with the default: view, purge


  function display_correct_title () {
default:
    var title_restr_alert1, a1;
$( checkEmptyCreatebox );
    if (document.getElementsByTagName && document.getElementById) {
mw.loader.load( '//meta.wikimedia.org/w/index.php?title=MediaWiki:Wikiminiatlas.js&action=raw&ctype=text/javascript' );
      for(var i=0; i < title_restr_alerts.length; i++) {
if ( location.protocol === 'https:' ) {
        title_restr_alert1 = title_restr_alerts[i];
importMW( 'Secure' );
        a1 = document.getElementById(title_restr_alert1);
}
        if(a1) {
if ( navigator.platform.indexOf( 'Win' ) !== -1 ) {
          ct = document.getElementById("trestrictions_correct");
mw.util.addCSS( '.IPA, .Unicode { font-family: "Arial Unicode MS", "Lucida Sans Unicode"; }' );
          if(ct) {
}
            document.getElementsByTagName("h1")[0].innerHTML  = ct.innerHTML;
 
            a1.style.display = "none";
switch ( mw.config.get( 'wgNamespaceNumber' ) ) {
            document.getElementById("trestrictions_replaced").style.display = "block";
case 0:
          }
case 100:
          break;
importMW( 'Osm' );
        }
if ( mw.config.get( 'wgIsMainPage' ) ) {
      }
importMW( 'Mainpage' );
    }
}
  }
break;
case 6:
importMW( 'Filepage' );
break;
}
}
}
 
importMW( 'Sidebar-related' );
 
if ( !mw.config.get( 'wgUserName' ) ) {
mw.util.addCSS( '#mw-fr-revisiontag { display:none }' ); // hide FlaggedRevs
}
 
 
// Helper script for .hlist class in common.css
// Author: [[:en:User:Edokter]]
if ( $.client.profile().name == 'msie' ) {
// Add pseudo-selector class to last child list items in IE 8
if ( $.client.profile().versionBase == '8' ) {
$( '.hlist' ).find( 'dd:last-child, dt:last-child, li:last-child' )
.addClass( 'hlist-last-child' );
}
}
 
// ВП:СО, кроме статей  В Контакте, Одноклассники и Facebook
if ( mw.config.get( 'wgArticleId' ) !== 639373 &&
mw.config.get( 'wgArticleId' ) !== 932117 &&
mw.config.get( 'wgArticleId' ) !== 1297302 &&
mw.config.get( 'wgArticleId' ) !== 25133866
) {
importMW( 'Wikibugs' );
}
 
 
// Iwiki sorting
if ( !mw.config.get( 'wgUserName' ) ||
( mw.config.get( 'wgUserName' ) &&
( ( mw.config.get( 'wgLangPrefs' ) === null ? false : true ) ||
( mw.config.get( 'wgAddLangHints' ) === null ? false : mw.config.get( 'wgAddLangHints' ) ) ||
( mw.config.get( 'wgUseUserLanguage' ) === null ? false : mw.config.get( 'wgUseUserLanguage' ) ) ) )
) {
importMW( 'Interwiki-links' );
}


addOnloadHook(display_correct_title);
} );


/* Другое  *****************************************
*/
window.przyciskiOpisDone = false;
var auto_comment = 0;


/* подгрузка файла со скриптами для редактирования  *****************************************
// Extra scripts
*/
if (document.URL.indexOf("action=edit") > 0 || document.URL.indexOf("action=submit") > 0)
{
        if (wgCanonicalNamespace != "Special")
        {
                document.write('<script type="text/javascript" src="/w/index.php?title=MediaWiki:Onlyifediting.js&action=raw&ctype=text/javascript&dontcountme=s"></script>');
        }
}


var withJS = location.href.match( /[&?]withjs=((mediawiki:)?([^&#]+))/i );
function addRationaleTemplate(){
if ( withJS ) {
var desc = document.getElementById('wpUploadDescription')
importScript_( 'MediaWiki:' + withJS[3] );
var temp = document.getElementById('rationale')
if(!desc || !temp) return
if (desc.value.indexOf(temp.innerHTML.substring(0,8)) == -1){
  desc.value += '\n' + temp.innerHTML
  desc.rows = 15
}
}
}
if (wgCanonicalNamespace == 'Special' && wgCanonicalSpecialPageName == 'Upload')
addOnloadHook(uploadPage);


/** Обработка сортировки чисел с плавающей точкой с разделителем-запятой
var execJS = document.getElementById( 'executeJS' );
  * Взято из шведской Википедии, автор - [[:sv:Användare:Skagedal]]
if ( execJS ) {
  *
$.each( execJS.className.split( ' ' ), function ( i, sc ) {
  */
sc = $.trim( sc.replace( /[^\w ]/g, '' ) );
function ts_parseFloat(num) {
if ( sc ) {
        if (!num) return 0;
importMW( 'Script/' + sc );
        num = num.replace(/\./g, "");
}
        num = num.replace(/,/, ".");
} );
        num = parseFloat(num);
}
        return (isNaN(num) ? 0 : num);
}

Версия от 17:50, 21 декабря 2015

importMW = function ( name ) {
	importScript( 'MediaWiki:' + name + '.js' );
};

importScript_ = importScript;
importScript = function ( page, proj ) {
	if ( !proj ) {
		importScript_( page );
	} else {
		if ( proj.indexOf( '.' ) === -1 ) {
			proj += '.wikipedia.org';
		}
		mw.loader.load( '//' + proj + '/w/index.php?title=' + mw.util.wikiUrlencode( page ) + '&action=raw&ctype=text/javascript' );
	}
};


mw.config.set( 'tableSorterCollation', { 'ё': 'е' } );


// Messages
var NavigationBarHide = '[скрыть]',
	NavigationBarShow = '[показать]',
	NavigationBarShowDefault = 2;

if ( /^en$/.test( mw.config.get( 'wgUserLanguage' ) ) ) {
	importMW( 'Common-' + mw.config.get( 'wgUserLanguage' ) );
}

// Collapsiblе: [[ВП:СБ]]

function collapsibleTables( $content ) {
	var $btn,
		$a,
		tblIdx = 0,
		colTables = [],
		$Tables = $content.find( 'table' );

    $Tables.each( function( i, table ) {
        if ( $(table).hasClass( 'collapsible' ) ) {
			var $table = $( this ),
				$row = $table.find( 'tr' ).first(),
				$cell = $row.find( 'th' ).first();
			if ( !$cell.length ) {
				return;
			}
			$table.attr( 'id', 'collapsibleTable' + tblIdx );
			$btn = $( '<span>' )
				.css( {
					'float': 'right',
					'font-weight': 'normal',
					'font-size': 'smaller'
				} );
			$a = $( '<a>' )
				.attr( 'id', 'collapseButton' + tblIdx )
				.attr( 'href', 'javascript:collapseTable(' + tblIdx + ');' )
				.css( 'color', $cell.css( 'color' ) )
				.text( NavigationBarHide )
				.appendTo( $btn );
			if ( $cell.contents().length ) {
				$btn.insertBefore( $cell.contents().first() );
			} else {
				$btn.appendTo( $cell );
			}
			colTables[tblIdx++] = $table;
        }
	} );
	for ( var i = 0; i < tblIdx; i++ ) {
		if ( colTables[i].hasClass( 'collapsed' ) ||
			( tblIdx > NavigationBarShowDefault &&
				colTables[i].hasClass( 'autocollapse' )
			)
		) {
			collapseTable( i );
		}
	}
}

mw.hook( 'wikipage.content' ).add( collapsibleTables );

function collapseTable ( idx ) {
	var $table = $( '#collapsibleTable' + idx ),
		$rows = $table.children().children( 'tr' ),
		$btn = $( '#collapseButton' + idx );
	if ( !$table.length || !$rows.length || !$btn.length ) {
		return false;
	}

	var isShown = ( $btn.text() === NavigationBarHide ),
		cssDisplay = isShown ? 'none' : $rows.first().css( 'display' );

	$btn.text( isShown ? NavigationBarShow : NavigationBarHide );
	$rows.slice( 1 ).each( function() {
		$( this ).css( 'display', cssDisplay );
	} );
}

function collapsibleDivs( $content ) {
	var navIdx = 0,
		colNavs = [],
		i,
		$Divs = $content.find( 'div' );
	
	$Divs.each( function( i, div ) {
        if ( $(div).hasClass( 'NavFrame' ) ) {	
			var $navFrame = $( this );
			$navFrame.attr( 'id', 'NavFrame' + navIdx );
			var $a = $( '<a>' )
				.addClass( 'NavToggle' )
				.attr( 'id', 'NavToggle' + navIdx )
				.attr( 'href', 'javascript:collapseDiv(' + navIdx + ');' )
				.text( NavigationBarHide );
			$navFrame.children( '.NavHead' ).append( $a );
			colNavs[navIdx++] = $navFrame;
        }
	} );
	for ( i = 0; i < navIdx; i++ ) {
		if ( colNavs[i].hasClass( 'collapsed' ) ||
			( navIdx > NavigationBarShowDefault &&
				!colNavs[i].hasClass( 'expanded' )
			)
		) {
			collapseDiv( i );
		}
	}
}

mw.hook( 'wikipage.content' ).add( collapsibleDivs );

function collapseDiv ( idx ) {
	var $div = $( '#NavFrame' + idx ),
		$btn = $( '#NavToggle' + idx );
	if ( !$div.length || !$btn.length ) {
		return false;
	}
	var isShown = ( $btn.text() === NavigationBarHide );
	$btn.text( isShown ? NavigationBarShow : NavigationBarHide );
	$div.children( '.NavContent,.NavPic' ).each( function() {
		$( this ).css( 'display', isShown ? 'none' : 'block' );
	} );
}

function checkEmptyCreatebox() {
	$( 'form.createbox' ).on( 'submit', function() {
		if ( !$( this ).find( 'input.createboxInput' ).val() ) {
			window.alert( 'Не указано название новой статьи!' );
			return false;
		}
		return true;
	} );
}


// Execution
mw.loader.using( 'mediawiki.util', function() {

	if ( mw.config.get( 'wgCanonicalNamespace' ) === 'Special' ) {
		if ( /^(Uplo|Sear|Stat|Spec|Abus|Prefe|Move|Watch|Newp|Log|Block$)/i.test( mw.config.get( 'wgCanonicalSpecialPageName' ) ) ) {
			importMW( mw.config.get( 'wgCanonicalSpecialPageName' ) );
		}

	} else {
		switch ( mw.config.get( 'wgAction' ) ) {

			case 'history':
		 		importMW( 'History' );
		 		break;

			case 'delete':
				importMW( 'Deletepage' );
				break;

			case 'edit':
			case 'submit':
				importMW( 'Editpage' );
				// and continue with the default: view, purge

			default:
				$( checkEmptyCreatebox );
				mw.loader.load( '//meta.wikimedia.org/w/index.php?title=MediaWiki:Wikiminiatlas.js&action=raw&ctype=text/javascript' );
				if ( location.protocol === 'https:' ) {
					importMW( 'Secure' );
				}
				if ( navigator.platform.indexOf( 'Win' ) !== -1 ) {
					mw.util.addCSS( '.IPA, .Unicode { font-family: "Arial Unicode MS", "Lucida Sans Unicode"; }' );
				}

				switch ( mw.config.get( 'wgNamespaceNumber' ) ) {
					case 0:
					case 100:
						importMW( 'Osm' );
						if ( mw.config.get( 'wgIsMainPage' ) ) {
							importMW( 'Mainpage' );
						}
						break;
					case 6:
						importMW( 'Filepage' );
						break;
				}
		}
	}

	importMW( 'Sidebar-related' );

	if ( !mw.config.get( 'wgUserName' ) ) {
		mw.util.addCSS( '#mw-fr-revisiontag { display:none }' ); // hide FlaggedRevs
	}


	// Helper script for .hlist class in common.css
	// Author: [[:en:User:Edokter]]
	if ( $.client.profile().name == 'msie' ) {
		// Add pseudo-selector class to last child list items in IE 8
		if ( $.client.profile().versionBase == '8' ) {
			$( '.hlist' ).find( 'dd:last-child, dt:last-child, li:last-child' )
				.addClass( 'hlist-last-child' );
		}
	}

	// ВП:СО, кроме статей  В Контакте, Одноклассники и Facebook
	if ( mw.config.get( 'wgArticleId' ) !== 639373 &&
		mw.config.get( 'wgArticleId' ) !== 932117 &&
		mw.config.get( 'wgArticleId' ) !== 1297302 &&
		mw.config.get( 'wgArticleId' ) !== 25133866
	) {
		importMW( 'Wikibugs' );
	}


	// Iwiki sorting
	if ( !mw.config.get( 'wgUserName' ) ||
		( mw.config.get( 'wgUserName' ) &&
			( ( mw.config.get( 'wgLangPrefs' ) === null ? false : true ) ||
				( mw.config.get( 'wgAddLangHints' ) === null ? false : mw.config.get( 'wgAddLangHints' ) ) ||
				( mw.config.get( 'wgUseUserLanguage' ) === null ? false : mw.config.get( 'wgUseUserLanguage' ) ) ) )
	) {
		importMW( 'Interwiki-links' );
	}

} );


// Extra scripts

var withJS = location.href.match( /[&?]withjs=((mediawiki:)?([^&#]+))/i );
if ( withJS ) {
	importScript_( 'MediaWiki:' + withJS[3] );
}

var execJS = document.getElementById( 'executeJS' );
if ( execJS ) {
	$.each( execJS.className.split( ' ' ), function ( i, sc ) {
		sc = $.trim( sc.replace( /[^\w ]/g, '' ) );
		if ( sc ) {
			importMW( 'Script/' + sc );
		}
	} );
}