Difference between revisions of "MediaWiki:Common.js"

m
m
Line 1: Line 1:
 +
// Google Adsense
 +
$(function () {
 +
  $('#mw-advert').html('<script data-ad-client="ca-pub-6349531755061641" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>');
 +
}());
 +
 
// <nowiki>
 
// <nowiki>
 
/* globals $, mw, uix, XenForo */
 
/* globals $, mw, uix, XenForo */

Revision as of 09:32, 15 December 2019

// Google Adsense 
$(function () {
  $('#mw-advert').html('<script data-ad-client="ca-pub-6349531755061641" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>');
}());

// <nowiki>
/* globals $, mw, uix, XenForo */
(function() {
    "use strict";

    var namespace = window.namespace = mw.config.get('wgCanonicalNamespace');
    var action = window.action = mw.config.values.wgAction;

    /* Add a class to allow per-theme styling of the wiki. */
    var theme;
    if (typeof uix === 'undefined') {
        theme = $("dt:contains('Style')").next().find('a').text();
    } else {
        theme = uix.user.themeName;
    }
    $('#mw-content-text').addClass('w' + theme.replace(/\s/g, ''));

    /* Add a class to allow per-namespace styling of the wiki. */
    $('#mw-content-text').addClass('wNamespace' + namespace);

    /* Fix broken mail and alert popups while on the wiki */
    XenForo.ExtLoader = function(f) {
        return function() {
            try {
                f.apply(this, arguments);
            } catch (e) {
                var mailreq = 'https://www.stratics.com/conversations/popup?_xfRequestUri=%2F&_xfNoRedirect=1&_xfResponseType=json&_xfToken=' + $('input[name=_xfToken]:first').attr('value');
                $.getJSON(mailreq, function(data) {
                    $('#ConversationsMenu .listPlaceholder').empty().html(data.templateHtml);
                });
                var alertreq = 'https://www.stratics.com/conversations/alerts-popup?_xfRequestUri=%2F&_xfNoRedirect=1&_xfResponseType=json&_xfToken=' + $('input[name=_xfToken]:first').attr('value');
                $.getJSON(alertreq, function(data) {
                    $('#AlertsMenu .listPlaceholder').empty().html(data.templateHtml);
                });
            }
        };
    }(XenForo.ExtLoader);

    /* Fix TOC anchor scrolling (Xenforo breaks it otherwise).  */
    $('.toclevel-1, .toclevel-2, .toclevel-3, .toclevel-4, .toclevel-5').on('click', function(e) {
        e.preventDefault();

        var $target = $(document.location.hash.replace(/[–-]/,'E2.80.93').replace(',','2C'));

        $('html, body').stop()
            .animate({
                'scrollTop': $target.offset().top - 100
            }, 500, 'swing', function() {
                window.location.hash = target;
            });
    });

    /* Create a common namespace for stratics wiki js */
    (function() {
        var temp = {
            data: {},
            f: {
                atlas: {
                    ui: {}
                },
                util: {
                    /* Get the current time. */
                    getTime: function() {
                        var j;
                        var now = new Date(),
                            time = [now.getHours(), now.getMinutes(), now.getSeconds()],
                            suffix = time[0] < 12 ? "AM" : "PM";
                        for (j = 1; 3 > j; j++) {
                            time[j] = ('0' + time[j]).slice(-2);
                        }
                        return [time.join(":"), ' ', suffix].join('');
                    },
                    makehtml: function(type, obj, text) {
                        var str = "<" + type,
                            key;
                        for (key in obj) {
                            if (obj.hasOwnProperty(key)) {
                                str += ' ' + key + '="' + obj[key] + '"';
                            }
                        }
                        return str + ('input' === type ? '' : '>') + ("input" === type ? '/>' + (undefined === text ? '' : text) :
                            (undefined === text ? '' : text) + '</' + type + '>');
                    },
                    reloadPage: function() {
                        location.reload();
                    }
                },
                wiki: {
                    api: new mw.Api(),
                    /* Retrieves the wiki markup for a page; defaults to the current page. */
                    getMarkup: function(page) {
                        var getPage = function(callback, page) {
                            $.get('https://www.stratics.com/w/api.php?action=query&prop=revisions&rvprop=content&format=json&formatversion=2&titles=' + page, function(data) {
                                callback.apply(data);
                            });
                        };
                        getPage(function() {
                        /* Allow scripts to be cached. */
                            $.ajaxSetup({
                                cache: false
                            });
                            stratics.wiki.markup = this.query.pages[0].revisions[0].content;
                            $('body').trigger('markupArrived');
                        }, page || mw.config.get("wgPageName"));
                    },
                    /* Submits a markup edit to the server */
                    submitMarkup: function(summary, content) {
                        stratics.f.wiki.api.postWithToken("edit", {
                            action: "edit",
                            title: mw.config.get("wgPageName"),
                            summary: summary,
                            text: content
                        }).done(function(result, jqXHR) {
                            mw.log("Saved successfully");
                            $('body').trigger('submitMarkupSuccess');
                        }).fail(function(code, result) {
                            if (code === "http") {
                                mw.log("HTTP error: " + result.textStatus); // result.xhr contains the jqXHR object
                            } else if (code === "ok-but-empty") {
                                mw.log("Got an empty response from the server");
                            } else {
                                mw.log("API error: " + code);
                            }
                            $('body').trigger('submitMarkupFailure');
                        });
                    }
                }
            },
            keycodes: {
                27: 'ESC',
                33: 'NE',
                34: 'SE',
                35: 'SW',
                36: 'NW',
                37: 'W',
                38: 'N',
                39: 'E',
                40: 'S'
            },
            wiki: {
                markup: '',
                openEdits: []
            }
        };

        window.stratics = $.extend(true, (undefined === window.stratics) ? {} : window.stratics, temp); // Avoid clobbering any existing window.stratics object.
    })(window);

    /* Tests if an element is visible on the screen. */
    $.fn.isOnScreen = function() {
        var element = this.get(0);
        var bounds = element.getBoundingClientRect();
        return bounds.top < window.innerHeight && bounds.bottom > 0;
    };

    /* Returns the scale transform value for an element. */
    $.fn.getScale = function() {
        var vals = this.css('transform');
        return (vals == 'none') ? 1 : vals.split('(')[1].split(')')[0].split(',')[0];
    };

    /* Returns an array of the 4 inset values for an element. */
    $.fn.getInsets = function() {
        var vals = this.css('clip-path');
        if (vals == 'none') {
            vals = this.css('-webkit-clip-path');
        }
        return vals.split('(')[1].split(')')[0].split(/px\s?/);
    };

    /* Sort the options within a select alphabetically */
    $.fn.sortOptions = function() {
        var optionList = this.find('option')
            .sort(function(a, b) {
                return (a.text > b.text ? 1 : (a.text < b.text ? -1 : 0));
            });
        return this.empty()
            .append(optionList);
    };

    $.fn.extend({
        /* Allow changing tip text */
        changeTip: function (newText) {
            return this.each(function() {
                var $e = $(this).find('.tooltipstered');
                $e.data($e.data('tooltipster-ns')[0]).Content[0].innerText = newText;
            });
        },
        /* Allow retrieving tip text */
        getTip: function (newText) {
            return this.data(this.data('tooltipster-ns')[0]).Content[0].innerText;
        },

        /* Add visibility equivalents to show/hide/toggle */
        vis: function() {
            return this.each(function() {
                $(this).css("visibility", "visible");
            });
        },
        invis: function() {
            return this.each(function() {
                $(this).css("visibility", "hidden");
            });
        },
        toggleVis: function() {
            return this.each(function() {
                $(this).css("visibility", function(b, a) {
                    return "visible" == a ? "hidden" : "visible";
                });
            });
        }
    });

    /* HTML construction helper function */
    var makehtml = window.makehtml = function(type, o, text) {
        var i = '<' + type;
        for (var key in o) {
            if (o.hasOwnProperty(key)) {
                i += ' ' + key + '="' + o[key] + '"';
            }
        }
        i += (type === 'input') ? '' : '>';
        i += (type === 'input') ? '/>' + (text || '') : (text || '') + '</' + type + '>';
        return i;
    };

    /* Add jQuery UI css */
    var addjQueryCSS = function() {
        $('head').append(makehtml('link', {
            rel: 'stylesheet',
            type: 'text/css',
            href: 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/ui-darkness/jquery-ui.min.css'
        }));

        /* Workaround for jQuery UI/Xenforo/Mediawiki css conflict */
        $('head').append(makehtml('style', {}, 'body .ui-dialog .ui-widget-header,body .ui-button {background:#333!important}'));

        /* Add jQuery UI styling for input[type=number] */
        $('head').append(makehtml('style', {}, 'input[type=number] {font-size: 13px;font-family: \'Open Sans\',Arial,sans-serif;color: rgb(207, 207, 207);background-color: #101010;padding: 5px 10px;margin-bottom: 2px;border: 1px solid #383838;-webkit-border-radius: 2px;-moz-border-radius: 2px;-khtml-border-radius: 2px;border-radius: 2px;outline: 0;-webkit-box-sizing: border-box;-moz-box-sizing: border-box;-ms-box-sizing: border-box;box-sizing: border-box;min-height: 30}'));
    };

    /* Start: collapsible navboxes */

    $('.navbox-inner:gt(0)').each(function () {
        $(this)[$(this).hasClass('expanded') ? 'removeClass' : 'addClass']('mw-collapsed');
    });
    $('.navbox-inner').makeCollapsible();

    /* End: collapsible navboxes */

    /* Start Item Editor */

    if (action === 'edit' && (namespace === 'UO' || namespace === 'User')) {

        addjQueryCSS();

        /* Load properties JSON */
        $.getScript('/w/index.php?title=MediaWiki:PropertyBuilder.js&action=raw&ctype=text/javascript&1.0.1').complete(function() {

            /* Load jQuery UI */
            mw.loader.using(['jquery.ui.button', 'jquery.ui.tabs', 'jquery.ui.dialog'], function() {

                /* Load Editor */
                $.getScript('/w/index.php?title=MediaWiki:PropertyEditor.js&action=raw&ctype=text/javascript&1.0.0', function() {
                    loadEditor();
                });
            });
        });
    }

    /* End Item Editor  */

    /* Start Atlas Tools */

    if (/^UO\:Atlas/.test(mw.config.values.wgPageName) && namespace === 'UO' && $('.map-holder').length > 0) { /* Only run on UO Atlas pages which have a map present. */

        addjQueryCSS();

        /* Load jQuery UI */
        mw.loader.using(['jquery.ui.button', 'jquery.ui.tabs', 'jquery.ui.dialog'], function() {

            /* Load Editor */
            $.getScript('/w/index.php?title=MediaWiki:AtlasTools.js&action=raw&ctype=text/javascript');
        });
    }

    /* End Atlas Tools */

    /* Start Hunter's Guide scripts */

    if ($('a[title="Category:UO:Mobile"]').length > 0) {

        /* Block clicks to the edit tab as early as possible. */
        $('a[accesskey="e"]').click(function(e) {
            e.preventDefault();
            $('body').data('editClicked', true);
            return false;
        });

        /* Allow scripts to be cached. */
        $.ajaxSetup({
            cache: true
        });

        addjQueryCSS();

        /* Load jQuery UI */
        mw.loader.using(['jquery.ui.button', 'jquery.ui.tabs', 'jquery.ui.dialog', 'jquery.ui.selectable'], function() {

            /* Load jQuery UI selectmenu */
            $.getScript('https://cdn.rawgit.com/jquery/jquery-ui/master/ui/widgets/selectmenu.js').complete(function() {

                /* Load Localization */
                $.getScript('/w/index.php?title=MediaWiki:Localization.js&action=raw&ctype=text/javascript&1.0.5').complete(function() {

                    /* Load Mob Editor */
                    $.getScript('/w/index.php?title=MediaWiki:Mob%20Editor.js&action=raw&ctype=text/javascript&1.1.6');

                    /* Load Animal Lore Editor */
                    $.getScript('/w/index.php?title=MediaWiki:AnimalLoreTool.js&action=raw&ctype=text/javascript&1.2.23');

                });
            });

            /* Load OrgChart generator script */
            $.getScript('/w/index.php?title=MediaWiki:Orgchart.js&action=raw&ctype=text/javascript&1.0.0').complete(function() {

                /* Load Mob taxonomy data */
                $.getScript('/w/index.php?title=MediaWiki:MobData.js&action=raw&ctype=text/javascript&1.0.8').complete(function() {

                    /* Load Taxonomy chart builder */
                    $.getScript('/w/index.php?title=MediaWiki:MobTaxonomy.js&action=raw&ctype=text/javascript&1.0.1').complete(function() {

                    });
                });
            });
        });
    }

    /* Add quick links to the Hunter's Guide main page. */
    if (/\?title=UO:Hunter%27s_Guide/.test(location.search)) {
        $.getScript('/w/index.php?title=MediaWiki:AddQuickLinks.js&action=raw&ctype=text/javascript&1.0.0');
    }

   /* End Hunter's Guide scripts */

    /* Start crafter table script */

    if ($('table.crafteditems').length > 0) {
        /* Load StupidTable plugin */
        $.getScript('/w/index.php?title=MediaWiki:Stupidtable.min.js&action=raw&ctype=text/javascript&1.0.0').complete(function() {

            // This next works around the fact that mediawiki doesn't build proper HTML for tables.
            $('.crafteditems:not(.nosort)').each(function () {
                var th, trs, $this = $(this);
                th = $this.find('tr:first').detach();
                trs = $this.find('tr').detach();
                $this.empty()
                $this.append('<thead></thead><tbody></tbody>');
                $this.find('thead').append(th);
                $this.find('tbody').append(trs);
            });

            // Init stupidtable
            $('table.crafteditems').stupidtable();
            setTimeout(function(){ 
                $('.craftablecategory').click();
            }, 1);

        });
    }

   /* End crafter table scripts */

    /* Allow comining DPL results that need to be broken into multiple queries (ie, mobiles). */
    $('.mergetablefrom').find('th').parent().remove();
    $('.mergetableto').append($('.mergetablefrom').find('tr').detach());
    $('.mergetablefrom').remove();

}());  
// </nowiki>