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

>Edward Chernenko
мНет описания правки
Откат правки 362378 участника Тэйтанка-птекила (обс.)
Метка: отмена
 
(не показано 259 промежуточных версий 17 участников)
Строка 1: Строка 1:
/* <pre><nowiki> */
/* Нигилистические фокусы (см. шаблон {{tl|Нигилизм}}) */
 
$(function () {
document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://absurdopedia.wikia.com/index.php?title=MediaWiki:Wikifier.js&action=raw&ctype=text/javascript&dontcountme=s\"></script>");
    var nihilism = $('#nihilism');
 
    if (nihilism[0] && !document.location.href.match("diff")) {
function addLoadEvent(func)  
        var msg = nihilism.html();
{
        if (!nihilism.hasClass('nihilism-no-white')) {
if (window.addEventListener)
        $('body').css('background-color', 'white');
  window.addEventListener("load", func, false);
        }
else if (window.attachEvent)  
        var scripts = $('script');
  window.attachEvent("onload", func);
        var bodyNihilism = $('body').html('');
}
        var divNihilism = $('<div class="mw-parser-output"></div>').html(msg);
 
        if (nihilism.css('top') == '0px') {
function onPageInit()
        bodyNihilism.css('top', '0px').css('left', '0px');
{
        }
    fillEditSummaries();
        bodyNihilism.append(divNihilism).append(scripts);
    fillDeleteReasons();
        $(document).dblclick(function () {
    do_nihilism();
        window.location = mw.util.getUrl(null, {'action': 'edit'});
    do_edit_null();
         });
    hide_bad_iwiki();
    sysdep_init();
    wikipedia_iwiki();
 
    if(typeof onPageLoad != "undefined")
    {
         onPageLoad();
     }
     }
}
});
 
/* Маскируем неправильно настроенные интервики — (C) Edward. */
function hide_bad_iwiki()
{
  for (var i = 0; i < document.links.length; i ++)
  {
    if(document.links[i].href.match("title=([A-Z][a-z]|Simple|Zh-.*?):"))
      document.links[i].innerHTML = "";
  }
}
 
function wikipedia_iwiki()
{/*
  iw = document.getElementById('wikipedia-interwiki');
  if(iw && !document.getElementById('p-wikipedia'))
  {
    document.getElementById('p-lang').innerHTML = "<ul><li class=\"interwiki-x-wikipedia\"><a href=\"http://ru.wikipedia.org/wiki/" + escape(iw.innerHTML) + "\">Википедия</a></li></ul>" + document.getElementById('p-lang').innerHTML;
  }
*/
}
 
/* Обеспечиваем фокус с {{sysdep}} — (C) Edward. */
function sysdep_init()
{
  var lo = document.getElementById('linux_only');
  var wo = document.getElementById('winds_only');
  if(navigator.userAgent.match("Linux") || navigator.userAgent.match("X11"))
  {
    if(lo) lo.style.display = "block";
    if(wo) wo.style.display = "none";
  }
  else
  {
    if(lo) lo.style.display = "none";
    if(wo) wo.style.display = "block";
  }
}
 
/* Обеспечиваем нигилистические фокусы — (C) Edward (см., например, статью [[Google]]) */
function do_nihilism()
{
  nhl = document.getElementById('nihilism');
  if(nhl)
  {
    msg = nhl.innerHTML;
    document.getElementById('globalWrapper').innerHTML = "<div id='nihilism_message'>" + msg + "</div>";  
  }
}


/* Делаем ссылку «править» для нулевой секции — (C) Edward. */
/* Стирание памяти для [[MIB]] («Людей в чёрном») */
function do_edit_null()
$(function () {
{  
    if ($("#erase_memory")[0])
  if(document.getElementById('bodyContent').innerHTML.match('class=\"editsection\"'))
        setTimeout(function () { $("#erase_memory").hide(); }, 20000);
    document.getElementById('bodyContent').innerHTML = "<div class=\"editsection\" id=\"ca-edit-0\">[<a href=\"http://absurdopedia.wikia.com/index.php?title=" + document.title.substr(0, document.title.lastIndexOf(" ")) + "&action=edit&section=0\">править</a>]</div>" + document.getElementById('bodyContent').innerHTML;
});
}


