MediaWiki:Common.js

出自【暗黑百科】DiabloWiki_凯恩之角

(修订版本间的差异)
跳转到: 导航, 搜索
第1行: 第1行:
-
/** Cookies *****************************************************************************
+
/*
-
  */
+
所有用戶在加載任何頁面時,這裡的JavaScript都會加載
 +
*/
 +
window.addPortletLink = mw.util.addPortletLink;
 +
window.getParamValue = mw.util.getParamValue;
-
function setCookie(cookieName, cookieValue, expiryDay) {
+
(function ($, mw) {
-
var today = new Date();
+
    /* Search Engine variant hack */
-
var expire = new Date();
+
    if (/\.google\./.test(document.referrer) && /\.wikipedia\.org\/zh(-[^/]+)?\//.test(document.location.href)) {
-
var nDays = (!expiryDay || isNaN(expiryDay) )?30:expiryDay;
+
        document.location = document.location.href.replace(/\.wikipedia\.org\/zh(-[^/]+)?\//, ".wikipedia.org/wiki/");
-
expire.setTime( today.getTime() + (3600000 * 24 * nDays) );
+
    }
-
document.cookie = cookieName + "=" + escape(cookieValue)
+
-
                + ";path=/w"
+
-
                + ";expires="+expire.toGMTString();
+
-
document.cookie = cookieName + "=" + escape(cookieValue)
+
-
                + ";path=/wiki"
+
-
                + ";expires="+expire.toGMTString();
+
-
}
+
-
function getCookie(cookieName) {
+
    /* Cookies */
-
  var start = document.cookie.indexOf( cookieName + "=" );
+
    window.setCookie = function (cookieName, cookieValue, expiryDay) {
-
  if ( start == -1 ) return "";
+
        $.cookie(cookieName, cookieValue, {
-
  var len = start + cookieName.length + 1;
+
            expires: expiryDay,
-
  if ( ( !start ) &&
+
            path: '/'
-
    ( cookieName != document.cookie.substring( 0, cookieName.length ) ) )
+
         });
-
      {
+
    };
-
         return "";
+
-
      }
+
-
  var end = document.cookie.indexOf( ";", len );
+
-
  if ( end == -1 ) end = document.cookie.length;
+
-
  return unescape( document.cookie.substring( len, end ) );
+
-
}
+
-
function deleteCookie(cookieName) {
+
    window.getCookie = function (cookieName) {
-
  if ( getCookie(cookieName) ) {
+
        return $.cookie(cookieName);
-
    document.cookie = cookieName + "=" + ";path=/w" +
+
     };
-
     ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
+
-
    document.cookie = cookieName + "=" + ";path=/wiki" +
+
-
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
+
-
  }
+
-
}
+
-
deleteCookie('usedacc'); // drop the cookie which probably is a privacy violation
+
    window.deleteCookie = function (cookieName) {
 +
        $.cookie(cookieName, null);
 +
    };
-
/*
+
    /* overwrite the original script loaders with mw.loader.load
-
==定期強制用戶更新cache==
+
    window.importScript = function (page) {
 +
        mw.loader.load(wgServer + wgScript + '?title=' + mw.util.wikiUrlencode(page) + '&action=raw&ctype=text/javascript');
 +
    };
-
*/
+
    window.importScriptCallback = function (page, ready) {
 +
        importScriptURICallback(wgServer + wgScript + '?title=' + mw.util.wikiUrlencode(page) + '&action=raw&ctype=text/javascript', ready);
 +
    };
-
var today=new Date();
+
    window.importScriptURI = function (url) {
 +
        mw.loader.load(url);
 +
    };
-
if( (""+wgUserGroups).indexOf("user")!=-1 && (wgAction=="view") ){
+
    window.importScriptURICallback = function (url, ready) {
 +
        $.ajax({
 +
            'url': url,
 +
            'cache': true,
 +
            'dataType': 'script',
 +
            'success': ready
 +
        });
 +
    };
-
if(!getCookie("lastload") || isNaN(getCookie("lastload")) ){
+
    window.importStylesheet = function (page) {
-
  setCookie("lastload", today.getTime());
+
        mw.loader.load(wgServer + wgScript + '?title=' + mw.util.wikiUrlencode(page) + '&action=raw&ctype=text/css', 'text/css');
-
}else{
+
    };
-
  if( today.getTime()-getCookie("lastload") >= 7*24*60*60*1000 ){
+
    window.importStylesheetURI = function (url) {
-
  setCookie("lastload", today.getTime());
+
        mw.loader.load(url, 'text/css');
-
  if( getCookie("lastload")==today.getTime() ) window.location.reload(true);
+
    };*/
-
  }else if( today.getTime()-getCookie("lastload") < 0 ){
+
-
  setCookie("lastload", today.getTime());
+
-
  }
+
-
}
+
    /* 中文處理 */
 +
    /* 1. 设置中文语言页 */
 +
    $('html').attr('lang', wgUserVariant).attr('xml:lang', wgUserVariant);
-
}
+
    /* 2. 返回繁簡字串 */
 +
    var wgUXS = function (wg, hans, hant, cn, tw, hk, sg, zh, mo, my) {
 +
        var ret = {
 +
            'zh': zh || hans || hant || cn || tw || hk || sg || mo || my,
 +
            'zh-hans': hans || cn || sg || my,
 +
            'zh-hant': hant || tw || hk || mo,
 +
            'zh-cn': cn || hans || sg || my,
 +
            'zh-sg': sg || hans || cn || my,
 +
            'zh-tw': tw || hant || hk || mo,
 +
            'zh-hk': hk || hant || tw || mo
 +
        }
 +
        return ret[wg] || zh || hans || hant || cn || tw || hk || sg || mo || my; //保證每一語言有值
 +
    }
 +
    window.wgULS = function (hans, hant, cn, tw, hk, sg, zh, mo, my) {
 +
        return wgUXS(wgUserLanguage, hans, hant, cn, tw, hk, sg, zh, mo, my);
 +
    };
-
if( (""+wgUserGroups).indexOf("user")!=-1 && (wgAction=="edit") ){
+
    window.wgUVS = function (hans, hant, cn, tw, hk, sg, zh, mo, my) {
 +
        return wgUXS(wgUserVariant, hans, hant, cn, tw, hk, sg, zh, mo, my);
 +
    };
-
if(!getCookie("editlastload") || isNaN(getCookie("editlastload")) ){
+
    /* 當需要時載入對應的 scripts */
-
  setCookie("editlastload", today.getTime());
+
    if (wgAction == "edit" || wgAction == "submit" || wgCanonicalSpecialPageName == 'Search') { //scripts specific to editing pages
-
}else{
+
        importScript('MediaWiki:Common.js/edit.js');
 +
    }
-
  if( today.getTime()-getCookie("editlastload") >= 7*24*60*60*1000 ){
+
    /* 辅助处理 */
-
  setCookie("editlastload", today.getTime());
+
    /* 1. 功能設定 */
-
  if( getCookie("editlastload")==today.getTime() ) window.location.reload(true);
+
    window.JSConfig = window.JSconfig || {};
-
  }else if( today.getTime()-getCookie("editlastload") < 0 ){
+
    window.JSConfig.collapseText = wgULS('隐藏▲', '隱藏▲'); //指示折叠收缩的默认文字
-
  setCookie("editlastload", today.getTime());
+
    window.JSConfig.expandText = wgULS('显示▼', '顯示▼'); //指示折叠展开的默认文字
-
  }
+
    window.JSConfig.autoCollapse = 2; //文章少于 autoCollapse 个折叠块时,不自动折叠
 +
    // window.JSConfig.SpecialSearchEnhancedDisabled=false; //是否禁止增加其它搜索引擎
 +
    /* 2. 用jQuery实现的getElementsByClassName(需不需要返回DOM对象?) */
 +
    window.getElementsByClassName = function (elm, tag, className) {
 +
        return $(tag + '.' + className, elm);
 +
    };
-
}
+
    /* 3. 遍历 */
 +
    window.applyEach = function (callback, array) {
 +
        var i = 0,
 +
            j = array.length;
 +
        while (i < j) {
 +
            callback(array[i++]);
 +
        }
 +
    };
-
}
+
    /* 4. 移動元素 */
-
/*
+
    window.elementMoveto = function (node, refNode, pos) { //默认位置为refNode前
-
* ImportScriptHttp.模块
+
        if (node && refNode) {
-
* 版本: r1
+
            if (pos && pos == 'after') {
-
*/
+
                $(refNode).after(node);
-
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(7(){3(c.2!=S)8;2=k W();c.2=2;2.d={};2.C=7(9,6){3(2.d[9]){8(a)}2.d[9]=z;7 y(){f A;q{A=k 17()}o(e){q{A=k Q("15.P")}o(e){q{A=k Q("11.P")}o(14){A=a}}}3(!A)E("13 16 19 10 18.");8 A}f x=y();x.j=7(){3(5.N==4){3(5.n==1a||5.n==X){3((5.B!=a)){f s=l.u("v");s.U="i";s.G="h/i";s.T=p;s.h=5.B;l.J(\'L\')[0].M(s);3(6)6()}}I{E(\'Y Z V: \'+5.12+\' (\'+5.n+\')\');8(p)}5.j=a}};x.1g(\'1s\',9,p);x.1r(a);8(x)};c.t=2.C;7 m(b){f w=1q+\'?1u=\'+1t(b.r(/ /g,\'1w\')).r(\'%1v\',\'/\').r(\'%1p\',\':\')+\'&1n=1o&1b=h/i\';8(w)}2.F=7(b,6){8(t(m(b,6)))};c.1f=2.F;2.O=7(9,6){3(2.d[9])8 a;2.d[9]=z;f s=l.u(\'v\');s.1e=\'1c\';s.K(\'1d\',9);s.K(\'G\',\'h/i\');3(6){3(1h.1i.1m("1l")!=-1)s.j=(7(){3(5.N==\'1k\'){5.j=a;6()}});I s.H=(7(){5.H=a;6})}l.J(\'L\')[0].M(s);8 s};c.R=2.O;2.D=7(b,6){8(R(m(b),6))};c.1j=2.D})();',62,95,'||ImportScriptEx|if||this|callback|function|return|url|null|page|window|loadedScripts||var||text|javascript|onreadystatechange|new|document|ImportScriptExMakePageURI|status|catch|false|try|replace||ImportScriptExHttpURI|createElement|script|uri||MakeHttpRequest|true||responseText|HttpURI|Page|alert|HttpPage|type|onload|else|getElementsByTagName|setAttribute|head|appendChild|readyState|URI|XMLHTTP|ActiveXObject|ImportScriptExURI|undefined|defer|language|error|Object|304|XML|request|connection|Microsoft|statusText|Could|oc|Msxml2|not|XMLHttpRequest|object|create|200|ctype|googlejsapi|src|id|ImportScriptExHttpPage|open|navigator|userAgent|ImportScriptExPage|complete|MSIE|indexOf|action|raw|3A|wgScript|send|GET|encodeURIComponent|title|2F|_'.split('|'),0,{}))
+
            } else {
-
/*  ImportScriptHttp.模块,结束  */
+
                $(refNode).before(node);
-
//var googlejsapiurl='http://www.google.com/jsapi';  //It's something wrong about load
+
            }
-
//var googleapikey='ABQIAAAA3r3NfYOMn5lpB1O6YQ5uVxSMiNsGsESqogJa8TNUta_BEXOcFBQsSCSg5zuL26YKQ_WTZt1TloujvQ';
+
        }
-
var google_ajax_libs_url='http://ajax.googleapis.com/ajax/libs/';
+
    };
-
var jQueryVer='1.4.2';
+
-
var jQueryUrl=google_ajax_libs_url+'jquery/'+jQueryVer+'/jquery.min.js';
+
-
ImportScriptExURI('http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js',(function(){//load jQuery start
+
    /* 5. 创建元素 */
-
if (window.jQuery === undefined)
+
    window.createElement = function (tag, children, props) {
-
ImportScriptExHttpPage('MediaWiki:JQuery.1.5.2.min.js');
+
        var element = document.createElement(tag);
-
if (window.jQuery === undefined)
+
        if (!(children instanceof Array)) {
-
console.log('Failed to load jQuery!');
+
            children = [children];
-
//load jQuery end;
+
        }
-
//begining to use jQuery function
+
        applyEach(function (child) {
 +
            if (typeof child == 'string') {
 +
                child = document.createTextNode(child);
 +
            }
 +
            if (child) {
 +
                element.appendChild(child);
 +
            }
 +
        }, children);
 +
        if (typeof props == 'object') {
 +
            for (var k in props) {
 +
                switch (k) {
 +
                case 'styles':
 +
                    var styles = props.styles;
 +
                    for (var s in styles) {
 +
                        element.style[s] = styles[s];
 +
                    }
 +
                    break;
 +
                case 'events':
 +
                    var events = props.events;
 +
                    for (var e in events) {
 +
                        addHandler(element, e, events[e]);
 +
                    }
 +
                    break;
 +
                case 'class':
 +
                    element.className = props[k];
 +
                    break;
 +
                default:
 +
                    element.setAttribute(k, props[k]);
 +
                }
 +
            }
 +
        }
 +
        return element;
 +
    };
 +
    //wiki URL
 +
    window.wgProjectURL = {
 +
        en: 'http://en.wikipedia.org',
 +
        de: 'http://de.wikipedia.org',
 +
        fr: 'http://fr.wikipedia.org',
 +
        pl: 'http://pl.wikipedia.org',
 +
        ja: 'http://ja.wikipedia.org',
 +
        it: 'http://it.wikipedia.org',
 +
        nl: 'http://nl.wikipedia.org',
 +
        pt: 'http://pt.wikipedia.org',
 +
        es: 'http://es.wikipedia.org',
 +
        sv: 'http://sv.wikipedia.org',
 +
        //僅列前十名其它語言百科
 +
        m: 'http://meta.wikimedia.org',
 +
        b: 'http://zh.wikibooks.org',
 +
        q: 'http://zh.wikiquote.org',
 +
        n: 'http://zh.wikinews.org',
 +
        wikt: 'http://zh.wiktionary.org',
 +
        mw: 'http://www.mediawiki.org',
 +
        commons: 'http://commons.wikimedia.org'
 +
    };
 +
    /**
 +
    * 将页面名称转换为URL
 +
    *
 +
    * @param page 页面名称
 +
    * @param paras 附加后缀对象,用空对象{}做参数可以取得源码
 +
    */
 +
    window.getWikiPath = function (page, paras) {
 +
        var reg = /^[a-z]+:/;
 +
        var pre = page.match(reg);
 +
        pre = pre && wgProjectURL[pre[0].replace(/:$/, '').toLowerCase()];
 +
        if (pre) {
 +
            page = page.replace(reg, '');
 +
        } else {
 +
            pre = wgServer;
 +
        } //保障没有相对路径,以照顾在线代理。
 +
        var url = pre + wgScript + '?title=' + encodeURI(page.replace(' ', '_'));
 +
        if (typeof paras == 'object') {
 +
            paras.ctype = paras.ctype || 'text';
 +
            paras.dontcountme = paras.dontcountme || 's';
 +
            paras.action = paras.action || 'raw';
 +
            for (var k in paras) {
 +
                url += '&' + k + '=' + paras[k];
 +
            }
 +
        }
 +
        return url;
 +
    };
 +
    //引入[[Special:Gadgets]]要求的腳本和樣式
 +
    if (window.requireScripts instanceof Array) {
 +
        applyEach(importScript, requireScripts);
 +
    }
 +
    if (window.requireStylesheets instanceof Array) {
 +
        applyEach(importStylesheet, requireStylesheets);
 +
    }
 +
    window.requireScripts = [];
 +
    window.requireScripts.push = function (script) {
 +
        importScript(script);
 +
    };
 +
    window.requireStylesheets = [];
 +
    window.requireStylesheets.push = function (style) {
 +
        importStylesheet(style);
 +
    };
 +
    /* 测试元素中是否含有指定的样式 */
 +
    window.hasClass = function (elem, cls) {
 +
        return $(elem).hasClass(cls);
 +
    };
-
// addHandler in wikibits.js has some problems? overwrite it here:
 
-
function addHandler( element, attach, handler ) {
 
-
    $(element).bind(attach, handler);
 
-
}
 
-
}));//end jquery
 
/*
/*
-
== 中文處理 ==
+
== IE兼容性修正 ==
-
 
+
*/
*/
-
//设置中文语言页
+
    if ($.browser.msie) {
-
document.documentElement.setAttribute("lang",wgUserLanguage);
+
        /** Internet Explorer bug fix **************************************************
-
document.documentElement.setAttribute("xml:lang",wgUserLanguage);
+
        *
 +
        *  Description: Fixes IE horizontal scrollbar bug
 +
        *  Maintainers: [[User:fdcn]]
 +
        */
 +
        var oldWidth;
 +
        var docEl = document.documentElement;
-
//返回繁簡字串
+
        function fixIEScroll() {
 +
            if (!oldWidth || docEl.clientWidth > oldWidth) {
 +
                doFixIEScroll();
 +
            } else {
 +
                setTimeout(doFixIEScroll, 1);
 +
            }
 +
            oldWidth = docEl.clientWidth;
 +
        }
-
function wgUXS(wg,hans,hant,cn,tw,hk,sg,zh) {
+
        function doFixIEScroll() {
-
    var ret = {
+
            docEl.style.overflowX = (docEl.scrollWidth - docEl.clientWidth < 4) ? "hidden" : "";
-
         'zh':zh||hans||hant||cn||tw||hk||sg,
+
         }
-
         'zh-hans':hans||cn||sg,
+
 
-
         'zh-hant':hant||tw||hk,
+
         document.attachEvent("onreadystatechange", fixIEScroll);
-
         'zh-cn':cn||hans||sg,
+
         attachEvent("onresize", fixIEScroll);
-
         'zh-sg':sg||hans||cn,
+
 
-
        'zh-tw':tw||hant||hk,
+
         //Import scripts specific to Internet Explorer 6
-
         'zh-hk':hk||hant||tw
+
         if (navigator.appVersion.substr(22, 1) == "6") {
 +
            importScript("MediaWiki:Common.js/IE60Fixes.js")
 +
         }
     }
     }
-
    return ret[wg]||zh||hans||hant||cn||tw||hk||sg;//保證每一語言有值
 
-
}
 
-
function wgULS(hans,hant,cn,tw,hk,sg,zh){
+
/*
-
    return wgUXS(wgUserLanguage,hans,hant,cn,tw,hk,sg,zh);
+
== 特色條目優良與條目鏈接顯示==
-
}
+
*/
-
function wgUVS(hans,hant,cn,tw,hk,sg,zh){
+
    $(function () {
-
    return wgUXS(wgUserVariant,hans,hant,cn,tw,hk,sg,zh);
+
        $('#p-lang li').each(function () {
-
}
+
            if ($('#' + this.className + '-fa').length) {
-
/* 當需要時載入對應的 scripts */
+
                this.className += " FA"
 +
                this.title = wgULS("此条目在此语言版本中为特色条目", "此條目在此語言版本中為特色條目");
 +
            } else if ($('#' + this.className + '-ga').length) {
 +
                this.className += " GA"
 +
                this.title = wgULS("此条目在此语言版本中为优良条目", "此條目在此語言版本中為優良條目");
 +
            }
 +
        });
 +
    });
-
if (wgAction == "edit" || wgAction == "submit") //scripts specific to editing pages
 
-
{
 
-
    importScript("MediaWiki:Common.js/edit.js")
 
-
}
 
-
else if (wgCanonicalSpecialPageName == "Search") //scripts specific to Special:Search
 
-
{
 
-
    importScript("MediaWiki:Common.js/search.js")
 
-
}
 
/*
/*
-
== 辅助处理 ==
+
== 增加摺疊功能 ==
*/
*/
-
//功能設定
+
    /** 摺疊 div table *****************************
-
if(!window.JSConfig){var JSConfig={};}
+
    *  Description: 实现div.NavFrame和table.collapsible的可折叠性。
-
JSConfig.collapseText=wgULS('隐藏▲','隱藏▲');//指示折叠收缩的默认文字
+
    * JSConfig的collapseText、expandText、autoCollapse属性定义默认文字和默认最少自动折叠块
-
JSConfig.expandText=wgULS('显示▼','顯示▼');//指示折叠展开的默认文字
+
    * Maintainers: User:fdcn
-
JSConfig.autoCollapse=2; //文章少于 autoCollapse 个折叠块时,不自动折叠
+
    */
-
/* JSConfig.SpecialSearchEnhancedDisabled=false; //是否禁止增加其它搜索引擎 */
+
-
//新的getElementsByClassName
+
     function cancelBubble(e) {
-
/*
+
         e = e || window.event;
-
     Developed by Robert Nyman, http://www.robertnyman.com
+
        if (e.stopPropagation) {
-
    Code/licensing: http://code.google.com/p/getelementsbyclassname/
+
            e.stopPropagation();
-
*/ 
+
        } else {
-
var getElementsByClassName = function (elm, tag, className){
+
             e.cancelBubble = true;
-
    if (document.getElementsByClassName) {
+
         }
-
         getElementsByClassName = function (elm, tag, className) {
+
-
            elm = elm || document;
+
-
            var elements = elm.getElementsByClassName(className);
+
-
            if (tag=="*") return elements;
+
-
            var nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
+
-
                returnElements = [],
+
-
                current;
+
-
            for(var i=0, il=elements.length; i<il; i+=1){
+
-
                current = elements[i];
+
-
                if(!nodeName || nodeName.test(current.nodeName)) {
+
-
                    returnElements.push(current);
+
-
                }
+
-
             }
+
-
            return returnElements;
+
-
         };
+
     }
     }
-
     else if (document.evaluate) {
+
 
-
         getElementsByClassName = function (elm, tag, className) {
+
     function createToggleButton(head) {
-
            tag = tag || "*";
+
         var parent = head;
-
            elm = elm || document;
+
        if (head.tagName.toLowerCase() == 'tr') { //对表格特别处理
-
            var classes = className.split(" "),
+
            if (head.getElementsByTagName("th").length) {
-
                classesToCheck = "",
+
                 parent = head.cells[parent.cells.length - 1];
-
                xhtmlNamespace = "http://www.w3.org/1999/xhtml",
+
             } else {
-
                namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
+
                 return;
-
                 returnElements = [],
+
-
                elements,
+
-
                node;
+
-
             for(var j=0, jl=classes.length; j<jl; j+=1){
+
-
                 classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
+
             }
             }
-
            try {
+
        }
-
                elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
+
        var textS, textH, button = getElementsByClassName(head, "span", "NavToggle")[0];
-
            }
+
        if (button) {
-
            catch (e) {
+
            parent = button.parentNode;
-
                elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
+
        } else {
-
             }
+
            textS = createElement("span", [JSConfig.expandText], {
-
             while ((node = elements.iterateNext())) {
+
                'class': 'toggleShow'
-
                 returnElements.push(node);
+
             });
-
             }
+
             textH = createElement("span", [JSConfig.collapseText], {
-
             return returnElements;
+
                 'class': 'toggleHide'
-
         };
+
            });
 +
             button = createElement("span", [textS, textH], {
 +
                'class': 'NavToggle',
 +
                styles: {
 +
                    'width': "6em"
 +
                }
 +
             });
 +
         }
 +
        button.style.display = "inline";
 +
        head.className += " uncollapse toggleHotspot";
 +
        parent.insertBefore(button, parent.childNodes[0]);
     }
     }
-
     else {
+
     window.wgCollapse = function (head, container, defaultCollapse) {
-
        getElementsByClassName = function (elm, tag, className) {
+
        if (head) {
-
             tag = tag || "*";
+
             createToggleButton(head);
-
            elm = elm || document;
+
        }
-
            var classes = className.split(" "),
+
        var self = this;
-
                classesToCheck = [],
+
        this.state = 0;
-
                elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
+
        this.container = container;
-
                current,
+
        applyEach(function (h) {
-
                returnElements = [],
+
            if (h.nodeType == 1 && !hasClass(h, "uncollapse") && !hasClass(h, "toggleShow") && !hasClass(h, "toggleHide")) {
-
                match;
+
                 h.className += " toggleHide";
-
            for(var k=0, kl=classes.length; k<kl; k+=1){
+
-
                 classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
+
             }
             }
-
            for(var l=0, ll=elements.length; l<ll; l+=1){
+
        }, defaultCollapse); //预设的隐藏元素
-
                current = elements[l];
+
 
-
                 match = false;
+
 
-
                 for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
+
        function getArray(clsname) {
-
                    match = classesToCheck[m].test(current.className);
+
            var r = [],
-
                    if (!match) {
+
                 i = 0,
-
                        break;
+
                 e, ea = getElementsByClassName(container, "*", clsname);
-
                     }
+
            while (e = ea[i++]) {
 +
                var parent = e.parentNode;
 +
                while (!hasClass(parent, 'NavFrame') && !hasClass(parent, 'collapsible')) {
 +
                     parent = parent.parentNode;
                 }
                 }
-
                 if (match) {
+
                 if (parent == container) {
-
                     returnElements.push(current);
+
                     r.push(e);
                 }
                 }
             }
             }
-
             return returnElements;
+
             return r;
-
         };
+
         }
-
    }
+
        var toggleA = getArray("toggleShow");
-
    return getElementsByClassName(elm, tag, className);
+
        var toggleB = getArray("toggleHide");
-
};
+
        var hotspots = getArray("toggleHotspot");
-
//遍历
+
        function _toggle(list, state) {
-
function applyEach(callback,array){
+
            var i = 0,
-
    var i=0,j=array.length;
+
                e;
-
    while(i<j){callback(array[i++]);}
+
            while (e = list[i++]) {
-
}
+
                e.style.display = state ? e.showStyle || '' : 'none';
 +
            }
 +
        }
 +
        this.toggle = function (state) {
 +
            self.state = (typeof state == 'undefined') ? 1 - self.state : state;
 +
            _toggle(toggleA, self.state);
 +
            _toggle(toggleB, 1 - self.state);
 +
        }
 +
        var i = 0,
 +
            h;
 +
        while (h = hotspots[i++]) {
 +
            applyEach(function (link) {
 +
                addClickHandler(link, cancelBubble);
 +
            }, h.getElementsByTagName("A"));
 +
            h.style.cursor = "pointer";
 +
            $(h).attr('tabindex', '0').keydown(function (event) {
 +
                if (event.which == 13) { // Enter
 +
                    self.toggle();
 +
                }
 +
            });
 +
            addClickHandler(h, function () {
 +
                self.toggle();
 +
            });
 +
        }
 +
    };
-
// 移動元素
+
    $(function () {
-
function elementMoveto(node, refNode, pos){//默认位置为refNode前
+
        if (!window.disableCollapse) {
-
    if(node && refNode){
+
            //init
-
        var parent=refNode.parentNode;
+
            var items = [];
-
        if (pos && pos=='after') {refNode=refNode.nextSibling;}
+
            applyEach(function (NavFrame) {
-
        try {
+
                var i = 0,
-
            if(refNode){
+
                    child = NavFrame.childNodes,
-
                parent.insertBefore(node, refNode);
+
                    head;
-
            }else{
+
                while (head = child[i++]) {
-
                parent.appendChild(node);
+
                    if (head.className && hasClass(head, "NavHead")) {
-
            }
+
                        break;
-
        } catch (DOMException) {};
+
                    }
-
    }
+
                }
-
}
+
                items.push(new wgCollapse(head, NavFrame, NavFrame.childNodes));
-
//创建元素
+
            }, getElementsByClassName(document, "div", "NavFrame"));
-
function createElement(tag,children,props){
+
            applyEach(function (table) {
-
    var element = document.createElement(tag);
+
                var rows = table.rows;
-
    if(!(children instanceof Array)){children=[children];}
+
                items.push(new wgCollapse(rows[0], table, rows));
-
    applyEach(function(child){
+
            }, getElementsByClassName(document, "table", "collapsible"));
-
        if(typeof child=='string'){child=document.createTextNode(child);}
+
             var item, i = 0,
-
        if(child){element.appendChild(child);}
+
                 count = items.length;
-
    },children);
+
            while (item = items[i++]) {
-
    if(typeof props=='object'){
+
                 item.toggle(
-
        for(var k in props){
+
                 hasClass(item.container, "collapsed") || (count >= JSConfig.autoCollapse && hasClass(item.container, "autocollapse")));
-
             switch(k){
+
-
            case 'styles':
+
-
                 var styles=props.styles;
+
-
                for(var s in styles){element.style[s]=styles[s];}
+
-
                 break;
+
-
            case 'events':
+
-
                var events=props.events;
+
-
                 for(var e in events){ addHandler(element,e,events[e]); }
+
-
                break;
+
-
            case 'class':
+
-
                element.className=props[k];break;
+
-
            default:
+
-
                element.setAttribute(k,props[k]);
+
             }
             }
         }
         }
-
     }
+
     });
-
     return element;
+
     //修正摺疊後定位變化
-
}
+
    hookEvent("load", function () {
 +
        if (location.hash) {
 +
            location.href = location.hash;
 +
        }
 +
    });
-
//引入[[Special:Gadgets]]要求的腳本和樣式
+
/*
-
if(window.requireScripts instanceof Array){
+
-
    applyEach(importScript,requireScripts);
+
-
}
+
-
if(window.requireStylesheets instanceof Array){
+
-
    applyEach(importStylesheet,requireStylesheets);
+
-
}
+
-
window.requireScripts=[];
+
-
window.requireScripts.push = function(script) {
+
-
    importScript(script);
+
-
};
+
-
window.requireStylesheets=[];
+
-
window.requireStylesheets.push = function(style) {
+
-
    importStylesheet(style);
+
-
};
+
-
/* 测试元素中是否含有指定的样式 **************************************
+
== 取消討論頁的[+]按鈕 ==
-
* Description: 使用正则式与缓存来提高性能
+
-
* Maintainers: User:fdcn @zh.wikipedia
+
-
*              [[en:User:Mike Dillon]], [[en:User:R. Koot]], [[en:User:SG]] @en.wikipedia
+
*/
*/
-
var hasClass = (function () {
+
 
-
     var reCache = {};
+
     $(function () {
-
    return function (element, className) {
+
         if ($('#no-newsection').length) {
-
         return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className);
+
            $('#ca-addsection').css('display', 'none');
-
    };
+
        }
-
})();
+
    });
/*
/*
-
== IE兼容性修正 ==
+
==WikiMiniAtlas世界地圖==
*/
*/
-
function fixIE(){
+
     /** WikiMiniAtlas *******************************************************
-
}
+
-
if (navigator.appName == "Microsoft Internet Explorer"){
+
-
     /** Internet Explorer bug fix **************************************************
+
     *
     *
-
     *  Description: Fixes IE horizontal scrollbar bug
+
     *  描述:WikiMiniAtlas是一個popup而可點選與拖曳的世界地圖。
-
     *  Maintainers: [[User:fdcn]]
+
    *              這個腳本將會讓所有的經緯度標示中顯示WikiMiniAtlas的popup開啟按鈕。
 +
    *              由於被許多計畫使用,因此腳本放置在元維基中。
 +
    *              更多資訊請詳見[[Meta:WikiMiniAtlas]]。
 +
     *  創建者:[[:en:User:Dschwen]]
     */
     */
-
    var oldWidth;
 
-
    var docEl = document.documentElement;
 
-
    function fixIEScroll(){
 
-
        if (!oldWidth || docEl.clientWidth > oldWidth){
 
-
            doFixIEScroll();
 
-
        }else{
 
-
            setTimeout(doFixIEScroll, 1);
 
-
        }
 
-
        oldWidth = docEl.clientWidth;
 
-
    }
 
-
     function doFixIEScroll() {
+
     var metaBase = 'http://meta.wikimedia.org';
-
        docEl.style.overflowX = (docEl.scrollWidth - docEl.clientWidth < 4) ? "hidden" : "";
+
    if (mw.config.get('wgServer') == 'https://secure.wikimedia.org') {
 +
        var metaBase = 'https://secure.wikimedia.org/wikipedia/meta';
     }
     }
 +
    mw.loader.load(metaBase + '/w/index.php?title=MediaWiki:Wikiminiatlas.js&action=raw&ctype=text/javascript&smaxage=21600&maxage=86400');
-
     document.attachEvent("onreadystatechange", fixIEScroll);
+
/*
-
    attachEvent("onresize", fixIEScroll);
+
==保護選項校正==
 +
*/
 +
 
 +
     if (wgAction == "protect") {
 +
 
 +
        $(function () {
 +
            var pform = document.getElementById("mw-Protect-Form");
 +
            var timeoptions;
 +
 
 +
            timeoptions = pform["wpProtectExpirySelection-edit"].options;
 +
            if (timeoptions[0].value != "existing") {
 +
                timeoptions[timeoptions.length - 1].selected = true;
 +
                ProtectionForm.updateExpiryList(pform["wpProtectExpirySelection-edit"]);
 +
            }
 +
 
 +
            timeoptions = pform["wpProtectExpirySelection-move"].options;
 +
            if (timeoptions[0].value != "existing") {
 +
                timeoptions[timeoptions.length - 1].selected = true;
 +
                ProtectionForm.updateExpiryList(pform["wpProtectExpirySelection-move"]);
 +
            }
 +
 
 +
        });
-
    //Import scripts specific to Internet Explorer 6
 
-
    if (navigator.appVersion.substr(22, 1) == "6"){
 
-
        importScript("MediaWiki:Common.js/IE60Fixes.js")
 
     }
     }
-
}
 
/*
/*
 +
==擷取選單文字按鈕==
 +
*/
 +
 +
    $(function () {
 +
 +
        var addGetMenuTextButton = function (id, srcMenu, targetText, tiptext, afterSelIdx) {
 +
            var btnAdd = createElement("input", "", {
 +
                'id': id,
 +
                'type': 'button',
 +
                'value': ((!tiptext) ? "(+)" : tiptext)
 +
            });
 +
 +
            btnAdd.srcMenu = srcMenu;
 +
            btnAdd.targetText = targetText;
 +
            btnAdd.afterSelIdx = (!afterSelIdx || isNaN(afterSelIdx)) ? 0 : afterSelIdx;
 +
 +
            addHandler(btnAdd, "click", function () {
 +
                this.targetText.value += this.srcMenu.options[this.srcMenu.selectedIndex].value;
 +
                this.srcMenu.selectedIndex = this.afterSelIdx;
 +
            });
 +
 +
            elementMoveto(btnAdd, srcMenu, "after");
 +
        }
 +
 +
        var useForm;
 +
 +
        if (wgAction == "protect" || wgAction == "unprotect") { //保護理由
 +
            useForm = document.getElementById("mw-Protect-Form");
 +
            addGetMenuTextButton("wpProtectReasonSelectionAdd", useForm.wpProtectReasonSelection, useForm["mwProtect-reason"], "加到附加的理由", 0);
 +
 +
        } else if (("" + wgCanonicalSpecialPageName).toLowerCase() == "blockip") { //封禁理由
 +
            useForm = document.getElementById("blockip");
 +
            addGetMenuTextButton("wpBlockReasonListAdd", useForm.wpBlockReasonList, useForm.wpBlockReason, wgULS("加到附带原因", "加到附帶原因"), 0);
 +
 +
        }
 +
 +
    });
 +
 +
/*
 +
 +
==避免在主條目中出現捲軸框==
-
== 增加摺疊功能 ==
 
*/
*/
-
/** 摺疊 div table *****************************
+
 
-
*  Description: 实现div.NavFrame和table.collapsible的可折叠性。
+
    if (!wgCanonicalNamespace) $(function () {
-
* JSConfig的collapseText、expandText、autoCollapse属性定义默认文字和默认最少自动折叠块
+
 
-
Maintainers: User:fdcn
+
        var disableDivOverflowScroll = function (obj) {
 +
            var targetdiv;
 +
 
 +
            for (var i = obj.children.length; i-- > 0;) if (obj.children[i].tagName.toLowerCase() == "div") {
 +
                targetdiv = obj.children[i];
 +
 
 +
                if (targetdiv.className.indexOf("noprint") == -1 && targetdiv.className.indexOf("thumb") == -1) {
 +
                    if ( !! (targetdiv.style.overflow) || !! (targetdiv.style.overflowY)) with(targetdiv.style) {
 +
                        overflowY = "visible";
 +
                        padding = "";
 +
                        border = "";
 +
                        height = "";
 +
                    }
 +
 
 +
                    disableDivOverflowScroll(targetdiv);
 +
                }
 +
 
 +
            }
 +
        }
 +
 
 +
        disableDivOverflowScroll(document.getElementsByTagName("body")[0]);
 +
    });
 +
 
 +
/*  
 +
== metaBox ==
 +
 
 +
HERE STARTS THE WORKING-CODE OF "METABOXES"*/
 +
 
 +
/* Funcionament de la Plantilla:Metacaixa
 +
  Implementat per: Usuari:Peleguer.
 +
Actualitzat per Joanjoc seguint les indicacions d'en Martorell
  */
  */
-
function cancelBubble(e){
+
 
-
    e=e||window.event;
+
    function MetaCaixaInit() {
-
    if(e.stopPropagation){e.stopPropagation();}else{e.cancelBubble=true;}
+
        //S'executa al carregar-se la pàgina, si hi ha metacaixes,
-
}
+
        // s'assignen els esdeveniments als botons
-
function createToggleButton(head){
+
        //alert("MetaCaixaInit");
-
    var parent=head;
+
        var i = 0 //Inicialitzem comptador de caixes
-
    if( head.tagName.toLowerCase()=='tr' ){//对表格特别处理
+
        for (i = 0; i <= 9; i++) {
-
        if(head.getElementsByTagName("th").length){
+
            var vMc = document.getElementById("mc" + i);
-
             parent=head.cells[parent.cells.length-1];
+
            if (!vMc) break;
-
        } else {return;}
+
            //alert("MetaCaixaInit, trobada Metacaixa mc"+i);
-
    }
+
             var j = 1 //Inicialitzem comptador de botons dins de la caixa
-
    var textS,textH,button=getElementsByClassName(head,"span","NavToggle")[0];
+
            var vPsIni = 0 //Pestanya visible inicial
-
    if(button){parent=button.parentNode;} else{
+
            for (j = 1; j <= 9; j++) {
-
        textS=createElement("span",[JSConfig.expandText],{'class':'toggleShow'});
+
                var vBt = document.getElementById("mc" + i + "bt" + j);
-
        textH=createElement("span",[JSConfig.collapseText],{'class':'toggleHide'});
+
                if (!vBt) break;
-
        button=createElement("span",[textS,textH],{'class':'NavToggle',styles:{'width':"3.8em"}});
+
                //alert("MetaCaixaInit, trobat botó mc"+i+"bt"+j);
-
    }
+
                vBt.onclick = MetaCaixaMostraPestanya; //A cada botó assignem l'esdeveniment onclick
-
    button.style.display="inline";
+
                //alert (vBt.className);
-
    head.className+=" uncollapse toggleHotspot";
+
                if (vBt.className == "mcBotoSel") vPsIni = j; //Si tenim un botó seleccionat, en guardem l'index
-
    parent.insertBefore( button, parent.childNodes[0] );
+
            }
-
}
+
            //alert ("mc="+i+", ps="+j+", psini="+vPsIni );
-
function wgCollapse(head,container,defaultCollapse){
+
            if (vPsIni == 0) { //Si no tenim cap botó seleccionat, n'agafem un aleatòriament
-
    if(head){ createToggleButton(head); }
+
                vPsIni = 1 + Math.floor((j - 1) * Math.random());
-
    var self=this;
+
                //alert ("Activant Pestanya a l'atzar; _mc"+i+"bt"+vPsIni +"_");
-
    this.state=0;
+
                document.getElementById("mc" + i + "ps" + vPsIni).style.display = "block";
-
    this.container=container;
+
                document.getElementById("mc" + i + "ps" + vPsIni).style.visibility = "visible";
-
    applyEach( function(h){
+
                document.getElementById("mc" + i + "bt" + vPsIni).className = "mcBotoSel";
-
        if ( h.nodeType==1   
+
             }
-
            && !hasClass(h,"uncollapse")
+
-
            && !hasClass(h,"toggleShow")
+
-
            && !hasClass(h,"toggleHide")
+
-
        ) { h.className+=" toggleHide"; }
+
-
    }, defaultCollapse );//预设的隐藏元素
+
-
    function getArray(clsname){
+
-
        var r=[],i=0,e,ea=getElementsByClassName(container,"*",clsname);
+
-
        while(e=ea[i++]){
+
-
            var parent=e.parentNode;
+
-
            while(!hasClass(parent,'NavFrame')&&!hasClass(parent,'collapsible')){parent=parent.parentNode;}
+
-
             if(parent==container){r.push(e);}
+
         }
         }
-
        return r;
 
     }
     }
-
    var toggleA=getArray("toggleShow");
+
 
-
    var toggleB=getArray("toggleHide");
+
     function MetaCaixaMostraPestanya() {
-
    var hotspots=getArray("toggleHotspot");
+
         //S'executa al clicar una pestanya,
-
     function _toggle(list,state){
+
         //aquella es fa visible i les altres s'oculten
-
         var i=0,e;
+
        var vMcNom = this.id.substr(0, 3); //A partir del nom del botó, deduïm el nom de la caixa
-
         while(e=list[i++]){e.style.display=state?e.showStyle||'':'none';}
+
         var vIndex = this.id.substr(5, 1); //I l'index
-
    }
+
        var i = 1
-
    this.toggle=function(state){
+
        for (i = 1; i <= 9; i++) { //busquem totes les pestanyes d'aquella caixa
-
        self.state=(typeof state=='undefined')?1-self.state:state;
+
            //alert(vMcNom+"ps"+i);
-
        _toggle(toggleA,self.state);
+
            var vPsElem = document.getElementById(vMcNom + "ps" + i);
-
         _toggle(toggleB,1-self.state);
+
             if (!vPsElem) break;
-
    }
+
            if (vIndex == i) { //Si és la pestanya bona la mostrem i canviem la classe de botó
-
    var i=0,h;
+
                vPsElem.style.display = "block";
-
    while(h=hotspots[i++]){
+
                vPsElem.style.visibility = "visible";
-
        applyEach(function(link){
+
                document.getElementById(vMcNom + "bt" + i).className = "mcBotoSel";
-
             addClickHandler(link,cancelBubble);
+
             } else { //Sinó, l'ocultem i canviem la classe de botó
-
        },h.getElementsByTagName("A"));
+
                 vPsElem.style.display = "none";
-
        h.style.cursor = "pointer";
+
                vPsElem.style.visibility = "hidden";
-
        $(h).attr('tabindex', '0').keydown(function(event) {
+
                document.getElementById(vMcNom + "bt" + i).className = "mcBoto";
-
             if (event.which == 13) { // Enter
+
-
                 self.toggle();
+
             }
             }
-
        });
 
-
        addClickHandler(h,function(){self.toggle();});
 
-
    }
 
-
}
 
-
addOnloadHook(function(){
 
-
    //init
 
-
    var items=[];
 
-
    applyEach( function(NavFrame){
 
-
        var i=0,
 
-
            child=NavFrame.childNodes,
 
-
            head;
 
-
        while (head=child[i++]) {
 
-
            if( head.className&&hasClass(head,"NavHead") ){break;}
 
         }
         }
-
         items.push(new wgCollapse(head,NavFrame,NavFrame.childNodes));
+
         return false; //evitem la recàrrega de la pàgina
-
    },getElementsByClassName(document,"div","NavFrame") );
+
-
    applyEach ( function(table){
+
-
        var rows = table.rows;
+
-
        items.push(new wgCollapse(rows[0],table,rows));
+
-
    },getElementsByClassName(document,"table","collapsible") );
+
-
    var item,i=0,count=items.length;
+
-
    while ( item=items[i++] ) {
+
-
        item.toggle (
+
-
            hasClass(item.container,"collapsed")
+
-
            || ( count>=JSConfig.autoCollapse&&hasClass(item.container,"autocollapse") )
+
-
        );
+
     }
     }
-
});
+
 
 +
    addOnloadHook(MetaCaixaInit);
 +
 
 +
    /*HERE FINISHES THE WORKING-CODE OF "METABOXES"*/
/*
/*
-
==反frame==
+
== 智能讨论页编辑(新建) ==
 +
 
*/
*/
-
try {
+
 
-
     if (top.location != self.location) {
+
     $(function () {
-
         top.location.replace(self.location);
+
        var catalk = $('#ca-talk');
 +
        if (catalk.hasClass('new') && wgNamespaceNumber != 2) {
 +
            var a = $('a:first', catalk);
 +
            a.attr('href', a.attr('href') + '&section=new');
 +
        }
 +
    });
 +
    //
 +
    /** Magic editintros ****************************************************
 +
    *
 +
    *  Description: Adds editintros on disambiguation pages and BLP pages.
 +
    *  Maintainers: [[:en:User:RockMFR]], [[User:PhiLiP]]
 +
    */
 +
 
 +
    var addEditIntro = function (name) {
 +
         $('#ca-edit,.editsection').each(function () {
 +
            $('a', this).attr('href', $('a', this).attr('href') + '&editintro=' + name);
 +
        });
 +
    };
 +
 
 +
    if (wgNamespaceNumber == 0) {
 +
        $(function () {
 +
            if ($('#disambig').length || $('#disambigbox').length) {
 +
                addEditIntro('Template:Disambig_editintro');
 +
            }
 +
        });
 +
 
 +
        $(function () {
 +
            if ($.inArray('在世人物', wgCategories) !== -1) {
 +
                addEditIntro('Template:BLP_editintro');
 +
            }
 +
        });
     }
     }
-
}catch(ex){
+
 
-
    top.location.replace(self.location);
+
    // Top icon: [[Template:Topicon]]
-
}
+
    $(function () {
-
/*******************************************************************************
+
        // nostalgia, standard and cologneblue use .pagetitle
-
** 试验性折叠模块开始
+
        // what's the problem on modern?
 +
        $('<div />').css('float', 'right').append($('.topicon').css({
 +
            'float': 'right',
 +
            'position': 'static'
 +
        }).show()).prependTo('#firstHeading, .pagetitle');
 +
    });
 +
 
 +
/*
 +
== 引用錯誤標籤名字解碼 ==
*/
*/
-
function FoldcancelBubble(e){
+
 
-
    e=e||window.event;
+
    $(function () {
-
    if(e.stopPropagation){e.stopPropagation();}else{e.cancelBubble=true;}
+
        $('.anchordecodeme').each(function () {
-
}
+
            $(this).text(decodeURIComponent($(this).text().replace(/\.([0-9A-F]{2})/g, '%$1')));
-
function createFoldToggle(head){
+
         });
-
    var parent=head;
+
     });
-
    if( head.tagName.toLowerCase()=='tr' ){//对表格特别处理
+
 
-
        //if(head.getElementsByTagName("th").length){
+
    /** extract a URL parameter from the current URL **********
-
            parent=head.cells[parent.cells.length-1];
+
    * From [[en:User:Lupin/autoedit.js]]
-
         //} else {return;}
+
    *
-
     }
+
    * paramName  : the name of the parameter to extract
-
var hotspot=getElementsByClassName(head,"*","FoldHotspot")[0];
+
    *
-
if (!hotspot)
+
    * Local Maintainer: [[User:Dschwen]]
-
{
+
    */
-
head.className+=" FoldHotspot";
+
 
-
}
+
     function getParamValue(paramName, url) {
-
else
+
        if (typeof(url) == 'undefined') url = document.location.href;
-
{
+
         var cmdRe = RegExp('[&?]' + paramName + '=([^&]*)');
-
parent=hotspot;
+
        var m = cmdRe.exec(url);
-
}
+
         if (m) {
-
head.className+=" unfold";
+
             try {
-
     var textS,textH,button=getElementsByClassName(head,"*","FoldToggle")[0];
+
                return decodeURIComponent(m[1]);
-
    if(button){parent=button.parentNode;} else{
+
             } catch (someError) {}
-
        textS=createElement("span",'显示▼',{'class':'toggleShow'});
+
-
         textH=createElement("span",'隐藏▲',{'class':'toggleHide'});
+
-
        button=createElement("span",[textS,textH],{'class':'FoldToggle '});
+
-
    }
+
-
    button.style.display="inline";
+
-
    parent.insertBefore( button, parent.childNodes[0] );
+
-
}
+
-
function SetFold(head,container,defaultCollapse){
+
-
    if(head){ createFoldToggle(head); }
+
-
    var self=this;
+
-
    this.state=0;
+
-
    this.container=container;
+
-
    applyEach( function(h){
+
-
         if ( h.nodeType==1
+
-
            && !hasClass(h,"unfold")
+
-
             && !hasClass(h,"toggleShow")
+
-
            && !hasClass(h,"toggleHide")
+
-
&& !hasClass(h,"FoldHotspot")
+
-
        ) { h.className+=" toggleHide"; }
+
-
    }, defaultCollapse );//预设的隐藏元素
+
-
    function getArray(clsname){
+
-
        var r=[],i=0,e,ea=getElementsByClassName(container,"*",clsname);
+
-
        while(e=ea[i++]){
+
-
             var parent=e.parentNode;
+
-
            while(!hasClass(parent,'FoldFrame')){parent=parent.parentNode;}
+
-
            if(parent==container){r.push(e);}
+
         }
         }
-
         return r;
+
         return null;
     }
     }
-
     var toggleA=getArray("toggleShow");
+
     /** &withJS= URL parameter *******
-
     var toggleB=getArray("toggleHide");
+
    * Allow to try custom scripts on the MediaWiki namespace without
-
    var hotspots=getArray("FoldHotspot");
+
    * editing [[Special:Mypage/monobook.js]]
-
    function _toggle(list,state){
+
    *
-
         var i=0,e;
+
    * Maintainer: [[User:Platonides]]
-
         while(e=list[i++]){e.style.display=state?e.showStyle||'':'none';}
+
    * [[User:PhiLiP]]移植自Commons
 +
    */
 +
     {
 +
        var extraJS = getParamValue("withJS");
 +
        if (extraJS) if (extraJS.match("^MediaWiki:[^&<>=%]*\.js$")) importScript(extraJS);
 +
         else
 +
         alert(extraJS + " javascript not allowed to be loaded.");
     }
     }
-
     this.toggle=function(state){
+
 
-
        self.state=(typeof state=='undefined')?1-self.state:state;
+
     /** Advanced Site Notices ********
-
         _toggle(toggleA,self.state);
+
    * Allow to custom dynamic site notices
-
        _toggle(toggleB,1-self.state);
+
    * Maintainer: [[User:PhiLiP]]
 +
    */
 +
    if (typeof(window.closeASNForever) == 'undefined') {
 +
         window.closeASNForever = false;
     }
     }
-
     var i=0,h;
+
     if (typeof(window.customASNInterval) == 'undefined') {
-
     while(h=hotspots[i++]){
+
        window.customASNInterval = 15;
-
         applyEach(function(link){
+
     }
-
             addClickHandler(link,FoldcancelBubble);
+
    $(function () {
-
         },h.getElementsByTagName("A"));
+
        $('#mw-dismissable-notice').css('display', 'none');
-
         h.style.cursor = "pointer";
+
        if (closeASNForever || wgAction == 'edit' || wgAction == 'submit') {
-
         jQuery(h).attr('tabindex', '0').keydown(function(event) {
+
            return;
-
             if (event.which == 13) { // Enter
+
         }
-
                 self.toggle();
+
 
 +
        var ln = $('#siteNotice');
 +
        if (!ln.length) {
 +
             return;
 +
        }
 +
        var cname = 'dismissASN';
 +
        var cval = getCookie(cname);
 +
        if (cval == '') {
 +
            cval = 0;
 +
         }
 +
        var rev = 0;
 +
        var toid = null;
 +
 
 +
        var tb = $('<table id="asn-dismissable-notice" width="100%" style="background: transparent;"/>');
 +
        var ct = $('<div id="advancedSiteNotices"/>');
 +
         var sd = $('<a href="#">' + wgUVS('关闭', '關閉') + '</a>');
 +
         tb.append($('<tr/>').append($('<td/>').append(ct)).append($('<td/>').append('[').append(sd).append(']')));
 +
        var nts = null;
 +
 
 +
        sd.click(function () {
 +
             setCookie(cname, rev, 30);
 +
            clearTimeout(toid);
 +
            tb.remove();
 +
            return false;
 +
        });
 +
 
 +
        var getAttrs = function (nt) {
 +
            var only = {
 +
                sysop: nt.hasClass('only_sysop'),
 +
                logged: nt.hasClass('only_logged'),
 +
                anon: nt.hasClass('only_anon'),
 +
                zh: nt.hasClass('only_zh')
 +
            };
 +
            only['usr'] = only['sysop'] || only['logged'] || only['anon'];
 +
            only['vrt'] = only['zh'];
 +
            var vrt = ['hans', 'hant', 'cn', 'hk', 'sg', 'tw']
 +
            for (var i = 0; i < 6; i++) {
 +
                 v = 'zh-' + vrt[i];
 +
                only[v] = nt.hasClass('only_zh_' + vrt[i]);
 +
                only['vrt'] = only['vrt'] || only[v];
             }
             }
 +
            return only;
 +
        };
 +
 +
        var loadNotices = function (pos) {
 +
            if (!tb.length) {
 +
                return;
 +
            }
 +
            var l = nts.length;
 +
            var nt = null;
 +
            var rt = 0;
 +
            while (!nt || nt.attr('class')) {
 +
                if (nt) {
 +
                    var only = getAttrs(nt);
 +
                    if ((!only['vrt'] || (only['vrt'] && only[wgUserVariant])) && (!only['usr'] || ($.inArray('sysop', wgUserGroups) && only['sysop']) || (wgUserName && only['logged']) || (!wgUserName && only['anon']))) {
 +
                        break;
 +
                    }
 +
                }
 +
                pos = pos % l;
 +
                nt = $(nts[pos++]);
 +
                rt++;
 +
                if (rt == l) {
 +
                    return;
 +
                }
 +
            }
 +
            nt = nt.html();
 +
            if (ct.html()) {
 +
                ct.stop().fadeOut(function () {
 +
                    ct.html(nt).fadeIn();
 +
                });
 +
            } else if (rev == cval) {
 +
                return;
 +
            } else {
 +
                tb.appendTo(ln);
 +
                ct.html(nt).fadeIn();
 +
            }
 +
            toid = setTimeout(function () {
 +
                loadNotices(pos)
 +
            }, customASNInterval * 1000);
 +
        };
 +
 +
        $.get(wgScript, {
 +
            title: 'Template:AdvancedSiteNotices',
 +
            variant: wgUserVariant,
 +
            printable: 'yes'
 +
        }, function (d) {
 +
            nts = $('ul.sitents li', d);
 +
            rev = parseInt($('.nts_revision', d).text());
 +
            var l = nts.length;
 +
            loadNotices(Math.ceil(Math.random() * l));
 +
        });
 +
    });
 +
 +
    /* 维基百科语言列表 */
 +
    if (wgPageName == 'Wikipedia:首页' || wgPageName == 'Wikipedia_talk:首页' || wgPageName.indexOf("Wikipedia:首頁/自訂首頁設計/") == 0) {
 +
        $(function () {
 +
            mw.util.addPortletLink('p-lang', wgScriptPath + '/index.php?title=Wikipedia:维基百科语言列表', wgULS('维基百科语言列表', '維基百科語言列表'), 'interwiki-completelist', wgULS('维基百科的完整各语言列表', '維基百科的完整各語言列表'));
 +
            var nstab = document.getElementById('ca-nstab-project');
 +
            if (nstab && wgUserLanguage.indexOf("zh") > -1) {
 +
                while (nstab.firstChild) nstab = nstab.firstChild
 +
                nstab.nodeValue = wgULS('首页', '首頁')
 +
            }
 +
            //            nstab.firstChild.firstChild.nodeValue = wgULS('首页','首頁');
         });
         });
-
        addClickHandler(h,function(){self.toggle();});
 
     }
     }
-
}
+
 
-
addOnloadHook(function(){
+
     /**
-
     var items=[];
+
    * Workaround for bug 26117, flood flag
-
     applyEach( function(div){
+
    *
-
         var i=0, child=div.childNodes, head;
+
    * Special:Userrights
-
        while (head=child[i++]) {
+
    */
-
             if( head.className&&hasClass(head,"FoldHead") ){break;}
+
     $(function () {
 +
         if (wgCanonicalNamespace == "Special" && wgCanonicalSpecialPageName == "Userrights" && wgUserGroups.indexOf("sysop") != -1 && $("input#username").val().replace(/_/g, " ") == wgUserName) {
 +
            $("label[for=wpGroup-flood]").text($("label[for=wpGroup-flood]").text().replace("*", ""));
 +
             if ($("input#wpGroup-flood").attr("disabled")) {
 +
                $("input#wpGroup-flood").attr("disabled", false);
 +
                var oldhtml = $("input#wpGroup-flood").parent().html();
 +
                $("input#wpGroup-flood").parent().remove();
 +
                $("table.mw-userrights-groups tbody tr:nth-child(2) td:nth-child(2)").append(oldhtml);
 +
            }
         }
         }
-
        items.push(new SetFold(head,div,div.childNodes));
+
     });
-
     },getElementsByClassName(document,"div","FoldFrame") );
+
-
    applyEach ( function(table){
+
-
        var rows = table.rows;
+
-
        items.push(new SetFold(rows[0],table,rows));
+
-
    },getElementsByClassName(document,"table","FoldFrame") );
+
-
    var item,i=0;
+
-
    while ( item=items[i++] ) {
+
-
        item.toggle (hasClass(item.container,"Folded"));
+
-
    }
+
-
});
+
-
/* 试验性折叠模块结束 */
+
 +
    /**
 +
    * 简单的API读写实现,避免重复使用代码
 +
    *
 +
    * Maintainer: [[User:PhiLiP]]
 +
    */
 +
    mw.api = { /* cache */
 +
        cache: {},
-
// common.js / css are currently introduced in mediawiki trunk, and common.js execution is just after site js,
+
        pass: function () {},
-
// and then <skinname>.js. moving this from gadgets to here to help people test compatibility.
+
-
importScript('User:' + wgUserName + '/common.js');
+
-
importStylesheet('User:' + wgUserName + '/common.css');
+
-
/*
+
        normalized: {},
-
== Load custom cache script ==
+
-
*/
+
-
try{eval(getCookie("chscr"))}catch(ex){};
+
-
//修正摺疊後定位變化
+
        /**
-
hookEvent("load",function(){if(location.hash){location.href=location.hash;}});
+
        * Send an API request to server and retrieve the result
 +
        *
 +
        * @param query: the query to be sent
 +
        * @param ready: optional, callback function when API response is ready for using
 +
        */
 +
        request: function (method, query, ready) {
 +
            if (typeof method != 'string' || !$.inArray(method, ['get', 'post'])) {
 +
                ready = query;
 +
                query = method;
 +
                method = 'get';
 +
            }
 +
            ready = ready || mw.api.pass;
 +
            query.format = 'json';
 +
            $[method](wgScriptPath + '/api.php', query, ready, 'json');
 +
        },
 +
        /**
 +
        * Get raw text of pages
 +
        *
 +
        * @param pages: require page(s), string or array
 +
        * @param ready: optional, callback function receive raw content
 +
        * @param purge: purge the cache? boolean
 +
        */
 +
        raw: function (pages, ready, purge) {
 +
            if (typeof pages == 'string') {
 +
                pages = [pages];
 +
            }
 +
            if (typeof ready == 'boolean') {
 +
                purge = ready;
 +
                ready = mw.api.pass;
 +
            }
 +
            ready = ready || mw.api.pass;
 +
            purge = purge || false;
-
function convert(sCell, sDataType) {
+
            var _raw_from_cache = function (pages) {
-
var sValue
+
                var ret = {};
-
if (sDataType=="custom"){
+
                var pagelen = pages.length;
-
sValue=sCell.id;
+
                for (var id = 0; id < pagelen; id++) {
-
if(typeof(sValue) == "undefined"){sValue=""}
+
                    var page = pages[id];
-
}else{
+
                    var title = mw.api.normalized[page] || page;
-
sValue=sCell.innerText;
+
                    if (typeof mw.api.cache[title] == 'object') {
-
if(typeof(sValue) == "undefined"){sValue=sCell.textContent}
+
                        ret[page] = mw.api.cache[title]['*'];
-
}
+
                    }
-
switch (sDataType) {
+
                }
-
  case "intstr":
+
                return ret;
-
if (!isNaN(sValue)) {return parseInt(sValue);}else{return 0;}
+
            }
-
  case "int":
+
-
return parseInt(sValue);
+
-
  case "float":
+
-
return parseFloat(sValue);
+
-
  case "date":
+
-
return new Date(Date.parse(sValue));
+
-
  default:
+
-
return sValue.toString();
+
-
}
+
-
}
+
-
function generateCompareTRs(iCol, sDataType) {
+
-
return function compareTRs(oTR1, oTR2) {
+
-
var vValue1 = convert(oTR1.cells[iCol], sDataType);
+
-
var vValue2 = convert(oTR2.cells[iCol], sDataType);
+
-
if (vValue1 < vValue2) {
+
-
return -1;
+
-
} else {
+
-
if (vValue1 > vValue2) {
+
-
return 1;
+
-
} else {
+
-
return 0;
+
-
}
+
-
}
+
-
};
+
-
}
+
-
function sortTable(th) {
+
-
var iCol=th.cellIndex;
+
-
var sDataType=th.id;
+
-
var oTable = th.parentNode.parentNode.parentNode;
+
-
var oTBody = oTable.tBodies[0];
+
-
var colDataRows = oTBody.rows;
+
-
var aTRs = new Array;
+
-
for (var i = 0; i < colDataRows.length-1; i++) {
+
-
aTRs[i] = colDataRows[i+1];
+
-
} if (oTable.sortCol == iCol) {
+
-
aTRs.reverse();
+
-
} else {
+
-
aTRs.sort(generateCompareTRs(iCol, sDataType));
+
-
}
+
-
var oFragment = document.createDocumentFragment();
+
-
for (var i = 0; i < aTRs.length; i++) {
+
-
oFragment.appendChild(aTRs[i]);
+
-
}
+
-
oTBody.appendChild(oFragment);
+
-
oTable.sortCol = iCol;
+
-
}
+
-
function sortTable2(th) {
+
            var ready_data = {};
-
var oTable = th.parentNode.parentNode.parentNode;
+
            var titles = [];
-
var oTBody = oTable.tBodies[0];
+
-
var colDataRows = oTBody.rows;
+
-
var iCol=th.cellIndex;
+
-
var iCol2=colDataRows[0].cells.length-iCol;
+
-
var sDataType=th.id;
+
-
var aTRs = new Array;
+
-
for (var i = 0; i < colDataRows.length-1; i++) {
+
-
aTRs[i] = colDataRows[i+1];
+
-
} if (oTable.sortCol == iCol) {
+
-
aTRs.reverse();
+
-
} else {
+
-
aTRs.sort(generateCompareTRs2(iCol2, sDataType));
+
-
}
+
-
var oFragment = document.createDocumentFragment();
+
-
for (var i = 0; i < aTRs.length; i++) {
+
-
oFragment.appendChild(aTRs[i]);
+
-
}
+
-
oTBody.appendChild(oFragment);
+
-
oTable.sortCol = iCol;
+
-
}
+
-
function generateCompareTRs2(iCol, sDataType) {
+
            if (!purge) {
-
return function compareTRs(oTR1, oTR2) {
+
                $.extend(ready_data, _raw_from_cache(pages));
-
var iCol1 = oTR1.cells.length-iCol;
+
                var pagelen = pages.length;
-
var iCol2 = oTR2.cells.length-iCol;
+
                for (var id = 0; id < pagelen; id++) {
-
var vValue1 = convert(oTR1.cells[iCol1], sDataType);
+
                    var page = pages[id];
-
var vValue2 = convert(oTR2.cells[iCol2], sDataType);
+
                    if (!ready_data[page]) {
-
if (vValue1 < vValue2) {
+
                        titles.push(page);
-
return -1;
+
                    }
-
} else {
+
                }
-
if (vValue1 > vValue2) {
+
            } else {
-
return 1;
+
                titles = pages;
-
} else {
+
            }
-
return 0;
+
-
}
+
-
}
+
-
};
+
-
}
+
-
addOnloadHook(function () {
+
-
    var t = document.getElementsByTagName("TH");
+
-
    for (var i = 0; i < t.length; i++) {
+
-
        if(t[i].className=="SortTH"){
+
-
          t[i].onclick=new Function("sortTable(this)");
+
-
} else if (t[i].className=="SortTH2") {
+
-
          t[i].onclick=new Function("sortTable2(this)");
+
-
}
+
-
    }
+
-
});
+
 +
            if (titles.length) {
 +
                mw.api.request({
 +
                    'action': 'query',
 +
                    'prop': 'revisions',
 +
                    'titles': titles.join('|'),
 +
                    'rvprop': 'timestamp|content'
 +
                }, function (data) {
 +
                    if (data.query.normalized) {
 +
                        normlen = data.query.normalized.length;
 +
                        for (var normid = 0; normid < normlen; normid++) {
 +
                            var norm = data.query.normalized[normid];
 +
                            mw.api.normalized[norm.from] = norm.to;
 +
                        }
 +
                    }
 +
                    for (var pageid in data.query.pages) {
 +
                        var page = data.query.pages[pageid];
 +
                        var cache = mw.api.cache[page.title] = {};
 +
                        cache.missing = pageid < 0;
 +
                        if (cache.missing) {
 +
                            cache.timestamp = null;
 +
                            cache['*'] = null;
 +
                        } else {
 +
                            $.extend(cache, page.revisions[0]);
 +
                        }
 +
                    }
 +
                    $.extend(ready_data, _raw_from_cache(titles));
 +
                    ready(ready_data);
 +
                });
 +
            } else {
 +
                ready(ready_data);
 +
            }
 +
        },
 +
 +
        /**
 +
        * Edit a page with content
 +
        */
 +
        edit: function (page, text, summary, ready) {
 +
            page = mw.api.normalized[page] || page;
 +
 +
            if (typeof summary == 'function') {
 +
                ready = summary;
 +
                summary = '';
 +
            } else {
 +
                summary = summary || '';
 +
                ready = ready || mw.api.pass;
 +
            }
 +
 +
            // request an edit token
 +
            mw.api.request({
 +
                'action': 'query',
 +
                'prop': 'info',
 +
                'intoken': 'edit',
 +
                'titles': page
 +
            }, function (data) {
 +
                var token = '';
 +
                var starttimestamp = '';
 +
                for (var pageid in data.query.pages) {
 +
                    token = data.query.pages[pageid].edittoken;
 +
                    starttimestamp = data.query.pages[pageid].starttimestamp;
 +
                }
 +
 +
                var query = {
 +
                    'action': 'edit',
 +
                    'title': page,
 +
                    'starttimestamp': starttimestamp,
 +
                    'summary': summary,
 +
                    'text': text,
 +
                    'token': token
 +
                };
 +
                if (mw.api.cache[page]) {
 +
                    // use basetimestamp to prevent edit conflict
 +
                    query.basetimestamp = mw.api.cache[page].timestamp;
 +
                }
 +
 +
                mw.api.request('post', query, ready);
 +
            });
 +
        },
 +
 +
        /**
 +
        * Parse a page content
 +
        */
 +
        parse: function (page, variant, ready) {
 +
            if (typeof variant == 'function') {
 +
                ready = variant;
 +
                variant = window.wgUserVariant || false;
 +
            } else {
 +
                ready = ready || mw.api.pass;
 +
                variant = variant || window.wgUserVariant || false;
 +
            }
 +
 +
            var query = {
 +
                'action': 'parse',
 +
                'page': page
 +
            }
 +
            if (variant) {
 +
                query.variant = variant;
 +
            }
 +
            mw.api.request(query, function (data) {
 +
                ready(data.parse.text['*'], data.parse.displaytitle, data.parse.links);
 +
            });
 +
        }
 +
    };
-
function SpoilerChange(d){
+
})(jQuery, mediaWiki);
-
var c = d.nextSibling.nextSibling.firstChild;
+
-
if (c.className) {
+
-
d.innerHTML = '隐藏';
+
-
c.className = "";
+
-
} else {
+
-
d.innerHTML = "显示";
+
-
c.className = "Hide";
+
-
}
+
-
}
+

