MediaWiki:Common.js
Перейти к навигации
Перейти к поиску
Замечание. Возможно, после сохранения вам придётся очистить кэш своего браузера, чтобы увидеть изменения.
- Firefox / Safari: Удерживая клавишу Shift, нажмите на панели инструментов Обновить либо нажмите Ctrl-F5 или Ctrl-R (⌘-R на Mac)
- Google Chrome: Нажмите Ctrl-Shift-R (⌘-Shift-R на Mac)
- Internet Explorer: Удерживая Ctrl, нажмите Обновить либо нажмите Ctrl-F5
- Opera: Перейдите в Menu → Настройки (Opera → Настройки на Mac), а затем Безопасность → Очистить историю посещений → Кэшированные изображения и файлы
/* Размещённый здесь код JavaScript будет загружаться пользователям при обращении к каждой странице */
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'
importScriptURI('//'+proj+'/w/index.php?action=raw&ctype=text/javascript&title='+mw.util.wikiUrlencode(page))
}
}
mw.config.set( 'tableSorterCollation', {'ё':'е'} )
//Messages
var listFA = {
fa:'Эта статья является избранной',
fl:'Этот список или портал является избранным',
ga:'Эта статья является хорошей'}
var textFA = ' в другом языковом разделе'
var zeroSectionTip = 'Править введение'
var NavigationBarHide = '[скрыть]'
var NavigationBarShow = '[показать]'
var NavigationBarShowDefault = 2
if( /^en$/.test(wgUserLanguage) ) importMW('Common-' + wgUserLanguage)
function LinkFA(){
var ll, s
$('#p-lang li').each( function(i, iw){
ll = iw.className.split(' ')[0] + '-'
for( var s in listFA )
if( document.getElementById(ll + s) )
$( iw )
.addClass( s.toUpperCase() )
.attr( 'title', listFA[s] + textFA )
})
}
function editZeroSection(){
if( !wgArticleId ) return
mw.util.$content.find('h2')
.children('.editsection:first')
.clone().prependTo('#bodyContent')
.css('float','right')
.find('a')
.attr('title', zeroSectionTip)
.attr('href', wgScript + '?title='+mw.util.wikiUrlencode(wgPageName) + '&action=edit§ion=0' )
}
//Collapsiblе: [[ВП:СБ]]
var hasClass = (function (){
var reCache = {}
return function (element, className){
return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className)
}
})()
function collapsibleTables(){
var Table, HRow, HCell, btn, a, tblIdx = 0, colTables = []
var allTables = document.getElementsByTagName('table')
for (var i=0; Table = allTables[i]; i++){
if (!hasClass(Table, 'collapsible')) continue
if (!(HRow=Table.rows[0])) continue
if (!(HCell=HRow.getElementsByTagName('th')[0])) continue
Table.id = 'collapsibleTable' + tblIdx
btn = document.createElement('span')
btn.style.cssText = 'float:right; text-align:right; width:6em; font-weight:normal'
a = document.createElement('a')
a.id = 'collapseButton' + tblIdx
a.href = 'javascript:collapseTable(' + tblIdx + ');'
a.style.color = HCell.style.color
a.appendChild(document.createTextNode(NavigationBarHide))
btn.appendChild(a)
HCell.insertBefore(btn, HCell.childNodes[0])
colTables[tblIdx++] = Table
}
for (var i=0; i < tblIdx; i++)
if ((tblIdx > NavigationBarShowDefault && hasClass(colTables[i], 'autocollapse')) || hasClass(colTables[i], 'collapsed'))
collapseTable(i)
}
function collapseTable (idx){
var Table = document.getElementById('collapsibleTable' + idx)
var btn = document.getElementById('collapseButton' + idx)
if (!Table || !btn) return false
var Rows = Table.rows
var isShown = (btn.firstChild.data == NavigationBarHide)
btn.firstChild.data = isShown ? NavigationBarShow : NavigationBarHide
var disp = isShown ? 'none' : Rows[0].style.display
for (var i=1; i < Rows.length; i++)
Rows[i].style.display = disp
}
function collapsibleDivs(){
var navIdx = 0, colNavs = [], i, NavFrame
var divs = document.getElementById('content').getElementsByTagName('div')
for (i=0; NavFrame = divs[i]; i++) {
if (!hasClass(NavFrame, 'NavFrame')) continue
NavFrame.id = 'NavFrame' + navIdx
var a = document.createElement('a')
a.className = 'NavToggle'
a.id = 'NavToggle' + navIdx
a.href = 'javascript:collapseDiv(' + navIdx + ');'
a.appendChild(document.createTextNode(NavigationBarHide))
for (var j=0; j < NavFrame.childNodes.length; j++)
if (hasClass(NavFrame.childNodes[j], 'NavHead'))
NavFrame.childNodes[j].appendChild(a)
colNavs[navIdx++] = NavFrame
}
for (i=0; i < navIdx; i++)
if ((navIdx > NavigationBarShowDefault && !hasClass(colNavs[i], 'expanded')) || hasClass(colNavs[i], 'collapsed'))
collapseDiv(i)
}
function collapseDiv(idx) {
var div = document.getElementById('NavFrame' + idx)
var btn = document.getElementById('NavToggle' + idx)
if (!div || !btn) return false
var isShown = (btn.firstChild.data == NavigationBarHide)
btn.firstChild.data = isShown ? NavigationBarShow : NavigationBarHide
var disp = isShown ? 'none' : 'block'
for (var child = div.firstChild; child != null; child = child.nextSibling)
if (hasClass(child, 'NavPic') || hasClass(child, 'NavContent'))
child.style.display = disp
}
//Execution
mw.loader.using( 'mediawiki.util', function() {
if (wgCanonicalNamespace == 'Special'){
if (/^(Uplo|Sear|Stat|Spec|Abus|Prefe|Move|Watch|Newp|Log)/i.test(wgCanonicalSpecialPageName))
importMW(wgCanonicalSpecialPageName)
}else switch (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:
$(editZeroSection)
addOnloadHook(collapsibleDivs)
addOnloadHook(collapsibleTables)
mw.loader.load('//meta.wikimedia.org/w/index.php?title=MediaWiki:Wikiminiatlas.js&action=raw&ctype=text/javascript&smaxage=21600&maxage=86400')
if( document.location && document.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( wgNamespaceNumber ){
case 0: case 100:
$(LinkFA)
importMW('Osm')
if( wgArticleId==4401 ) importMW('Mainpage')
break
case 6:
importMW('Filepage')
break
}
}
if( !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' );
}
/* Generate interpuncts and parens for IE < 8 */
if ( $.client.profile().versionBase < '8' ) {
$( '.hlist' ).find( 'dt + dd, dt + dt' ).prev()
.append( '<b>:</b> ' );
$( '.hlist' ).find( 'dd + dd, dd + dt, li + li' ).prev()
.append( '<b>•</b> ' );
$( '.hlist' ).find( 'dl dl, ol ol, ul ul' )
.prepend( '( ' ).append( ') ' );
}
}
// ВП:СО, кроме статей В Контакте, Одноклассники и Facebook
if (wgArticleId!=639373 && wgArticleId!=932117 && wgArticleId!=1297302 && wgArticleId!=25133866)
importMW('Wikibugs')
// iwiki sorting
if (!wgUserName
|| (wgUserName
&& (((typeof wgLangPrefs == 'undefined') ? false : true)
|| ((typeof wgAddLangHints == 'undefined') ? false : wgAddLangHints)
|| ((typeof wgUseUserLanguage == 'undefined') ? false : wgUseUserLanguage))))
importMW('Interwiki-links');
})
//extra scripts
var withJS = document.URL.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)
})
/* Any JavaScript here will be loaded for all users on every page load. */
/* Hook that enables collapsing objects.
* Added 7/13/2008 by WhiteMystery (misterioblanco@gmail.com) */
addOnloadHook(createToggleLinks);
/* Function that creates collapsing objects and toggle links.
* Added 7/13/2008 by WhiteMystery (misterioblanco@gmail.com) */
function createToggleLinks() {
var stateArray = new Array();
var allObjects = document.getElementsByTagName('span');
var rCollapsingObject = new RegExp("^co;(.+?);(.+?);(.+?);(.+?)(;(.+?))?$");
for ( var i = 0; i < allObjects.length; i++ ) {
if ( rCollapsingObject.test(allObjects[i].className) ) {
var collapsingInformation = rCollapsingObject.exec(allObjects[i].className);
var collapseText = collapsingInformation[1];
var expandText = collapsingInformation[2];
var initialState = collapsingInformation[3];
var targetClass = collapsingInformation[4];
var linkColor = collapsingInformation[6];
var toggleLink = document.createElement("a");
if ( initialState == "0" ) {
toggleLink.appendChild(document.createTextNode(expandText));
stateArray[targetClass] = "none";
}
else {
toggleLink.appendChild(document.createTextNode(collapseText));
stateArray[targetClass] = "inline";
}
toggleLink.setAttribute("href", "javascript:toggleCollapse('" + targetClass + "','" + collapseText + "','" + expandText + "')");
if ( linkColor != undefined && linkColor != "undefined" && linkColor != "" )
toggleLink.style.color = linkColor;
allObjects[i].innerHTML = "";
allObjects[i].appendChild(toggleLink);
}
else if ( allObjects[i].className == "morphMaster" ) {
var spanID = allObjects[i].getAttribute("id");
var targetID = spanID.substr(0, spanID.length - 6);
var counter = 1;
// Create forward and backward paging if the paging elements exist
if ( returnObjById(targetID + "LinkNext") && returnObjById(targetID + "LinkPrev") && returnObjById(targetID + "Content1") ) {
// Create the forward link
var nextLink = document.createElement("a");
nextLink.appendChild(document.createTextNode(returnObjById(targetID + "LinkNext").innerHTML));
nextLink.setAttribute("href", "javascript:morphForward('" + targetID + "')");
returnObjById(targetID + "LinkNext").innerHTML = "";
returnObjById(targetID + "LinkNext").appendChild(nextLink, 0);
// Create the backward link
var prevLink = document.createElement("a");
prevLink.appendChild(document.createTextNode(returnObjById(targetID + "LinkPrev").innerHTML));
prevLink.setAttribute("href", "javascript:morphBackward('" + targetID + "')");
returnObjById(targetID + "LinkPrev").innerHTML = "";
returnObjById(targetID + "LinkPrev").appendChild(prevLink, 0);
// Initialize content panes
while ( returnObjById(targetID + "Content" + counter) ) {
if ( counter == 1 )
returnObjById(targetID + "Content" + counter).style.display = "inline";
else
returnObjById(targetID + "Content" + counter).style.display = "none";
counter++;
}
}
counter = 1;
// Whether or not there is paging, generate normal links
while ( returnObjById(targetID + "Link" + counter) && returnObjById(targetID + "Content" + counter) ) {
var morphLink = document.createElement("a");
morphLink.appendChild(document.createTextNode(returnObjById(targetID + "Link" + counter).innerHTML));
morphLink.setAttribute("href", "javascript:performMorph('" + targetID + "','" + counter + "')");
returnObjById(targetID + "Link" + counter).innerHTML = "";
returnObjById(targetID + "Link" + counter).appendChild(morphLink, 0);
// Initialize content panes
if ( counter == 1 )
returnObjById(targetID + "Content" + counter).style.display = "inline";
else
returnObjById(targetID + "Content" + counter).style.display = "none";
counter++;
}
allObjects[i].innerHTML = "1";
allObjects[i].style.display = "none";
}
}
// Set state of appropriate objects
allObjects = document.getElementsByTagName('*');
for ( var i = 0; i < allObjects.length; i++ ) {
if ( stateArray[allObjects[i].className] )
allObjects[i].style.display = stateArray[allObjects[i].className];
}
}
/* Function that toggles collapsing objects.
* Added 7/13/2008 by WhiteMystery (misterioblanco@gmail.com) */
function toggleCollapse(targetClass, collapseText, expandText) {
var allObjects = document.getElementsByTagName('*');
var rCollapsingObject = new RegExp("^co;(.+?);(.+?);(.+?);" + targetClass + "(;(.+?))?$");
var linkType;
for ( var i = 0; i < allObjects.length; i++ ) {
if ( allObjects[i].className == targetClass ) {
if ( allObjects[i].style.display == "none" ) {
allObjects[i].style.display = "inline";
linkType = "Collapse";
}
else {
allObjects[i].style.display = "none";
linkType = "Expand";
}
}
}
allObjects = document.getElementsByTagName('span');
for ( var i = 0; i < allObjects.length; i++ ) {
if ( rCollapsingObject.test(allObjects[i].className) ) {
var collapsingInformation = rCollapsingObject.exec(allObjects[i].className);
var collapseText = collapsingInformation[1];
var expandText = collapsingInformation[2];
var linkColor = collapsingInformation[5];
var toggleLink = document.createElement("a");
if ( linkType == "Expand" )
toggleLink.appendChild(document.createTextNode(expandText));
else if ( linkType == "Collapse" )
toggleLink.appendChild(document.createTextNode(collapseText));
toggleLink.setAttribute("href", "javascript:toggleCollapse('" + targetClass + "','" + collapseText + "','" + expandText + "')");
if ( linkColor != undefined && linkColor != "undefined" && linkColor != "" )
toggleLink.style.color = linkColor;
allObjects[i].innerHTML = "";
allObjects[i].appendChild(toggleLink);
}
}
}
/* Functions that perform the morph operations.
* Added 8/13/2008 by WhiteMystery (misterioblanco@gmail.com) */
function performMorph(targetID, targetNumber) {
var counter = 1;
while ( returnObjById(targetID + "Content" + counter) ) {
if ( counter == targetNumber )
returnObjById(targetID + "Content" + counter).style.display = "block";
else
returnObjById(targetID + "Content" + counter).style.display = "none";
counter++;
}
returnObjById(targetID + "Master").innerHTML = targetNumber;
}
function morphForward(targetID) {
var nextPane = parseInt(returnObjById(targetID + "Master").innerHTML) + 1;
if ( returnObjById(targetID + "Content" + nextPane) )
performMorph(targetID, nextPane);
else
performMorph(targetID, "1");
}
function morphBackward(targetID) {
var prevPane = parseInt(returnObjById(targetID + "Master").innerHTML) - 1;
if ( prevPane > 0 )
performMorph(targetID, prevPane);
else {
var maxIndex = 1;
while ( returnObjById(targetID + "Content" + maxIndex) )
maxIndex++;
performMorph(targetID, maxIndex - 1);
}
}
/* Function that returns an object by ID for various browsers
* Taken from http://www.netlobo.com/javascript_get_element_id.html */
function returnObjById( id ) {
if (document.getElementById)
var returnVar = document.getElementById(id);
else if (document.all)
var returnVar = document.all[id];
else if (document.layers)
var returnVar = document.layers[id];
return returnVar;
}
//mw.loader.load('http://code.jquery.com/jquery-1.7.2.min.js');
if(wgAction == 'edit' || wgAction == 'submit') {
importScript('MediaWiki:Editpage.js');
}
if(wgAction == 'view' || wgAction == 'submit') {
importScript('MediaWiki:Collapsebuttons.js');
}
function sysopProtectPage(){
var inp = document.getElementById('mwProtect-level-edit')
if (inp) addHandler(inp, 'change', noMoveAutoconfirmedProtection)
function noMoveAutoconfirmedProtection(){
var inp = document.getElementById('mwProtectUnchained')
if (!inp || inp.checked) return
inp = document.getElementById('mwProtect-level-move')
if (inp && inp.selectedIndex==1) inp.selectedIndex = 0
inp = document.getElementById('mwProtect-level-delete')
if (inp && inp.selectedIndex==1) inp.selectedIndex = 0
}
}
$(sysopProtectPage);
function newSectionLink(){
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)
}
/* Авторы: разработчики Викиреальности с некоторой помощью Mithgol the Webmaster */
$(function() {
$('.jnav').each(function(i,e) {
$(this).data('i', i+1).click(function() {
var $this = $(this),
$jnavb = $('#jnavb-' + $this.data('i'));
if( $this.hasClass('jnav-inactive') ) {
$('.jnav-active').removeClass('jnav-active').addClass('jnav-inactive');
$('.jnavb').slideUp(250);
$this.removeClass('jnav-inactive').addClass('jnav-active');
$jnavb.slideDown(300);
} else {
$this.removeClass('jnav-active').addClass('jnav-inactive');
$jnavb.slideUp(300);
}
return false;
});
});
if($('.jnavpm').width() > 0)
{
$('.jnavpm').each(function(i,e) {
$(this).data('i', i+1).click(function() {
var $this = $(this), $jnavb = $('#jnavb-' + $this.data('i'));
if( $this.hasClass('jnavpm-inactive') ) {
$('.jnavpm-active').removeClass('jnavpm-active').addClass('jnavpm-inactive');
$('.jnavb').slideUp(250);
$this.removeClass('jnavpm-inactive').addClass('jnavpm-active');
$jnavb.slideDown(300);
} else {
$this.removeClass('jnavpm-active').addClass('jnavpm-inactive');
$jnavb.slideUp(300);
}
return false;
});
});
}
});
/* Автор Tachikoma, доработано руководством Викиреальности */
$(function() {
if(wgUserName != null && typeof jsForceNewRefs == 'undefined') return;
if(!($('ol.references').size())) return;
$('ol.references').before($('<a href="#">[показать примечания]</a>').click(
function(e){e.preventDefault(); $('ol.references').toggle()})).hide();
$('.reference a').live('click', function(e) {
e.preventDefault();
var x = $(this), iscurrent = x.hasClass('curreference'), i = $('.fref').hide(250);
$('.curreference').removeClass('curreference');
if (iscurrent) return;
var par = x.parent(), o = par.offset(), l = o.left, t = o.top+13;
var b = $('body'), mh = b.height(), mw = b.width();
var c=$(x.attr('href')).clone().find('a:first').remove().end().html();
x.addClass('areference').addClass('curreference');
if (!i.size()) i = $('<div/>').addClass('fref');
c=c.replace(/↑/,'').replace(/<sup>.*<\/sup> /g,'').replace(/^ /,'');
i.appendTo(b).queue(function() {
i.empty().append(c).css({ 'left': l-((l+i.width() >= mw) && i.width()),
'top': t-((t+i.height() >= mh) && (i.height()+24)) }).dequeue()
}).show(350);
});
$(window).click(function(e) {
if (!($(e.target).hasClass('areference') || $(e.target).parents().andSelf().hasClass('tooltip'))) {
$('.tooltip').hide(350); $('.curreference').removeClass('curreference')
}
});
});
function showAndHideReferences() {
if (referencesBlock = document.querySelector("ol.references")) {
referencesBlock.style.display = "none";
var showAndHideRefBlock = document.createElement('p');
var showRefText = "Показать примечания";
var hideRefText = "Спрятать примечания";
showAndHideRefBlock.innerHTML = showRefText;
showAndHideRefBlock.style.cssText = "cursor:pointer;color:#2B587A;background-color:#F7F7F7;padding:5px 20px;width:150px;font-family:Tahoma,Arial;font-size:12px;border:1px solid #DAE1E8;font-weight:bold;";
var contentBlock = document.querySelector("div#mw-content-text");
contentBlock.insertBefore(showAndHideRefBlock,referencesBlock);
showAndHideRefBlock.onclick = showAndHideRefList;
}
function showAndHideRefList() {
if (showAndHideRefBlock.innerHTML == showRefText) {
showAndHideRefBlock.innerHTML = hideRefText;
referencesBlock.style.display = "block";
} else {
showAndHideRefBlock.innerHTML = showRefText;
referencesBlock.style.display = "none";
}
}
}
/* Morph LM Edition BEGIN */
function createMorphObjects() {
var morphTargets = new Array(), morphLinks = new Array(), currentMorph = new Array();
function morphHandler(cont, num) {
return function() {
currentMorph[cont].curr = num;
var t = morphTargets[cont];
var l = morphLinks[cont];
for(i in t) if(currentMorph[cont].ms != null) t[i].style.display = t[i].className.match(l[num].className.replace(/.*morphlink\s+morph(\S+).*/, '$1'))? "" : "none"; else t[i].style.display = i==num ? "" : "none";
var h = currentMorph[cont].hilight, d = currentMorph[cont].defstyle;
for(i in l) l[i].setAttribute('style', (i!=num)?d:h);
};
};
function morphNext(cont) {
return function() {
var t = currentMorph[cont];
morphHandler(cont, t.curr<(t.max-1)?t.curr+1:0)();
}
}
function morphPrev(cont) {
return function() {
var t = currentMorph[cont];
morphHandler(cont, t.curr>0?t.curr-1:t.max-1)();
}
}
var morphContainers = document.querySelectorAll(".morphcontainer");
for(var i = 0; i<morphContainers.length; i++) {
var this_ = morphContainers[i];
morphTargets[i] = {};
morphLinks[i] = {};
var isHover = this_.className.match(/\bhover\b/);
var isManualsort = this_.className.match(/\bmanualsort\b/);
var morphCs = this_.querySelectorAll(".morphcontent");
var morphLs = this_.querySelectorAll(".morphlink");
var h = getStylesLinks(this_,".morphlink_hilight","color:blue; text-decoration:underline; cursor: pointer;");
var def = getStylesLinks(this_,".morphlink_default","color:blue; cursor: pointer;");
currentMorph[i] = {max: morphLs.length, curr: 0, hilight: h, defstyle: def, ms: isManualsort};
for(var m = 0; m<morphLs.length; m++) {
morphLinks[i][m] = morphLs[m];
addHandler(morphLs[m], isHover?'mouseover':'click', morphHandler(i, m));
morphLs[m].setAttribute('style', m?def:h);
};
for(var m = 0; m<morphCs.length; m++) {
morphTargets[i][m] = morphCs[m];
if (isManualsort != null) morphCs[m].style.display = morphCs[m].className.match(morphLs[0].className.replace(/.*morphlink\s+morph(\S+).*/, '$1'))? "" : "none"; else morphCs[m].style.display = m ? "none" : "";
};
if (this_.querySelector(".morphprev")) addClickHandler(this_.querySelector(".morphprev"), morphPrev(i));
if (this_.querySelector(".morphnext")) addClickHandler(this_.querySelector(".morphnext"), morphNext(i));
}
function getStylesLinks(parentNode,selectorString,defaultStyle) {
if (gettedNode = parentNode.querySelector(selectorString)) {
needStyle = gettedNode.getAttribute('style');
gettedNode.parentNode.removeChild(gettedNode);
} else
needStyle = defaultStyle;
return needStyle;
}
}
/* Morph LM Edition END */
/* Add execute functions for different actions */
if (wgAction == "view") { //running functions for view user action
addOnloadHook(createMorphObjects);
addOnloadHook(showAndHideReferences);
}