function fillEditSummaries()
/* Ссылка «править» для нулевой секции */
{
$(function () {
     var label = document.getElementById("wpSummaryLabel");
     var zeroSectionTip = "Править введение";


     if(label == null)
     if (!mw.config.get("wgArticleId")) {
    {
         return;
         return;
     }
     }


     var comboString = "Стандартные описания:\n<select id='stdSummaries' onchange='onStdSummaryChange()'>\n"
     var action = mw.config.get("wgAction");
    var request;
     if (action != "view" && action != "purge")
 
         return;
    try
    {
        request = new XMLHttpRequest();
     }
    catch(e)
    {
        request = new ActiveXObject("Msxml2.XMLHTTP");
    }
 
    request.open("GET", "http://absurdopedia.wikia.com/index.php?title=Шаблон:Stdsummaries&action=raw&ctype=text/plain");
 
    request.onreadystatechange = function()
    {
        if(request.readyState == 4)
         {
            var lines = request.responseText.split("\n");
            var i;


            for(i = 0; i < lines.length; i++)
    mw.util.$content.find("h2").children(".mw-editsection:first").clone().prependTo("#bodyContent").css("float", "right").find("a").each(function (index) {
            {
        $(this).attr("title", zeroSectionTip);
                comboString += (lines[i].indexOf("-- ") == 0) ?
        if ($(this).attr("class") === "mw-editsection-visualeditor") {
                  (" <option value = '" + lines[i].substring(3) + "'>" + lines[i].substring(3) + "</option>\n") :
            $(this).attr("href", mw.config.get("wgScript") + "?title=" + mw.util.wikiUrlencode(mw.config.get("wgPageName")) + "&veaction=edit&vesection=0&summary=/*%20Преамбула%20*/%20");
                  (" <optgroup label='" + lines[i] + "' />\n");
        } else {
            }
            $(this).attr("href", mw.config.get("wgScript") + "?title=" + mw.util.wikiUrlencode(mw.config.get("wgPageName")) + "&action=edit&section=0&summary=/*%20Преамбула%20*/%20");
         }
         }
     }
     });
 
});
    request.send(null);
   
    comboString += "</select>\n<br />" + label.innerHTML;
    label.innerHTML = comboString;
}
 