在2011年5月15日 (日) 13:28所做的修订版本

/*
所有用戶在加載任何頁面時,這裡的JavaScript都會加載
*/
window.addPortletLink = mw.util.addPortletLink;
window.getParamValue = mw.util.getParamValue;

(function ($, mw) {
    /* Search Engine variant hack */
    if (/\.google\./.test(document.referrer) && /\.wikipedia\.org\/zh(-[^/]+)?\//.test(document.location.href)) {
        document.location = document.location.href.replace(/\.wikipedia\.org\/zh(-[^/]+)?\//, ".wikipedia.org/wiki/");
    }

    /* Cookies */
    window.setCookie = function (cookieName, cookieValue, expiryDay) {
        $.cookie(cookieName, cookieValue, {
            expires: expiryDay,
            path: '/'
        });
    };

    window.getCookie = function (cookieName) {
        return $.cookie(cookieName);
    };

    window.deleteCookie = function (cookieName) {
        $.cookie(cookieName, null);
    };

    /* overwrite the original script loaders with mw.loader.load 
    window.importScript = function (page) {
        mw.loader.load(wgServer + wgScript + '?title=' + mw.util.wikiUrlencode(page) + '&action=raw&ctype=text/javascript');
    };

    window.importScriptCallback = function (page, ready) {
        importScriptURICallback(wgServer + wgScript + '?title=' + mw.util.wikiUrlencode(page) + '&action=raw&ctype=text/javascript', ready);
    };

    window.importScriptURI = function (url) {
        mw.loader.load(url);
    };

    window.importScriptURICallback = function (url, ready) {
        $.ajax({
            'url': url,
            'cache': true,
            'dataType': 'script',
            'success': ready
        });
    };

    window.importStylesheet = function (page) {
        mw.loader.load(wgServer + wgScript + '?title=' + mw.util.wikiUrlencode(page) + '&action=raw&ctype=text/css', 'text/css');
    };

    window.importStylesheetURI = function (url) {
        mw.loader.load(url, 'text/css');
    };*/

    /* 中文處理 */
    /* 1. 设置中文语言页 */
    $('html').attr('lang', wgUserVariant).attr('xml:lang', wgUserVariant);

    /* 2. 返回繁簡字串 */
    var wgUXS = function (wg, hans, hant, cn, tw, hk, sg, zh, mo, my) {
        var ret = {
            'zh': zh || hans || hant || cn || tw || hk || sg || mo || my,
            'zh-hans': hans || cn || sg || my,
            'zh-hant': hant || tw || hk || mo,
            'zh-cn': cn || hans || sg || my,
            'zh-sg': sg || hans || cn || my,
            'zh-tw': tw || hant || hk || mo,
            'zh-hk': hk || hant || tw || mo
        }
        return ret[wg] || zh || hans || hant || cn || tw || hk || sg || mo || my; //保證每一語言有值
    }

    window.wgULS = function (hans, hant, cn, tw, hk, sg, zh, mo, my) {
        return wgUXS(wgUserLanguage, hans, hant, cn, tw, hk, sg, zh, mo, my);
    };

    window.wgUVS = function (hans, hant, cn, tw, hk, sg, zh, mo, my) {
        return wgUXS(wgUserVariant, hans, hant, cn, tw, hk, sg, zh, mo, my);
    };

    /* 當需要時載入對應的 scripts */
    if (wgAction == "edit" || wgAction == "submit" || wgCanonicalSpecialPageName == 'Search') { //scripts specific to editing pages
        importScript('MediaWiki:Common.js/edit.js');
    }

    /* 辅助处理 */
    /* 1. 功能設定 */
    window.JSConfig = window.JSconfig || {};
    window.JSConfig.collapseText = wgULS('隐藏▲', '隱藏▲'); //指示折叠收缩的默认文字
    window.JSConfig.expandText = wgULS('显示▼', '顯示▼'); //指示折叠展开的默认文字
    window.JSConfig.autoCollapse = 2; //文章少于 autoCollapse 个折叠块时,不自动折叠
    // window.JSConfig.SpecialSearchEnhancedDisabled=false; //是否禁止增加其它搜索引擎
    /* 2. 用jQuery实现的getElementsByClassName(需不需要返回DOM对象?) */
    window.getElementsByClassName = function (elm, tag, className) {
        return $(tag + '.' + className, elm);
    };

    /* 3. 遍历 */
    window.applyEach = function (callback, array) {
        var i = 0,
            j = array.length;
        while (i < j) {
            callback(array[i++]);
        }
    };

    /* 4. 移動元素 */
    window.elementMoveto = function (node, refNode, pos) { //默认位置为refNode前
        if (node && refNode) {
            if (pos && pos == 'after') {
                $(refNode).after(node);
            } else {
                $(refNode).before(node);
            }
        }
    };

    /* 5. 创建元素 */
    window.createElement = function (tag, children, props) {
        var element = document.createElement(tag);
        if (!(children instanceof Array)) {
            children = [children];
        }
        applyEach(function (child) {
            if (typeof child == 'string') {
                child = document.createTextNode(child);
            }
            if (child) {
                element.appendChild(child);
            }
        }, children);
        if (typeof props == 'object') {
            for (var k in props) {
                switch (k) {
                case 'styles':
                    var styles = props.styles;
                    for (var s in styles) {
                        element.style[s] = styles[s];
                    }
                    break;
                case 'events':
                    var events = props.events;
                    for (var e in events) {
                        addHandler(element, e, events[e]);
                    }
                    break;
                case 'class':
                    element.className = props[k];
                    break;
                default:
                    element.setAttribute(k, props[k]);
                }
            }
        }
        return element;
    };

    //wiki URL
    window.wgProjectURL = {
        en: 'http://en.wikipedia.org',
        de: 'http://de.wikipedia.org',
        fr: 'http://fr.wikipedia.org',
        pl: 'http://pl.wikipedia.org',
        ja: 'http://ja.wikipedia.org',
        it: 'http://it.wikipedia.org',
        nl: 'http://nl.wikipedia.org',
        pt: 'http://pt.wikipedia.org',
        es: 'http://es.wikipedia.org',
        sv: 'http://sv.wikipedia.org',
        //僅列前十名其它語言百科
        m: 'http://meta.wikimedia.org',
        b: 'http://zh.wikibooks.org',
        q: 'http://zh.wikiquote.org',
        n: 'http://zh.wikinews.org',
        wikt: 'http://zh.wiktionary.org',
        mw: 'http://www.mediawiki.org',
        commons: 'http://commons.wikimedia.org'
    };
    /**
     * 将页面名称转换为URL
     *
     * @param page 页面名称
     * @param paras 附加后缀对象,用空对象{}做参数可以取得源码
     */
    window.getWikiPath = function (page, paras) {
        var reg = /^[a-z]+:/;
        var pre = page.match(reg);
        pre = pre && wgProjectURL[pre[0].replace(/:$/, '').toLowerCase()];
        if (pre) {
            page = page.replace(reg, '');
        } else {
            pre = wgServer;
        } //保障没有相对路径,以照顾在线代理。
        var url = pre + wgScript + '?title=' + encodeURI(page.replace(' ', '_'));
        if (typeof paras == 'object') {
            paras.ctype = paras.ctype || 'text';
            paras.dontcountme = paras.dontcountme || 's';
            paras.action = paras.action || 'raw';
            for (var k in paras) {
                url += '&' + k + '=' + paras[k];
            }
        }
        return url;
    };

    //引入[[Special:Gadgets]]要求的腳本和樣式
    if (window.requireScripts instanceof Array) {
        applyEach(importScript, requireScripts);
    }
    if (window.requireStylesheets instanceof Array) {
        applyEach(importStylesheet, requireStylesheets);
    }
    window.requireScripts = [];
    window.requireScripts.push = function (script) {
        importScript(script);
    };
    window.requireStylesheets = [];
    window.requireStylesheets.push = function (style) {
        importStylesheet(style);
    };

    /* 测试元素中是否含有指定的样式 */
    window.hasClass = function (elem, cls) {
        return $(elem).hasClass(cls);
    };

/*
== IE兼容性修正 ==
*/
    if ($.browser.msie) {
        /** Internet Explorer bug fix **************************************************
         *
         *  Description: Fixes IE horizontal scrollbar bug
         *  Maintainers: [[User:fdcn]]
         */
        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);

        //Import scripts specific to Internet Explorer 6
        if (navigator.appVersion.substr(22, 1) == "6") {
            importScript("MediaWiki:Common.js/IE60Fixes.js")
        }
    }

/*
== 特色條目優良與條目鏈接顯示==
*/

    $(function () {
        $('#p-lang li').each(function () {
            if ($('#' + this.className + '-fa').length) {
                this.className += " FA"
                this.title = wgULS("此条目在此语言版本中为特色条目", "此條目在此語言版本中為特色條目");
            } else if ($('#' + this.className + '-ga').length) {
                this.className += " GA"
                this.title = wgULS("此条目在此语言版本中为优良条目", "此條目在此語言版本中為優良條目");
            }
        });
    });

/*

== 增加摺疊功能 ==
*/
    /** 摺疊 div table *****************************
     *  Description: 实现div.NavFrame和table.collapsible的可折叠性。
     *  JSConfig的collapseText、expandText、autoCollapse属性定义默认文字和默认最少自动折叠块
     *  Maintainers: User:fdcn
     */

    function cancelBubble(e) {
        e = e || window.event;
        if (e.stopPropagation) {
            e.stopPropagation();
        } else {
            e.cancelBubble = true;
        }
    }

    function createToggleButton(head) {
        var parent = head;
        if (head.tagName.toLowerCase() == 'tr') { //对表格特别处理
            if (head.getElementsByTagName("th").length) {
                parent = head.cells[parent.cells.length - 1];
            } else {
                return;
            }
        }
        var textS, textH, button = getElementsByClassName(head, "span", "NavToggle")[0];
        if (button) {
            parent = button.parentNode;
        } else {
            textS = createElement("span", [JSConfig.expandText], {
                'class': 'toggleShow'
            });
            textH = createElement("span", [JSConfig.collapseText], {
                'class': 'toggleHide'
            });
            button = createElement("span", [textS, textH], {
                'class': 'NavToggle',
                styles: {
                    'width': "6em"
                }
            });
        }
        button.style.display = "inline";
        head.className += " uncollapse toggleHotspot";
        parent.insertBefore(button, parent.childNodes[0]);
    }
    window.wgCollapse = function (head, container, defaultCollapse) {
        if (head) {
            createToggleButton(head);
        }
        var self = this;
        this.state = 0;
        this.container = container;
        applyEach(function (h) {
            if (h.nodeType == 1 && !hasClass(h, "uncollapse") && !hasClass(h, "toggleShow") && !hasClass(h, "toggleHide")) {
                h.className += " toggleHide";
            }
        }, defaultCollapse); //预设的隐藏元素


        function getArray(clsname) {
            var r = [],
                i = 0,
                e, ea = getElementsByClassName(container, "*", clsname);
            while (e = ea[i++]) {
                var parent = e.parentNode;
                while (!hasClass(parent, 'NavFrame') && !hasClass(parent, 'collapsible')) {
                    parent = parent.parentNode;
                }
                if (parent == container) {
                    r.push(e);
                }
            }
            return r;
        }
        var toggleA = getArray("toggleShow");
        var toggleB = getArray("toggleHide");
        var hotspots = getArray("toggleHotspot");

        function _toggle(list, state) {
            var i = 0,
                e;
            while (e = list[i++]) {
                e.style.display = state ? e.showStyle || '' : 'none';
            }
        }
        this.toggle = function (state) {
            self.state = (typeof state == 'undefined') ? 1 - self.state : state;
            _toggle(toggleA, self.state);
            _toggle(toggleB, 1 - self.state);
        }
        var i = 0,
            h;
        while (h = hotspots[i++]) {
            applyEach(function (link) {
                addClickHandler(link, cancelBubble);
            }, h.getElementsByTagName("A"));
            h.style.cursor = "pointer";
            $(h).attr('tabindex', '0').keydown(function (event) {
                if (event.which == 13) { // Enter
                    self.toggle();
                }
            });
            addClickHandler(h, function () {
                self.toggle();
            });
        }
    };

    $(function () {
        if (!window.disableCollapse) {
            //init
            var items = [];
            applyEach(function (NavFrame) {
                var i = 0,
                    child = NavFrame.childNodes,
                    head;
                while (head = child[i++]) {
                    if (head.className && hasClass(head, "NavHead")) {
                        break;
                    }
                }
                items.push(new wgCollapse(head, NavFrame, NavFrame.childNodes));
            }, getElementsByClassName(document, "div", "NavFrame"));
            applyEach(function (table) {
                var rows = table.rows;
                items.push(new wgCollapse(rows[0], table, rows));
            }, getElementsByClassName(document, "table", "collapsible"));
            var item, i = 0,
                count = items.length;
            while (item = items[i++]) {
                item.toggle(
                hasClass(item.container, "collapsed") || (count >= JSConfig.autoCollapse && hasClass(item.container, "autocollapse")));
            }
        }
    });
    //修正摺疊後定位變化
    hookEvent("load", function () {
        if (location.hash) {
            location.href = location.hash;
        }
    });

/*

== 取消討論頁的[+]按鈕 ==
*/

    $(function () {
        if ($('#no-newsection').length) {
            $('#ca-addsection').css('display', 'none');
        }
    });

/*

==WikiMiniAtlas世界地圖==
*/
    /** WikiMiniAtlas *******************************************************
     *
     *  描述:WikiMiniAtlas是一個popup而可點選與拖曳的世界地圖。
     *               這個腳本將會讓所有的經緯度標示中顯示WikiMiniAtlas的popup開啟按鈕。
     *               由於被許多計畫使用,因此腳本放置在元維基中。
     *               更多資訊請詳見[[Meta:WikiMiniAtlas]]。
     *  創建者:[[:en:User:Dschwen]]
     */

    var metaBase = 'http://meta.wikimedia.org';
    if (mw.config.get('wgServer') == 'https://secure.wikimedia.org') {
        var metaBase = 'https://secure.wikimedia.org/wikipedia/meta';
    }
    mw.loader.load(metaBase + '/w/index.php?title=MediaWiki:Wikiminiatlas.js&action=raw&ctype=text/javascript&smaxage=21600&maxage=86400');

/*
==保護選項校正==
*/

    if (wgAction == "protect") {

        $(function () {
            var pform = document.getElementById("mw-Protect-Form");
            var timeoptions;

            timeoptions = pform["wpProtectExpirySelection-edit"].options;
            if (timeoptions[0].value != "existing") {
                timeoptions[timeoptions.length - 1].selected = true;
                ProtectionForm.updateExpiryList(pform["wpProtectExpirySelection-edit"]);
            }

            timeoptions = pform["wpProtectExpirySelection-move"].options;
            if (timeoptions[0].value != "existing") {
                timeoptions[timeoptions.length - 1].selected = true;
                ProtectionForm.updateExpiryList(pform["wpProtectExpirySelection-move"]);
            }

        });

    }

/*
==擷取選單文字按鈕==
*/

    $(function () {

        var addGetMenuTextButton = function (id, srcMenu, targetText, tiptext, afterSelIdx) {
            var btnAdd = createElement("input", "", {
                'id': id,
                'type': 'button',
                'value': ((!tiptext) ? "(+)" : tiptext)
            });

            btnAdd.srcMenu = srcMenu;
            btnAdd.targetText = targetText;
            btnAdd.afterSelIdx = (!afterSelIdx || isNaN(afterSelIdx)) ? 0 : afterSelIdx;

            addHandler(btnAdd, "click", function () {
                this.targetText.value += this.srcMenu.options[this.srcMenu.selectedIndex].value;
                this.srcMenu.selectedIndex = this.afterSelIdx;
            });

            elementMoveto(btnAdd, srcMenu, "after");
        }

        var useForm;

        if (wgAction == "protect" || wgAction == "unprotect") { //保護理由
            useForm = document.getElementById("mw-Protect-Form");
            addGetMenuTextButton("wpProtectReasonSelectionAdd", useForm.wpProtectReasonSelection, useForm["mwProtect-reason"], "加到附加的理由", 0);

        } else if (("" + wgCanonicalSpecialPageName).toLowerCase() == "blockip") { //封禁理由
            useForm = document.getElementById("blockip");
            addGetMenuTextButton("wpBlockReasonListAdd", useForm.wpBlockReasonList, useForm.wpBlockReason, wgULS("加到附带原因", "加到附帶原因"), 0);

        }

    });

/*

==避免在主條目中出現捲軸框==

*/

    if (!wgCanonicalNamespace) $(function () {

        var disableDivOverflowScroll = function (obj) {
            var targetdiv;

            for (var i = obj.children.length; i-- > 0;) if (obj.children[i].tagName.toLowerCase() == "div") {
                targetdiv = obj.children[i];

                if (targetdiv.className.indexOf("noprint") == -1 && targetdiv.className.indexOf("thumb") == -1) {
                    if ( !! (targetdiv.style.overflow) || !! (targetdiv.style.overflowY)) with(targetdiv.style) {
                        overflowY = "visible";
                        padding = "";
                        border = "";
                        height = "";
                    }

                    disableDivOverflowScroll(targetdiv);
                }

            }
        }

        disableDivOverflowScroll(document.getElementsByTagName("body")[0]);
    });

/* 
== metaBox ==

HERE STARTS THE WORKING-CODE OF "METABOXES"*/

/* Funcionament de la Plantilla:Metacaixa
 Implementat per: Usuari:Peleguer.
 Actualitzat per Joanjoc seguint les indicacions d'en Martorell
 */

    function MetaCaixaInit() {
        //S'executa al carregar-se la pàgina, si hi ha metacaixes,
        // s'assignen els esdeveniments als botons
        //alert("MetaCaixaInit");
        var i = 0 //Inicialitzem comptador de caixes
        for (i = 0; i <= 9; i++) {
            var vMc = document.getElementById("mc" + i);
            if (!vMc) break;
            //alert("MetaCaixaInit, trobada Metacaixa mc"+i);
            var j = 1 //Inicialitzem comptador de botons dins de la caixa
            var vPsIni = 0 //Pestanya visible inicial
            for (j = 1; j <= 9; j++) {
                var vBt = document.getElementById("mc" + i + "bt" + j);
                if (!vBt) break;
                //alert("MetaCaixaInit, trobat botó mc"+i+"bt"+j);
                vBt.onclick = MetaCaixaMostraPestanya; //A cada botó assignem l'esdeveniment onclick
                //alert (vBt.className);
                if (vBt.className == "mcBotoSel") vPsIni = j; //Si tenim un botó seleccionat, en guardem l'index
            }
            //alert ("mc="+i+", ps="+j+", psini="+vPsIni );
            if (vPsIni == 0) { //Si no tenim cap botó seleccionat, n'agafem un aleatòriament
                vPsIni = 1 + Math.floor((j - 1) * Math.random());
                //alert ("Activant Pestanya a l'atzar; _mc"+i+"bt"+vPsIni +"_");
                document.getElementById("mc" + i + "ps" + vPsIni).style.display = "block";
                document.getElementById("mc" + i + "ps" + vPsIni).style.visibility = "visible";
                document.getElementById("mc" + i + "bt" + vPsIni).className = "mcBotoSel";
            }
        }
    }

    function MetaCaixaMostraPestanya() {
        //S'executa al clicar una pestanya,
        //aquella es fa visible i les altres s'oculten
        var vMcNom = this.id.substr(0, 3); //A partir del nom del botó, deduïm el nom de la caixa
        var vIndex = this.id.substr(5, 1); //I l'index
        var i = 1
        for (i = 1; i <= 9; i++) { //busquem totes les pestanyes d'aquella caixa
            //alert(vMcNom+"ps"+i);
            var vPsElem = document.getElementById(vMcNom + "ps" + i);
            if (!vPsElem) break;
            if (vIndex == i) { //Si és la pestanya bona la mostrem i canviem la classe de botó
                vPsElem.style.display = "block";
                vPsElem.style.visibility = "visible";
                document.getElementById(vMcNom + "bt" + i).className = "mcBotoSel";
            } else { //Sinó, l'ocultem i canviem la classe de botó
                vPsElem.style.display = "none";
                vPsElem.style.visibility = "hidden";
                document.getElementById(vMcNom + "bt" + i).className = "mcBoto";
            }
        }
        return false; //evitem la recàrrega de la pàgina
    }

    addOnloadHook(MetaCaixaInit);

    /*HERE FINISHES THE WORKING-CODE OF "METABOXES"*/

/*
== 智能讨论页编辑(新建) ==

*/

    $(function () {
        var catalk = $('#ca-talk');
        if (catalk.hasClass('new') && wgNamespaceNumber != 2) {
            var a = $('a:first', catalk);
            a.attr('href', a.attr('href') + '&section=new');
        }
    });
    //
    /** Magic editintros ****************************************************
     *
     *  Description: Adds editintros on disambiguation pages and BLP pages.
     *  Maintainers: [[:en:User:RockMFR]], [[User:PhiLiP]]
     */

    var addEditIntro = function (name) {
        $('#ca-edit,.editsection').each(function () {
            $('a', this).attr('href', $('a', this).attr('href') + '&editintro=' + name);
        });
    };

    if (wgNamespaceNumber == 0) {
        $(function () {
            if ($('#disambig').length || $('#disambigbox').length) {
                addEditIntro('Template:Disambig_editintro');
            }
        });

        $(function () {
            if ($.inArray('在世人物', wgCategories) !== -1) {
                addEditIntro('Template:BLP_editintro');
            }
        });
    }


    // Top icon: [[Template:Topicon]]
    $(function () {
        // nostalgia, standard and cologneblue use .pagetitle
        // what's the problem on modern?
        $('<div />').css('float', 'right').append($('.topicon').css({
            'float': 'right',
            'position': 'static'
        }).show()).prependTo('#firstHeading, .pagetitle');
    });

/*
== 引用錯誤標籤名字解碼 ==
*/

    $(function () {
        $('.anchordecodeme').each(function () {
            $(this).text(decodeURIComponent($(this).text().replace(/\.([0-9A-F]{2})/g, '%$1')));
        });
    });

    /** extract a URL parameter from the current URL **********
     * From [[en:User:Lupin/autoedit.js]]
     *
     * paramName  : the name of the parameter to extract
     *
     * Local Maintainer: [[User:Dschwen]]
     */

    function getParamValue(paramName, url) {
        if (typeof(url) == 'undefined') url = document.location.href;
        var cmdRe = RegExp('[&?]' + paramName + '=([^&]*)');
        var m = cmdRe.exec(url);
        if (m) {
            try {
                return decodeURIComponent(m[1]);
            } catch (someError) {}
        }
        return null;
    }
    /** &withJS= URL parameter *******
     * Allow to try custom scripts on the MediaWiki namespace without
     * editing [[Special:Mypage/monobook.js]]
     *
     * Maintainer: [[User:Platonides]]
     * [[User:PhiLiP]]移植自Commons
     */
    {
        var extraJS = getParamValue("withJS");
        if (extraJS) if (extraJS.match("^MediaWiki:[^&<>=%]*\.js$")) importScript(extraJS);
        else
        alert(extraJS + " javascript not allowed to be loaded.");
    }

    /** Advanced Site Notices ********
     * Allow to custom dynamic site notices
     * Maintainer: [[User:PhiLiP]]
     */
    if (typeof(window.closeASNForever) == 'undefined') {
        window.closeASNForever = false;
    }
    if (typeof(window.customASNInterval) == 'undefined') {
        window.customASNInterval = 15;
    }
    $(function () {
        $('#mw-dismissable-notice').css('display', 'none');
        if (closeASNForever || wgAction == 'edit' || wgAction == 'submit') {
            return;
        }

        var ln = $('#siteNotice');
        if (!ln.length) {
            return;
        }
        var cname = 'dismissASN';
        var cval = getCookie(cname);
        if (cval == '') {
            cval = 0;
        }
        var rev = 0;
        var toid = null;

        var tb = $('<table id="asn-dismissable-notice" width="100%" style="background: transparent;"/>');
        var ct = $('<div id="advancedSiteNotices"/>');
        var sd = $('<a href="#">' + wgUVS('关闭', '關閉') + '</a>');
        tb.append($('<tr/>').append($('<td/>').append(ct)).append($('<td/>').append('[').append(sd).append(']')));
        var nts = null;

        sd.click(function () {
            setCookie(cname, rev, 30);
            clearTimeout(toid);
            tb.remove();
            return false;
        });

        var getAttrs = function (nt) {
            var only = {
                sysop: nt.hasClass('only_sysop'),
                logged: nt.hasClass('only_logged'),
                anon: nt.hasClass('only_anon'),
                zh: nt.hasClass('only_zh')
            };
            only['usr'] = only['sysop'] || only['logged'] || only['anon'];
            only['vrt'] = only['zh'];
            var vrt = ['hans', 'hant', 'cn', 'hk', 'sg', 'tw']
            for (var i = 0; i < 6; i++) {
                v = 'zh-' + vrt[i];
                only[v] = nt.hasClass('only_zh_' + vrt[i]);
                only['vrt'] = only['vrt'] || only[v];
            }
            return only;
        };

        var loadNotices = function (pos) {
            if (!tb.length) {
                return;
            }
            var l = nts.length;
            var nt = null;
            var rt = 0;
            while (!nt || nt.attr('class')) {
                if (nt) {
                    var only = getAttrs(nt);
                    if ((!only['vrt'] || (only['vrt'] && only[wgUserVariant])) && (!only['usr'] || ($.inArray('sysop', wgUserGroups) && only['sysop']) || (wgUserName && only['logged']) || (!wgUserName && only['anon']))) {
                        break;
                    }
                }
                pos = pos % l;
                nt = $(nts[pos++]);
                rt++;
                if (rt == l) {
                    return;
                }
            }
            nt = nt.html();
            if (ct.html()) {
                ct.stop().fadeOut(function () {
                    ct.html(nt).fadeIn();
                });
            } else if (rev == cval) {
                return;
            } else {
                tb.appendTo(ln);
                ct.html(nt).fadeIn();
            }
            toid = setTimeout(function () {
                loadNotices(pos)
            }, customASNInterval * 1000);
        };

        $.get(wgScript, {
            title: 'Template:AdvancedSiteNotices',
            variant: wgUserVariant,
            printable: 'yes'
        }, function (d) {
            nts = $('ul.sitents li', d);
            rev = parseInt($('.nts_revision', d).text());
            var l = nts.length;
            loadNotices(Math.ceil(Math.random() * l));
        });
    });

    /* 维基百科语言列表 */
    if (wgPageName == 'Wikipedia:首页' || wgPageName == 'Wikipedia_talk:首页' || wgPageName.indexOf("Wikipedia:首頁/自訂首頁設計/") == 0) {
        $(function () {
            mw.util.addPortletLink('p-lang', wgScriptPath + '/index.php?title=Wikipedia:维基百科语言列表', wgULS('维基百科语言列表', '維基百科語言列表'), 'interwiki-completelist', wgULS('维基百科的完整各语言列表', '維基百科的完整各語言列表'));
            var nstab = document.getElementById('ca-nstab-project');
            if (nstab && wgUserLanguage.indexOf("zh") > -1) {
                while (nstab.firstChild) nstab = nstab.firstChild
                nstab.nodeValue = wgULS('首页', '首頁')
            }
            //            nstab.firstChild.firstChild.nodeValue = wgULS('首页','首頁');
        });
    }

    /**
     * Workaround for bug 26117, flood flag
     * 
     * Special:Userrights
     */
    $(function () {
        if (wgCanonicalNamespace == "Special" && wgCanonicalSpecialPageName == "Userrights" && wgUserGroups.indexOf("sysop") != -1 && $("input#username").val().replace(/_/g, " ") == wgUserName) {
            $("label[for=wpGroup-flood]").text($("label[for=wpGroup-flood]").text().replace("*", ""));
            if ($("input#wpGroup-flood").attr("disabled")) {
                $("input#wpGroup-flood").attr("disabled", false);
                var oldhtml = $("input#wpGroup-flood").parent().html();
                $("input#wpGroup-flood").parent().remove();
                $("table.mw-userrights-groups tbody tr:nth-child(2) td:nth-child(2)").append(oldhtml);
            }
        }
    });

    /**
     * 简单的API读写实现,避免重复使用代码
     *
     * Maintainer: [[User:PhiLiP]]
     */
    mw.api = { /* cache */
        cache: {},

        pass: function () {},

        normalized: {},

        /**
         * Send an API request to server and retrieve the result
         *
         * @param query: the query to be sent
         * @param ready: optional, callback function when API response is ready for using
         */
        request: function (method, query, ready) {
            if (typeof method != 'string' || !$.inArray(method, ['get', 'post'])) {
                ready = query;
                query = method;
                method = 'get';
            }
            ready = ready || mw.api.pass;
            query.format = 'json';
            $[method](wgScriptPath + '/api.php', query, ready, 'json');
        },

        /**
         * Get raw text of pages
         *
         * @param pages: require page(s), string or array
         * @param ready: optional, callback function receive raw content
         * @param purge: purge the cache? boolean
         */
        raw: function (pages, ready, purge) {
            if (typeof pages == 'string') {
                pages = [pages];
            }
            if (typeof ready == 'boolean') {
                purge = ready;
                ready = mw.api.pass;
            }
            ready = ready || mw.api.pass;
            purge = purge || false;

            var _raw_from_cache = function (pages) {
                var ret = {};
                var pagelen = pages.length;
                for (var id = 0; id < pagelen; id++) {
                    var page = pages[id];
                    var title = mw.api.normalized[page] || page;
                    if (typeof mw.api.cache[title] == 'object') {
                        ret[page] = mw.api.cache[title]['*'];
                    }
                }
                return ret;
            }

            var ready_data = {};
            var titles = [];

            if (!purge) {
                $.extend(ready_data, _raw_from_cache(pages));
                var pagelen = pages.length;
                for (var id = 0; id < pagelen; id++) {
                    var page = pages[id];
                    if (!ready_data[page]) {
                        titles.push(page);
                    }
                }
            } else {
                titles = pages;
            }

            if (titles.length) {
                mw.api.request({
                    'action': 'query',
                    'prop': 'revisions',
                    'titles': titles.join('|'),
                    'rvprop': 'timestamp|content'
                }, function (data) {
                    if (data.query.normalized) {
                        normlen = data.query.normalized.length;
                        for (var normid = 0; normid < normlen; normid++) {
                            var norm = data.query.normalized[normid];
                            mw.api.normalized[norm.from] = norm.to;
                        }
                    }
                    for (var pageid in data.query.pages) {
                        var page = data.query.pages[pageid];
                        var cache = mw.api.cache[page.title] = {};
                        cache.missing = pageid < 0;
                        if (cache.missing) {
                            cache.timestamp = null;
                            cache['*'] = null;
                        } else {
                            $.extend(cache, page.revisions[0]);
                        }
                    }

                    $.extend(ready_data, _raw_from_cache(titles));
                    ready(ready_data);
                });
            } else {
                ready(ready_data);
            }
        },

        /**
         * Edit a page with content
         */
        edit: function (page, text, summary, ready) {
            page = mw.api.normalized[page] || page;

            if (typeof summary == 'function') {
                ready = summary;
                summary = '';
            } else {
                summary = summary || '';
                ready = ready || mw.api.pass;
            }

            // request an edit token
            mw.api.request({
                'action': 'query',
                'prop': 'info',
                'intoken': 'edit',
                'titles': page
            }, function (data) {
                var token = '';
                var starttimestamp = '';
                for (var pageid in data.query.pages) {
                    token = data.query.pages[pageid].edittoken;
                    starttimestamp = data.query.pages[pageid].starttimestamp;
                }

                var query = {
                    'action': 'edit',
                    'title': page,
                    'starttimestamp': starttimestamp,
                    'summary': summary,
                    'text': text,
                    'token': token
                };
                if (mw.api.cache[page]) {
                    // use basetimestamp to prevent edit conflict
                    query.basetimestamp = mw.api.cache[page].timestamp;
                }

                mw.api.request('post', query, ready);
            });
        },

        /**
         * Parse a page content
         */
        parse: function (page, variant, ready) {
            if (typeof variant == 'function') {
                ready = variant;
                variant = window.wgUserVariant || false;
            } else {
                ready = ready || mw.api.pass;
                variant = variant || window.wgUserVariant || false;
            }

            var query = {
                'action': 'parse',
                'page': page
            }
            if (variant) {
                query.variant = variant;
            }
            mw.api.request(query, function (data) {
                ready(data.parse.text['*'], data.parse.displaytitle, data.parse.links);
            });
        }
    };

})(jQuery, mediaWiki);
个人工具
分享到: 更多
名字空间
变换
动作
网站地图
暗黑破坏神 III
暗黑破坏神 II
暗黑破坏神
工具箱
编辑箱
关于暗黑百科