function onStdSummaryChange()
{
    var combo = document.getElementById("stdSummaries");
    var value = combo.options[combo.selectedIndex].value;


     if(value != "")
/* Вставка юзернейма с помощью <span class="insertusername"></span> */
        document.getElementById("wpSummary").value = value;
$(function () {
}
     if ((typeof (disableUsernameReplace) == "undefined" || !disableUsernameReplace) && mw.config.get("wgUserName") !== null) {
 
        var username = mw.config.get("wgUserName");
function fillDeleteReasons()
        $("span.insertusername").text(username);
{
    var label = document.getElementById("wpReason");
 
    if(label == null || !window.location.href.match("action=delete"))
    {
        return;
     }
     }
});


    label = document.getElementById("contentSub");


     if(label == null)
/* Замена категорий для шаблона {{Cats}} */
     {
$(function () {
         return;
     var categoriesAlternative = $("#categories_alternative");
     if (categoriesAlternative[0]) {
         $('#mw-normal-catlinks').html(categoriesAlternative.html());
        categoriesAlternative.hide();
     }
     }
});


    var comboString = "<br /><select id='stdReasons' onchange='onStdReasonChange()'>";
    comboString += "</select>";
    label.innerHTML += comboString;


     var request;
/* Вставка VK-видео на страницу для шаблона {{VKVideo}} */
 
(function() {
     try
     'use strict';
     {
      
         request = new XMLHttpRequest();
     function initVKVideo() {
    }
         var containers = document.querySelectorAll('.vk-video-js');
    catch(e)
       
    {
        for (var i = 0; i < containers.length; i++) {
        request = new ActiveXObject("Msxml2.XMLHTTP");
            var container = containers[i];
    }
            var oid = container.getAttribute('data-oid');
 
            var id = container.getAttribute('data-id');
    request.open("GET", "http://absurdopedia.wikia.com/index.php?title=Шаблон:Stdreasons&action=raw&ctype=text/plain");
            var width = container.getAttribute('data-width') || '560';
 
            var height = container.getAttribute('data-height') || '315';
    request.onreadystatechange = function()
           
    {
            width = parseInt(width) || 560;
        if(request.readyState == 4)
            height = parseInt(height) || 315;
        {
            if (width > 1920) width = 1920;
            var combo = document.getElementById("stdReasons");
            if (height < 100) height = 100;
            var lines = request.responseText.split("\n");
            if (height > 1080) height = 1080;
            var i;
           
            if (oid && id && oid !== 'null' && id !== 'null' && /^[a-zA-Z0-9_-]{1,100}$/.test(oid) && /^[-_a-zA-Z0-9]+$/.test(id)) {
                var iframe = document.createElement('iframe');
                iframe.src = 'https://vk.com/video_ext.php?oid=' + encodeURIComponent(oid) + '&id=' + encodeURIComponent(id);
                iframe.width = width;
                iframe.height = height;
                iframe.frameBorder = '0';
                iframe.allowFullscreen = true;
               
                iframe.sandbox = 'allow-scripts allow-same-origin allow-presentation allow-fullscreen';
                iframe.allow = 'fullscreen';
                iframe.referrerPolicy = 'no-referrer';
                iframe.loading = 'lazy';
                iframe.style.border = 'none';
               
                while (container.firstChild) {
                    container.removeChild(container.firstChild);
                }
                container.appendChild(iframe);
            } else {
                var errorDiv = document.createElement('div');
               
                errorDiv.style.color = 'red';
                errorDiv.style.padding = '10px';
                errorDiv.style.textAlign = 'center';
                errorDiv.style.border = '1px solid';
                errorDiv.style.backgroundColor = '#fff';
                errorDiv.style.fontFamily = 'Arial, sans-serif';
                errorDiv.style.fontSize = '14px';
                errorDiv.style.margin = '5px 0';


            for(i = 0; i < lines.length; i++)
                errorDiv.textContent = 'Ошибка: неверные параметры видео';
            {
               
                var value = lines[i].indexOf("-- ") == 0 ? lines[i].substring(3) : "";
                while (container.firstChild) {
                 combo.innerHTML += "<option value='" + value + "'>" + lines[i] + "</option>";
                    container.removeChild(container.firstChild);
                 }
                container.appendChild(errorDiv);
             }
             }
         }
         }
     }
     }
 
      
    request.send(null);
     if (document.readyState === 'loading') {
}
        document.addEventListener('DOMContentLoaded', initVKVideo);
 
    } else {
function onStdReasonChange()
        initVKVideo();
{
    }
    var combo = document.getElementById("stdReasons");
})();
     var value = combo.options[combo.selectedIndex].value;
 
     if(value != "")
        document.getElementById("wpReason").value = value;
}
 
window.onload = onPageInit;
 
 
/* tooltips and access keys */
ta = new Object();
ta['pt-userpage'] = new Array('.','Моя страница пользователя');
ta['pt-anonuserpage'] = new Array('.','Страница пользователя для моего IP');
ta['pt-mytalk'] = new Array('n','Моя страница обсуждений');
ta['pt-anontalk'] = new Array('n','Страница обсуждений для моего IP');
ta['pt-preferences'] = new Array('','Мои настройки');
ta['pt-watchlist'] = new Array('l','Список страниц моего наблюдения');
ta['pt-mycontris'] = new Array('y','Список страниц, которые я редактировал');
ta['pt-login'] = new Array('o','Здесь можно зарегистрироваться в системе, но это необязательно');
ta['pt-anonlogin'] = new Array('o','Здесь можно зарегистрироваться в системе, но это необязательно');
ta['pt-logout'] = new Array('o','Отказаться от регистрации');
ta['ca-talk'] = new Array('t','Обсуждение статьи');
ta['ca-edit'] = new Array('e','Эту статью можно изменять. Перед сохранением изменений, пожалуйста, нажмите кнопку предварительного просмотра для визуальной проверки результата');
ta['ca-addsection'] = new Array('+','Добавить комментарий к обсуждению');
ta['ca-viewsource'] = new Array('e','Эта страница защищена от изменений, но вы можете посмотреть и скопировать её исходный текст');
ta['ca-history'] = new Array('h','Журнал изменений страницы');
ta['ca-protect'] = new Array('=','Защитить страницу от изменений');
ta['ca-delete'] = new Array('d','Удалить эту страницу');
ta['ca-undelete'] = new Array('d','Восстановить исправления страницы, сделанные до того, как она была удалена');
ta['ca-move'] = new Array('m','Переименовать страницу');
ta['ca-watch'] = new Array('w','Добавить эту страницу в ваш список наблюдения');
ta['ca-unwatch'] = new Array('w','Удалить эту страницу из вашего списка наблюдения');
ta['search'] = new Array('f','Искать это слово');
ta['p-logo'] = new Array('','Заглавная страница');
ta['n-mainpage'] = new Array('z','Перейти на заглавную страницу');
ta['n-portal'] = new Array('','О проекте, о том, что вы можете сделать, где что находится');
ta['n-currentevents'] = new Array('','Список текущих событий');
ta['n-recentchanges'] = new Array('r','Список последних изменений');
ta['n-randompage'] = new Array('x','Посмотреть случайную страницу');
ta['n-help'] = new Array('','Справочник по проекту «{{SITENAME}}»');
ta['n-sitesupport'] = new Array('','Поддержите проект');
ta['t-whatlinkshere'] = new Array('j','Список всех страниц, которые ссылаются на эту страницу');
ta['t-recentchangeslinked'] = new Array('k','Последние изменения в страницах, которые ссылаются на эту страницу');
ta['feed-rss'] = new Array('','Трансляция в формате RSS для этой страницы');
ta['feed-atom'] = new Array('','Трансляция в формате Atom для этой страницы');
ta['t-contributions'] = new Array('','Список страниц, которые изменял этот участник');
ta['t-emailuser'] = new Array('','Отправить письмо этому участнику');
ta['t-upload'] = new Array('u','Загрузить изображения или мультимедиа-файлы');
ta['t-specialpages'] = new Array('q','Список служебных страниц');
ta['t-print']=new Array('', 'Версия без кнопок, пригодная для распечатки');
ta['t-permalink'] = new Array('', 'Ссылка на текущую версию этой статьи');
ta['ca-nstab-main'] = new Array('c','Содержание статьи');
ta['ca-nstab-user'] = new Array('c','Персональная страница участника');
ta['ca-nstab-media'] = new Array('c','Мультимедиа-файл');
ta['ca-nstab-special'] = new Array('','Это служебная страница, она недоступна для редактирования');
ta['ca-nstab-wp'] = new Array('a','Страница проекта');
ta['ca-nstab-image'] = new Array('c','Страница изображения');
ta['ca-nstab-mediawiki'] = new Array('c','Страница сообщения MediaWiki');
ta['ca-nstab-template'] = new Array('c','Страница шаблона');
ta['ca-nstab-help'] = new Array('c','Страница справки');
ta['ca-nstab-category'] = new Array('c','Страница категории');
 
/* </nowiki></pre> */